branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<repo_name>ManishPaneri/School_Hostel_Assignment<file_sep>/src/main/java/school/Student.java package school; import java.util.Objects; public class Student { private String rollNumber; private Classes classes; private String foodPreference; public Student(String rollNumber, Classes classes, String foodPreference){ this.rollNumber = rollNumber; this.classes = classes; this.foodPreference = foodPreference; } public String getRollNumber() { return rollNumber; } public Classes getClasses() { return classes; } public String getFoodPreference() { return foodPreference; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Student student = (Student) o; return Objects.equals(rollNumber, student.rollNumber); } @Override public int hashCode() { return Objects.hash(rollNumber); } } <file_sep>/src/main/java/school/Classes.java package school; import java.util.Objects; public class Classes { private String className; public Classes(String name){ this.className = name; } public String getClassName() { return className; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Classes classes = (Classes) o; return Objects.equals(className, classes.className); } @Override public int hashCode() { return Objects.hash(className); } } <file_sep>/src/test/java/school/TestStudent.java package school; import org.junit.Assert; import org.junit.Test; public class TestStudent { @Test public void NullCheckStudent(){ Student student = new Student(null, null, null); Assert.assertNotNull(student); Assert.assertNull(student.getRollNumber()); Assert.assertNull(student.getClasses()); Assert.assertNull(student.getFoodPreference()); } @Test public void ValidStudentTestCase(){ Classes A = new Classes("A"); String rollNumber = "1"; Student student = new Student(rollNumber, A, FoodPreference.V.name()); Assert.assertNotNull(student); Assert.assertEquals(rollNumber, student.getRollNumber()); Assert.assertEquals(A, student.getClasses()); Assert.assertEquals(FoodPreference.V.name(), student.getFoodPreference()); } }
a51daed979ad275ae68da6f49d2025b8e7769dae
[ "Java" ]
3
Java
ManishPaneri/School_Hostel_Assignment
9243af9799e04d2513290bd1e5f590e4f673ebf0
df8da35ef1eda69877623e9b1dff0752b5b043d4
refs/heads/master
<repo_name>Sensoe/2048<file_sep>/save.c #include <math.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <time.h> #include "2048.h" /*! * * Fonction créant un repertoire pour stocker les sauvegardes. */ void makeSave() { printf("Creation du repertoire de sauvegardes :\n"); if (system("mkdir saves") == 0) printf("Le dossier a bien ete cree dans votre repertoire courant.\n\n\n"); else printf("Impossible donc de creer le dossier dans votre repertoire courant.\n\n\n"); } /*! * * Fonction sauvegardant la partie en cours * * * * \param p : pointeur sur la partie courante à sauvegarder * * * * Retourne 0 en cas de problème, 1 sinon */ int save_game(struct partie *p) { FILE *save = NULL, *saveD = NULL; char nomSav[TAILLE_CH] = "saves/"; char nomChoix[TAILLE_CH] = { '\0' }; printf("Veuillez donner un nom a la sauvegarde : "); do{ scanf("%s", nomChoix); if (verificationSave(nomChoix) == 0) printf("Ce nom n'est pas valide, veuillez entrer des caracteres alphanumeriques.\n"); } while (verificationSave(nomChoix) == 0); strcat(nomChoix, ".ygreg"); strcat(nomSav, nomChoix); save = fopen(nomSav, "wb"); saveD = fopen("saves/index.rolex", "ab"); if (save != NULL && saveD != NULL && p != NULL) { fwrite(p, sizeof(struct partie), 1, save); fclose(save); fwrite(nomSav, sizeof(char), TAILLE_CH, saveD); fclose(saveD); return 1; } return 0; } /*! * * Fonction chargeant la partie sauvegardée choisie. * * * * \param p : adresse du pointeur sur la partie à charger * * * * Retourne 0 en case de problème, 1 sinon */ int load_game(struct partie *p) { FILE *save = NULL, *saveD = NULL; int i = 1, j; char nomSav[TAILLE_CH] = { '\0' }; saveD = fopen("saves/index.rolex", "rb"); if (saveD != NULL) { printf("\nListe des sauvegardes disponibles :"); while (fread(nomSav, sizeof(char), TAILLE_CH, saveD) != 0) { printf("\n%d - %s", i, nomSav + 6); i++; } printf("\n\nQuelle sauvegarde souhaitez vous charger ? Entrez son numero : "); do{ scanf("%d", &j); } while (j>i); rewind(saveD); for (i = 1; i <= j; i++) fread(nomSav, sizeof(char), TAILLE_CH, saveD); printf("\n%s chargee!\n", nomSav + 6); fclose(saveD); } save = fopen(nomSav, "rb"); if (save != NULL && p != NULL) { fread(p, sizeof(struct partie), 1, save); fclose(save); return 1; } return 0; } /*! * Fonction affichant le menu (si p!=NULL, on permet de reprendre une partie et de sauvegarder la partie) * * \param p : pointeur sur la partie courante. * Valeur de retour : * 0 si les joueurs veulent quitter le jeu, * 1 s’ils veulent commencer une nouvelle partie, * 2 s’ils veulent charger la dernière partie sauvegardée, * 3 s’ils veulent sauvegarder la partie courante, * 4 s’ils veulent reprendre la partie courante. */ int menu(struct partie *p) { int choix; printf(" ------------------------------------------------------------------------------\n"); printf(" ... ... \n"); printf(" / \\\\\\ /// \\ \n"); printf(" ( ))) 2048 ((( ) \n"); printf(" \\ /// (4x4) \\\\\\ / \n"); printf("\n ------------------------------------------------------------------------------\n"); do{ printf("\n\nQue souhaitez-vous faire ?\n0 - Quitter\n1 - Nouvelle Partie\n2 - Charger une sauvegarde\n"); if (p != NULL) printf("3 - Sauvegarder la partie en cours\n4 - Retour au jeu en cours\n"); scanf("%d", &choix); if (choix<QUIT_GAME || (choix>SAVE_GAME && p == NULL) || choix>RESUME_GAME) printf("\nVotre saisie est invalide, veuillez entrer une des options proposees.\n"); } while (choix<0 || (choix>2 && p == NULL) || choix>4); return choix; } <file_sep>/menu.c #include <math.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <time.h> #include "2048.h" /*! * Retourne 1 si la case est vide, 0 sinon */ int empty_slot (game *p, int line, int column){ return (get_value(p, line, column)==0); } /*! * Ajoute une valeur (2 ou 4 choisi aléatoirement) sur une case vide * (elle aussi choisie aléatoirement). */ void set_random_value (game *p){ int *free_slots[p->free_slots]; int slot, val, dim = (p->n), empty = 0; srand(time(NULL)); /* * On parcourt tout le plateau de jeu pour identifier les cases vides. * Des qu'une case vaut 0 on stocke son adresse dans le tableau de pointeurs sur entier free_slots. * Ce tableau contient donc l'adresse de chacune des cases vides a la sortie de la boucle. */ for(slot=0; slot<(dim*dim); slot++){ if(get_value(p, slot/dim, slot%dim)==0){ free_slots[empty++] = &(p->grid[(dim*(slot/dim))+slot%dim]); } } /* * Si l'on a au moins une case de libre, on ajoute une valeur aleatoirement. * La case a remplir est tiree au hasard parmis les indices possibles de free_slots[] et on y accede directement grace a son adresse stockee dans ce tableau. * Enfin on diminue de 1 le nombre de cases vides. */ if(p->free_slots>0){ val = ((rand()%2)+1)*2; slot = rand()%(p->free_slots); *free_slots[slot] = val; (p->free_slots)--; } } /*! * Retourne 1 si la partie est gagnée, 0 sinon. */ int victory (game *p){ int slot = 0, dim = p->n; do{ if(get_value(p, slot/dim, slot%dim)==(p->max_value)){ return 1; } }while (++slot<(dim*dim)); return 0; } /*! * Retourne 1 si la partie est perdue, 0 sinon. */ int defeat (game*p){ int line, column, val, slot = 0, dim = p->n, limit = (dim*dim)-1; if(p->free_slots == 0){ do{ line = slot/dim, column = slot%dim, val = get_value(p, line, column); if(((val == get_value(p, line+1, column) && line != (dim-1)) || (val == get_value(p, line, column+1) && column != (dim-1))) && val != 0){ return 0; } }while(++slot<limit); } return (p->free_slots==0); } /*! * Retourne 1 si la partie est terminée, 0 sinon. */ int game_over (game*p){ return (victory(p) || defeat(p)); }<file_sep>/2048.c #include <math.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <time.h> #include "2048.h" int main(){ int exit, check, end; game *p=NULL; makeSave(); do{ exit = menu(p); if (exit == NEW_GAME) { p=init_game(4, 2048); set_random_value(p); set_random_value(p); check=1; } else if (exit == LOAD_GAME) { p = calloc(sizeof(game), 1); check = load_game(p); } else if (exit == SAVE_GAME) check = save_game(p); if (exit != QUIT_GAME && check != 0 && p != NULL) { end = play(p); if (end == 1) { if (defeat(p) == 1) { printf("Vous avez perdu.\n"); } else { printf("Vous avez gagné!\n"); } free_memory(p); p = NULL; } } else if (check == 0 && p != NULL) { if (exit == LOAD_GAME) printf("\nImpossible de charger la partie comme demande.\nFin du programme.\n"); else if (exit == SAVE_GAME) printf("\nImpossible de sauvegarder la partie comme demande.\nFin du programme.\n"); } } while (exit != QUIT_GAME && check != 0); return 0; } <file_sep>/makefile all: 2048 2048: 2048.o jeu.o organisation.o save.o menu.o terminalCouleur.o saisieM.o gcc 2048.o jeu.o organisation.o save.o menu.o terminalCouleur.o -o 2048 -lm 2048.o: 2048.c 2048.h gcc -c 2048.c -o 2048.o saisieM.o: saisieM.c 2048.h saisieM.h gcc -c saisieM.c -o saisieM.o jeu.o: jeu.c 2048.h saisieM.h gcc -c jeu.c -o jeu.o terminalCouleur.o: terminalCouleur.c 2048.h terminalCouleur.h gcc -c terminalCouleur.c -o terminalCouleur.o organisation.o: organisation.c 2048.h terminalCouleur.h gcc -c organisation.c -o organisation.o sauvegarde.o: save.c 2048.h gcc -c save.c -o save.o menu.o: menu.c 2048.h gcc -c menu.c -o menu.o clean: rm -rf *o 2048 <file_sep>/organisation.c #include <math.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <time.h> #include "2048.h" /*! * Alloue la grille de la variable jeu passée par adresse. * Initialise les cases de la grille avec des cases vides (valeurs nulles) * Initialise les champs n et max_value avec les valeurs passées en paramètre * * \param p : pointeur sur une partie de 2048 * \param n : taille de la grille * \param max_value : valeur à atteindre pour gagner */ void init_game (game *p, int n, int max_value){ if(p!=NULL){ p->grid = calloc(n*n, sizeof(int)); p->n = n; p->max_value = max_value; p->free_slots = n*n; } else printf("Une erreur de segmentation est survenue lors de l'initialisation de la partie. Veuillez réessayer plus tard."); } /*! * Libère la mémoire allouée pour la grille du jeu passé par adresse. * * \param p : pointeur sur une partie de 2048 */ void free_memory (game *p){ free(p->grid); } /*! * Fonction retournant 1 si la case (i, j) existe, 0 sinon. * */ int valid_slot (game *p, int line, int column){ return (line>=0 && line<(p->n) && column>=0 && column<(p->n)); } /*! * Fonction retournant la valeur de la case (ligne, colonne) de la partie p, * ou -1 si la case n’existe pas. * * \param p : pointeur sur la partie en cours * \param line : entier correspondant au numéro de ligne * \param column : entier correspondant au numéro de colonne */ int get_value (game *p, int line, int column){ return (p->grid[((p->n)*line)+column]*(valid_slot(p, line, column))-!(valid_slot(p, line, column))); } /*! * Fonction modifiant la valeur de la case (ligne, colonne) de la partie p, avec la valeur val * * \param p : pointeur sur la partie en cours * \param line : entier orrespondant au numéro de ligne * \param column : entier orrespondant au numéro de colonne * \param val : entier à mettre dans la case (i, j) (si elle existe) */ void set_value (game*p, int line, int column, int val){ if(valid_slot(p, line, column)){ p->grid[((p->n)*line)+column] = val; } } /*! * Fonction affichant une grille en couleur à l’écran. * * Le typedef enum COULEUR_TERMINAL contenu dans terminalCouleur.h nous permet de traiter chaque couleur * du panel comme étant un entier compris entre 0 et 7. * On attribue donc grâce à un log de base 2 une valeur comprise entre 0 et 7 à la couleur de la case courante, * couleur variant ainsi selon la puissance de 2 comprise dans la case en question. * * * \param p : pointeur sur la partie que l’on souhaite afficher */ void show (game *p){ int line, column, curr_val; COULEUR_TERMINAL bg_color, fg_color, absolute_color; clear_terminal(); for(line=0; line<(p->n); line++){ /* * Chaque ligne a (p->n) colonnes de hauteur egale a 3 pour donner de l'epaisseur. Donc chaque ligne est composee de 3 sous-lignes. * curr_val : valeur de la case actuelle * absolute_color : puissance de 2 correspondant à curr_val (si curr_val=8, absolute_color=3 car 8=2^3) * fg_color : couleur d'ecriture (On ecrira toujours en blanc, plus simple que de changer a chaque couleur et plus lisible) * bg_color : couleur de fond (On module par 7 pour ne pas avoir de case de couleur blanche) */ for(column=0; column<(p->n)*3; column++){ fg_color = WHITE; curr_val = get_value(p, line, column%(p->n)); absolute_color = (COULEUR_TERMINAL)(log2((double)(curr_val))); bg_color = (absolute_color%7)+(absolute_color>=7); // Si on est au debut d'une sous-ligne, on fait un saut de ligne et on decale de 3 tabulations pour centrer l'affichage if(column%(p->n)==0){ printf("\n\t\t\t"); } /* * Si on est pas sur la sous-ligne du milieu on affiche seulement une chaine vide de 7 caracteres. * Sinon si la valeur de la case est 0, on affiche un point sur 7 caracteres. * Sinon on affiche la valeur de la case sur 7 caracteres en tenant compte de la longueur du chiffre a afficher. */ if(column<(p->n) || column>=2*(p->n)){ color_printf(fg_color, bg_color, " "); } else if(curr_val==0){ color_printf(fg_color, bg_color, " . "); } else{ if(curr_val<10){ color_printf(fg_color, bg_color, " %d ", curr_val); } else if(curr_val<100){ color_printf(fg_color, bg_color, " %d ", curr_val); } else if(curr_val<1000){ color_printf(fg_color, bg_color, " %d ", curr_val); } } } } printf("\n"); }<file_sep>/2048.h #ifndef lala_H #define lala_H #define MOVE_RIGHT (-1) #define MOVE_LEFT 1 #define MOVE_DOWN (-1) #define MOVE_UP 1 typedef enum{ QUIT_GAME, NEW_GAME, LOAD_GAME, SAVE_GAME, RESUME_GAME }Select; typedef struct{ int n; int max_value; int free_slots; int *grid; }game; game* init_game(int n, int max_value); void free_memory(game *p); int valid_slot(game *p, int line, int column); int get_value(game *p, int line, int column); void set_value(game*p, int line, int column, int val); void show(game *p); int empty_slot(game *p, int line, int column); void set_random_value(game *p); int victory(game *p); int defeat(game*p); int game_over(game*p); int move_line(game *p, int line, int direction); int move_lines(game *p, int direction); int move_column(game *p, int column, int direction); int move_columns(game *p, int direction); int move(game *p, int direction); int input_read(); int play(game *p); void makeSave(); int save_game(game *p); int load_game(game *p); int menu(game *p); #endif <file_sep>/jeu.c #include <math.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <time.h> #include "2048.h" /*! * Effectue les mouvements (à gauche ou à droite) des cases d’une ligne. * Renvoie 1 si l’on a déplacé au moins une case, 0 sinon. * * \param p : pointeur sur un jeu * \param line : indice de ligne * \param direction : 1 pour déplacement vers la gauche et -1 pour un déplacement vers la droite */ int move_line (game *p, int line, int direction){ /* * start vaudra (n-1) si on va vers la droite ou 0 si on va vers la gauche. C'est la variable correspondant au départ des boucles utilisees. * limit vaudra 0 si on va vers la droite ou (n-1) si on va vers la gauche. C'est la variable correspondant à la fin des boucles utilisees. * On parcourt donc la ligne de gauche à droite si on veut se deplacer vers la gauche. On la parcourt de droite à gauche sinon. */ int column, other_val, curr_val, size = (p->n-1), start = size*(direction==MOVE_RIGHT), limit = size*(direction==MOVE_LEFT), move = 0, pack = start; /* * On tasse la ligne du cote du deplacement voulu. * pack ne va augmenter que lorsqu'on rencontrera une case non vide, ce qui permet de deplacer les elements non nuls dans les cases vides. * On ajoute a ca le vidage des cases deplacees pour reellement tasser la ligne et ne pas dupliquer de valeurs. * S'il y a deplacement, on incremente move. */ for(column=start; column!=(limit+direction); column+=direction){ if(get_value(p, line, column)!=0){ set_value(p, line, pack, get_value(p, line, column)); if(pack!=column){ set_value(p, line, column, 0); move++; } pack += direction; } } //Cette boucle effectue la fusion des cases identiques. for(column=start; column!=limit; column+=direction){ other_val = get_value(p, line, column+direction); curr_val = get_value(p, line, column); //Si deux cases ont la meme valeur et que ca n'est pas 0, on stocke la somme dans la case courante, on incremente le nombre de cases vides et move (il y a deplacement). if(other_val==curr_val && curr_val!=0){ move++; (p->free_slots)++; set_value(p, line, column, curr_val+other_val); //On decale ensuite d'un cran dans la direction voulue toute les cases non modifiees et on mets les cases d'origine de celles decalees a 0. for(pack=(column+direction); pack!=limit; pack+=direction){ set_value(p, line, pack, get_value(p, line, pack+direction)); set_value(p, line, pack+direction, 0); } //Pour mettre la derniere case de la ligne a 0 (pas pris en compte par la boucle). set_value(p, line, pack, 0); } } //Si move est different de 0, il y a eu au moins un mouvement. return (move!=0); } /*! * Effectue les mouvements (à gauche ou à droite) des cases sur toutes les lignes. * Renvoie 1 si l’on a déplacé au moins une case, 0 sinon. * * \param p : pointeur sur un jeu * \param direction : 1 pour déplacement vers la gauche et -1 pour un déplacement vers la droite */ int move_lines (game *p, int direction){ int line, move = 0; for(line=0; line<(p->n); line++){ move += move_line(p, line, direction); } return (move!=0); } /*! * Effectue les mouvements (vers le haut ou vers le bas) des cases d’une colonne. * Renvoie 1 si l’on a déplacé au moins une case, 0 sinon. * * \param p : pointeur sur un jeu * \param column : indice de colonne * \param direction : -1 pour déplacement vers la bas et 1 vers le haut */ int move_column (game *p, int column, int direction){ int line, other_val, curr_val, size = (p->n-1), start = size*(direction==MOVE_RIGHT), limit = size*(direction==MOVE_LEFT), move = 0, pack = start; for(line=start; line!=(limit+direction); line+=direction){ if(get_value(p, line, column)!=0){ set_value(p, pack, column, get_value(p, line, column)); if(pack!=line){ set_value(p, line, column, 0); move++; } pack += direction; } } for(line=start; line!=limit; line+=direction){ other_val = get_value(p, line+direction, column); curr_val = get_value(p, line, column); if(other_val==curr_val && curr_val!=0){ move++; (p->free_slots)++; set_value(p, line, column, curr_val+other_val); for(pack=(line+direction); pack!=limit; pack+=direction){ set_value(p, pack, column, get_value(p, pack+direction, column)); set_value(p, pack+direction, column, 0); } set_value(p, pack, column, 0); } } return (move!=0); } /*! * Effectue les mouvements (vers le haut ou vers le bas) des cases de toutes les colonnes. * Renvoie 1 si l’on a déplacé au moins une case, 0 sinon. * * \param p : pointeur sur un jeu * \param direction : -1 pour déplacement vers la bas et 1 vers le haut */ int move_columns (game *p, int direction){ int column, move = 0; for(column=0; column<(p->n); column++){ move += move_column(p, column, direction); } return (move!=0); } /*! * Effectue le mouvement sur les lignes ou sur les colonnes suivant la valeur de direction. * * \param p : pointeur sur un jeu * \param direction : entier donnant la direction : * 0 : vers le bas * 1 : vers la droite * 2 : vers le haut * 3 : vers la gauche * Renvoie 1 si l’on a déplacé au moins une case, 0 sinon */ int move (game *p, int direction){ switch(direction){ case KEY_DOWN : return (move_columns(p, MOVE_DOWN)); break; case KEY_RIGHT : return (move_lines(p, MOVE_RIGHT)); break; case KEY_UP : return (move_columns(p, MOVE_UP)); break; case KEY_LEFT : return (move_lines(p, MOVE_LEFT)); break; default : return 0; } } /*! * Fonction permettant la saisie d’une direction ou de l’arrêt du jeu * (saisie répétée pour les autres touches) * Retourne : * -1 si l’utilisateur arrête le jeu * 0 si l’utilisateur souhaite déplacer vers le bas * 1 si l’utilisateur souhaite déplacer vers la droite * 2 si l’utilisateur souhaite déplacer vers le haut * 3 si l’utilisateur souhaite déplacer vers le gauche */ int input_read (){ int arr_key; debutTerminalSansR(); do{ arr_key = (int)lectureFleche(); }while(arr_key==NO_KEY); finTerminalSansR(); return arr_key; } /*! * Fonction permettant de jouer la partie en cours (on la suppose initialisée) * Retourne 1 si la partie est terminée (l’utilisateur a gagné ou perdu), et 0 sinon * (l’utilisateur a appuyé sur la touche Echap). */ int play (game *p){ int direction; set_random_value(p); do{ show(p); direction = input_read(); if(direction!=KEY_ESCAPE){ //On ajoute une valeur aleatoire seulement s'il y a deplacement. if(move(p,direction)){ set_random_value(p); } } if(game_over(p)){ show(p); } }while(!game_over(p) && direction!=KEY_ESCAPE); return game_over(p); }
6dd459a048d3e5d294e2a8066fedbfab4df30a8d
[ "C", "Makefile" ]
7
C
Sensoe/2048
2f37fc722d0a1565f5eb52a745fc50041b6753be
b9cd223633726f38c9212e84df1da0da0ebdd43d
refs/heads/main
<file_sep>**Building the docker file** ``` sudo docker build --tag search-autocomplete-app . ``` **Running the docker file** Make sure you are in root directory of the project and run the following command ``` sudo docker run --name search-autocomplete-app -p 5001:5001 search-autocomplete-app ``` **Prerequisite** 1. Docker installed in the machine for build 2. Redis installation (IP needs to be updated in the app.py for redis connection) <file_sep># Repetitions solution ## Solution using AWK command Inside BEGIN we have used OFS to empty space that will act as the output field saperator for the rest we have compared second item to the first item and printing it if it is not equal (We printed the first word as we are iterating from the second word) ``` awk 'BEGIN{OFS=" "}{ printf "%s", $1 for (i=2; i<=NF; i++) { if ($i != $(i-1)) { printf "%s%s", OFS ,$i } } print "" }' input.txt > output.txt ``` ## Execution steps ``` cd 1/ && \ cat inputs/sample-input.txt | ./Repetitions.sh ``` <file_sep>awk 'BEGIN{OFS=" "}{ printf "%s", $1 for (i=2; i<=NF; i++) { if ($i != $(i-1)) { printf "%s%s", OFS ,$i } } print "" }' <file_sep>from flask import Flask,request,jsonify import redis from flask import Flask,request,jsonify app = Flask(__name__) r = redis.StrictRedis(host='192.168.127.12', port=6379, db=0) KEY = 'compl' ''' FORMAT: localhost:5000/add?name=<name> ''' @app.route('/') def details(): return """<xmp> Add word, http://127.0.0.1:5000/add?name=<word> Query word, http://127.0.0.1:5000/suggestions?prefix=<word> </xmp>""" @app.route('/add') def add_to_dict(): try: name = request.args.get('name') print("value of name"+name) line = name.strip() for end_index in range(1, len(line)): prefix = line[0:end_index] print("Prefix values :"+prefix) r.zadd(KEY,{prefix:0}) r.zadd(KEY,{line+'*':0}) return "Addition Successful" except: return "Addition failed" ''' FORMAT: localhost:5000/suggestions?prefix=<prefix_you want to match> ''' @app.route('/suggestions') def get_suggestions(): prefix = request.args.get('prefix') results = [] rangelen = 50 count=50 print("value of KEY: "+KEY) print("value of prefix: "+prefix) start = r.zrank(KEY, prefix) print(start) print ("Inside the function") if not start: return [] while len(results) != count: print ("Inside the while") range = r.zrange(KEY, start, start + rangelen - 1) print('Range') print(range) start += rangelen if not range or len(range) == 0: break for entry in range: print('Inside For Loop') entry=entry.decode('utf-8') print(entry) len_entry = len(entry) len_prefix = len(prefix) minlen = min((len(entry), len(prefix))) print(minlen) if entry[0:minlen] != prefix[0:minlen]: count = len(results) break if entry[-1] == '*' and len(results) != count: results.append(entry[0:-1]) return jsonify(results) if __name__ == "__main__": app.run(host ='0.0.0.0', port = 5001, debug=True)
0f74c4cfd21bac52accb8c37aaf380f4cfc21fad
[ "Markdown", "Python", "Shell" ]
4
Markdown
bombadeb/Demo1
6e96cbe7328b1f0a0e0ef9b8a9cd7488bed42c8e
c71b2148ba07dc400118e5e3329572848efe459c
refs/heads/master
<repo_name>joseph-tohdjojo/react-starter<file_sep>/server/routes/api/entries/entriesRoutes.js const entriesCtrl = require('./entriesCtrl.js') module.exports = (app) => { app.get('/api/posts', entriesCtrl.getAllPosts) } <file_sep>/server.js /*------------------------------------*\ #VENDOR DEPENDENCIES \*------------------------------------*/ const express = require('express') const path = require('path') /*------------------------------------*\ #VARIABLES \*------------------------------------*/ const port = 8080 /*------------------------------------*\ #INITIALIZE APP \*------------------------------------*/ const app = express() app.use(express.static(path.resolve(__dirname, 'public'))) // handle every other route with index.html, which will contain // a script tag to your application's JavaScript file(s). app.get('*', function (request, response){ response.sendFile(path.resolve(__dirname, 'public', 'index.html')) }) /*------------------------------------*\ #ROUTES \*------------------------------------*/ require('./server/routes/index.js')(app) /*------------------------------------*\ #LISTEN \*------------------------------------*/ app.listen(port, function() { console.log('Server listening on port', port) }) <file_sep>/webpack.config.js const path = require('path') const glob = require('glob') const merge = require('webpack-merge') const parts = require('./webpack.parts.js') const PATHS = { app: path.join(__dirname, 'src'), build: path.join(__dirname, 'public', 'build'), } const commonConfig = merge([ { entry: { app: PATHS.app, }, output: { path: PATHS.build, publicPath: '/build/', filename: '[name].js', }, }, parts.clean(PATHS.build), parts.lintJavaScript({ include: PATHS.app }), parts.extractCSS(), parts.loadJavaScript({ include: PATHS.app }), parts.extractBundles([ { name: 'vendor', minChunks: ({ userRequest }) => ( userRequest && userRequest.indexOf('node_modules') >= 0 && userRequest.match(/\.js$/) ), }, ]), ]) const productionConfig = merge([ { performance: { hints: 'warning', // 'error' or false are valid too maxEntrypointSize: 200000, // in bytes maxAssetSize: 200000, // in bytes }, }, parts.minifyJavaScript({ useSourceMap: true }), parts.minifyCSS({ options: { discardComments: { removeAll: true, }, // Run cssnano in safe mode to avoid // potentially unsafe ones. safe: true, }, }), ]) const developmentConfig = merge([ // parts.devServer({ // host: process.env.HOST, // port: process.env.PORT, // }), ]) module.exports = function(env) { return env === 'production' ? merge(commonConfig, productionConfig) : merge(commonConfig, developmentConfig) } <file_sep>/src/components/Home/Home.js import React from 'react' import styles from './Home.css' console.log(styles) const Main = React.createClass({ render () { return ( <div className={styles.test}> This is the home page </div> ) }, }) export default Main <file_sep>/server/routes/api/entries/entriesCtrl.js exports.getAllPosts = (req, res) => { res.send('Everything works') } <file_sep>/server/routes/index.js const apiRoutes = require('./api/apiRoutes.js') module.exports = ( app ) => { apiRoutes( app ) }
fc7075c4f154f184754270fa9d7a26fd42127e1b
[ "JavaScript" ]
6
JavaScript
joseph-tohdjojo/react-starter
ee228daa95aba740787759e86f470460c5bcb98c
d184a2f26d4909c0d7227234dd6a87b5c61c7788
refs/heads/master
<file_sep>import json import urllib2 import subprocess import time import datetime import os import re import glob import itertools theme_prefix='theme*' hashtag='kitty' igurl = 'https://api.instagram.com/v1/tags/'+hashtag+'/media/recent?access_token=<KEY>' def listdirsfullpath(folder): return [ d for d in (os.path.join(folder, d1) for d1 in os.listdir(folder)) if os.path.isdir(d) ] def listdirs(folder): return [d for d in os.listdir(folder) if os.path.isdir(os.path.join(folder, d))] def generateFrame(insertion,theme_use): subprocess.call(theme_use+".cmd " + insertion,shell=True) def generateFrame_Unix(insertion,theme_use): subprocess.call("./" + theme_use + ".sh " + insertion + " >/dev/null",shell=True) def downloadJpg(url): uopen = urllib2.urlopen(url) stream = uopen.read() newfilename=url.replace("/","_") file = open((newfilename[7:]),'wb') file.write(stream) file.close #print newfilename[7:] return newfilename[7:] def difference(a, b): return list(set(b).difference(set(a))) def difference_super(a,b): newset = [] first_set = set(map(tuple, a)) second_set= set(map(tuple, b)) for i in range(len(list(first_set))): dup_in_second=0 for j in range(len(list(second_set))): subset_a=list(first_set)[i][2] subset_b=list(second_set)[j][2] if subset_a == subset_b: dup_in_second=1 if dup_in_second == 0: newset.append(list(first_set)[i]) return list(newset) def showascii(filename): subprocess.call(["jp2a",filename,"--size=65x30"]) before_image_urls = [] for i in range(20): before_image_urls.append(str(i)) before_main_list = [] for i in range(20): before_main_list.append(list(str(i))) main_list = [] before_complist = [] firstwhile=1; infinite=1 dummy=0 time_before = datetime.datetime.now() theme_list = [path for path in glob.glob(theme_prefix) if os.path.isdir(path)] print theme_list a = 0 while infinite == 1: try: response = urllib2.urlopen(igurl) except Exception as exception: while a < 10: print "HTTPError Exception, retrying 10 times" a = a + 1 response = urllib2.urlopen(igurl) time.sleep(1) info = json.load(response) main_list = [] image_urls = [] username = [] mediatype = [] full_name = [] profile_picture = [] location = [] created_time = [] likescount = [] captiontext = [] commenttext = [] utf8string =" " for post in info['data']: image_urls.append(post["images"]["standard_resolution"]["url"]) username.append(post["user"]["username"]) mediatype.append(post["type"]) full_name.append(post["user"]["full_name"]) profile_picture.append(post["user"]["profile_picture"]) # location.append(post["location"]["latitude"]) if str(post["location"])== "None": #print "No Location" location.append("null") else: try: if str(post["location"]['name']) <> "None": #This thing got name location.append(post["location"]["name"]) except: #LatLong Only location.append("null") created_time.append(post["created_time"]) likescount.append(post["likes"]["count"]) try: if str(post["caption"]["text"]) <> "None": captiontext.append(post["caption"]["text"]) else: captiontext.append("null") except: captiontext.append("null") if int(post["comments"]["count"]) == 0: dummy=0 else: for commentpost in post['comments']['data']: # print str("write txt") utf8string=utf8string+(commentpost["from"]["username"]+u" "+commentpost["text"]+u"\n") commenttext.append(utf8string) utf8string="" for eachOne in range(len(username)): sublist = [] sublist.append(username[eachOne]) #0 sublist.append(mediatype[eachOne]) #1 sublist.append(image_urls[eachOne]) #2 sublist.append(profile_picture[eachOne]) #3 sublist.append(created_time[eachOne]) #4 sublist.append(location[eachOne]) #5 sublist.append(likescount[eachOne]) #6 sublist.append(captiontext[eachOne]) #7 sublist.append(commenttext[eachOne]) #8 main_list.append(sublist) # print "======" if firstwhile == 1: before_main_list = main_list list_diff=difference_super(main_list,before_main_list) before_main_list=main_list # print len(list_diff) if len(list_diff) > 0 and firstwhile == 0: print "Incoming Feed for:"+str(len(list_diff)) for eachOne in range(len(list_diff)): picturedate=datetime.datetime.fromtimestamp(int(list_diff[eachOne][4])) print ("Username: "+str(list_diff[eachOne][0])+"\t"+picturedate.strftime("%I:%M%p")) print ("Likes :"+str(list_diff[eachOne][6])) # print ("Caption"+(list_diff[eachOne][7])) # print ("Created:",datetime.datetime.fromtimestamp(int(list_diff[eachOne][4]))) # print str(list_diff[eachOne][5]) try: filename_profile=downloadJpg(list_diff[eachOne][3]) filename_main=downloadJpg(list_diff[eachOne][2]) if list_diff[eachOne][7].encode('utf8') <> "": captionfile=open(filename_main+".cap","wb") captionfile.write(list_diff[eachOne][7].encode('utf8')) captionfile.close() else: dummy=0 if list_diff[eachOne][8].encode('utf8') <> "": print "[...]" commentlabel=open(filename_main+".txt","wb") commentlabel.write(list_diff[eachOne][8].encode('utf8')) commentlabel.close() else: dummy=0 theme_use="default_theme" for ii in range(len(theme_list)): #print "#"+theme_list[ii] #print list_diff[eachOne][7].encode('utf8') if "#"+theme_list[ii] in list_diff[eachOne][7].encode('utf8'): #print "<Theme Match>" theme_use=theme_list[ii] break else: dummy=0 #print list_diff[eachOne][8].encode('utf8') if "#"+theme_list[ii] in list_diff[eachOne][8].encode('utf8'): theme_use=theme_list[ii] break else: dummy=0 print theme_use generateFrame( '\042' + str(list_diff[eachOne][0]) +'\042 '+ '\042' + str(list_diff[eachOne][5]) +'\042 '+ '\042' + str(filename_profile) +'\042 '+ '\042' + str(filename_main) +'\042 '+ '\042' + str(picturedate.strftime("%b-%d-%Y %I:%M%p")) + '\042 '+ '\042' + str(list_diff[eachOne][6]) + '\042 ' + '\042' + str(filename_main+".cap") + '\042',theme_use) except: print "* Error Getting Images: Photo has been deleted or permission denied" else: print ".zzZ" print "-----------------------------------------------" time_now = datetime.datetime.now() print (time_now - time_before).total_seconds() if (time_now - time_before).total_seconds() < 6: time_before=time_now time.sleep(5) else: time_before=time_now time.sleep(1) firstwhile=0 #-- END WHILE <file_sep>![](http://cdn.dnaindia.com/sites/default/files/styles/half/public/2016/05/12/459466-instagram-new-logo.jpg) # Instagram Printer Imagine you can setup the printer that can print out right from instagram when you tag it. This will be very useful at the party or event. I actually developed this one to use at one of the family party few years back. Just need laptop or raspberry pi connected to printer. ![https://github.com/thamarnan/instagram-printer/blob/master/images/setup_laptop_printer.jpg?raw=true](https://github.com/thamarnan/instagram-printer/blob/master/images/setup_laptop_printer.jpg?raw=true "https://github.com/thamarnan/instagram-printer/blob/master/images/setup_laptop_printer.jpg?raw=true") # How it works? First you need to setup python to run on computer. In this case I'm using python 2.7 running on Windows. (This code is dated, you might need to update the api and igURL) The python code then login to instgram as your account. It then freshed every few seconds to catch if there are any new picture that tagged with your specfic hashtag. if it found the matched. It will printout to the printer replicating instagram on paper. Once printed, the picture is deleted. | default_theme | | --- | | ![](https://github.com/thamarnan/instagram-printer/blob/master/images/default_theme.jpg?raw=true) | # Requirements What you will need are: 1. python 2.7 setup on computer 2. your instagram access token. You can follow [this](https://elfsight.com/blog/2016/05/how-to-get-instagram-access-token/ "this") instruction to get token 3. Update new token on the python code (printme.py) ````python hashtag='kitty' igurl = 'https://api.instagram.com/v1/tags/'+hashtag+'/media/recent?access_token=<KEY>' ```` Next step Set hashtag Then Set Printer name (default_theme.cmd) last line `rundll32 shimgvw.dll ImageView_PrintTo /pt %OUTPUT%.bmp "Canon IP4500"` and finally Run python printme.py # Customization | Customize Work Flow | | --- | | ![](https://github.com/thamarnan/instagram-printer/blob/master/images/printme_diagram.jpg?raw=true) | When hashtag found in the image. We can set the custom theme so that the picture print out in different template with secondary hashtag. For example, I'm looking to print the hashtag "cat" but if there is a secondary hashtag called "kitty" I want to use hellokitty theme template. To do this follow the step here: 1. new theme has prefix with the word 'theme' eg themekitty 2. create themekitty.cmd (example in this repository) 3. create folder call themekitty 4. set new background in the template_whitebackground.bmp | themekitty | | --- | | ![](https://github.com/thamarnan/instagram-printer/blob/master/images/themekitty.jpg?raw=true) | also included blank polariod theme in the example | themepolaroid | | --- | | ![](https://github.com/thamarnan/instagram-printer/blob/master/images/themepolaroid.jpg?raw=true) | Then virtually we have no limit on the variety and have more fun with different pre define template # Notes Please check any update on instagram api on https://www.instagram.com/developer/
2ca3c1b0788d17d15e3ce51cbadb6f6ae87a30c6
[ "Markdown", "Python" ]
2
Python
danielfeo/instagram-printer
bf8f2bb6a17756a89ec816f044121cd5a0f1c25b
91a59a56dd203439491f07d6f2777929e3f003d3
refs/heads/main
<repo_name>AndreaRR18/ACME-App<file_sep>/Architecture/Sources/Architecture/Router.swift public protocol Router { func presentPage(_ module: Presentable, animated: Bool, _ completion: (() -> Void)?) func dismissPage(animated: Bool, completion: (() -> Void)?) func pushPage(_ module: Presentable, animated: Bool) func popPage(animated: Bool) func setAsRoot(_ module: Presentable, animated: Bool) func popToRootPage(animated: Bool) } <file_sep>/Login/Tests/LoginTests/Interactor/LoginInteractorTests.swift import XCTest @testable import Login import RxBlocking import Entities import NetworkingCommon class LoginInteractorTests: XCTestCase { var sut: LoginIteractor! override func tearDown() { sut = nil super.tearDown() } func testDoLogin_LoginFailed() { sut = LoginIteractor( configuration: LoginInterarctorConfiguration( environment: MockEnvironment( asserDeleteUser: { XCTFail() }, asserUpdateUser: { _ in XCTFail() } ), repository: MockFailureLoginNetworking.shared, saveCredential: { _,_ in XCTFail() fatalError() } )) let result = sut.doLogin(username: "USR", password: "PSW") XCTAssertEqual( try result.toBlocking().first(), Result<User, ClientError>.failure(.badRequest) ) } func testDoLogin_LoginSuccess() { let responseUser = User(username: "USR", firstName: "FName", lastName: "LName") sut = LoginIteractor( configuration: LoginInterarctorConfiguration( environment: MockEnvironment( asserDeleteUser: { XCTFail() }, asserUpdateUser: { user in XCTAssertEqual(user, responseUser) } ), repository: MockSuccessLoginNetworking(user: responseUser), saveCredential: { value, pass in XCTAssertEqual("ACMEPassword", value) XCTAssertEqual("PSW", pass) return .success(()) } )) let result = sut.doLogin(username: "USR", password: "PSW") XCTAssertEqual( try result.toBlocking().first(), Result<User, ClientError>.success(responseUser) ) } } <file_sep>/Room/Sources/Room/View/CameraSession.swift import Foundation import AVFoundation protocol CameraSession { var previewFrame: CGRect { get } var captureSession: AVCaptureSession { get } var stillImageOutput: AVCapturePhotoOutput { get } func setupLivePreview() } extension CameraSession { func frontCamerarRunning() { captureSession.sessionPreset = .medium guard let frontCamera = AVCaptureDevice.default(.builtInWideAngleCamera, for: AVMediaType.video, position: .front) else { return } do { let input = try AVCaptureDeviceInput(device: frontCamera) if captureSession.canAddInput(input) && captureSession.canAddOutput(stillImageOutput) { captureSession.addInput(input) captureSession.addOutput(stillImageOutput) setupLivePreview() } DispatchQueue.global(qos: .userInitiated).async { captureSession.startRunning() } } catch let error { print("Error Unable to initialize back camera: \(error.localizedDescription)") } } func frontCameraStop() { captureSession.stopRunning() } } <file_sep>/README.md # ACME-App ACME Corporation App <file_sep>/SecureStore/Tests/SecureStoreTests/SecureStoreTests.swift import XCTest @testable import SecureStore final class SecureStoreTests: XCTestCase { var secureStoreWithGenericPwd: SecureStore! override func setUp() { super.setUp() let genericPwdQueryable = CredentialSecureStore(service: "ArtooService", accessGroup: nil) secureStoreWithGenericPwd = SecureStore(secureStoreQueryable: genericPwdQueryable) } override func tearDown() { _ = secureStoreWithGenericPwd.removeAllValues() super.tearDown() } func testSaveGenericPassword() { let setValueResult = secureStoreWithGenericPwd.setValue("pwd_1234", for: "genericPassword") switch setValueResult { case .success: XCTAssertTrue(true) case let .failure(e): XCTFail("Saving generic password failed with \(e.localizedDescription).") } } func testReadGenericPassword() { guard case .success = secureStoreWithGenericPwd.setValue("pwd_1234", for: "genericPassword") else { return XCTFail("Saving generic password failed.") } let passwordResult = secureStoreWithGenericPwd.getValue(for: "genericPassword") switch passwordResult { case let .success(password): XCTAssertEqual("<PASSWORD>", password) case let .failure(e): XCTFail("Reading generic password failed with \(e.localizedDescription).") } } func testUpdateGenericPassword() { guard case .success = secureStoreWithGenericPwd.setValue("pwd_1234", for: "genericPassword") else { return XCTFail("Saving generic password failed.") } guard case .success = secureStoreWithGenericPwd.setValue("pwd_1235", for: "genericPassword") else { return XCTFail("Saving generic password failed.") } let passwordResult = secureStoreWithGenericPwd.getValue(for: "genericPassword") switch passwordResult { case let .success(password): XCTAssertEqual("<PASSWORD>", password) case let .failure(e): XCTFail("Updating generic password failed with \(e.localizedDescription).") } } func testRemoveGenericPassword() { guard case .success = secureStoreWithGenericPwd.setValue("pwd_<PASSWORD>", for: "genericPassword") else { return XCTFail("Saving generic password failed.") } guard case .success = secureStoreWithGenericPwd.removeValue(for: "genericPassword") else { return XCTFail("Remove store value failed") } let sut = secureStoreWithGenericPwd.getValue(for: "genericPassword") switch sut { case let .success(value): XCTAssertNil(value) case let .failure(e): XCTFail("Saving generic password failed with \(e.localizedDescription).") } } func testRemoveAllGenericPasswords() { guard case .success = secureStoreWithGenericPwd.setValue("pwd_1234", for: "genericPassword") else { return XCTFail("Saving generic password failed.") } guard case .success = secureStoreWithGenericPwd.setValue("pwd_<PASSWORD>", for: "genericPassword2") else { return XCTFail("Saving generic password failed.") } guard case .success = secureStoreWithGenericPwd.removeAllValues() else { return XCTFail("Remove all values failed.") } switch secureStoreWithGenericPwd.getValue(for: "genericPassword") { case .success(let firstValue): switch secureStoreWithGenericPwd.getValue(for: "genericPassword2") { case .success(let secondValue): XCTAssertNil(firstValue) XCTAssertNil(secondValue) case let .failure(e): XCTFail("Removing generic passwords failed with \(e.localizedDescription).") } case let .failure(e): XCTFail("Removing generic passwords failed with \(e.localizedDescription).") } } static var allTests = [ ("testSaveGenericPassword", testSaveGenericPassword), ("testReadGenericPassword", testReadGenericPassword), ("testUpdateGenericPassword", testUpdateGenericPassword), ("testRemoveGenericPassword", testRemoveGenericPassword), ("testRemoveAllGenericPasswords", testRemoveAllGenericPasswords) ] } <file_sep>/Room/Sources/Room/Networking/WSRoomModel.swift import Foundation enum WSRoomModel { struct Request: Encodable { var contactId: String } struct Response: Decodable { var streamStatus: StreamStatus } struct StreamStatus: Decodable { var id: String var hasVideo: Bool var hasAudio: Bool var stream: Data } } <file_sep>/Room/Sources/Room/Room/RoomDelegate.swift public protocol RoomDelegate { func didConnect() func didDisconnect() func didAddStrem(_ stream: Stream) func didRemoveSteram(_ stream: Stream) } <file_sep>/Room/Sources/Room/View/ContactView.swift import Foundation import UIKit import Architecture import FunctionalKit class ContactView: UIView, Updatable { typealias UpdateType = ContactsViewState let imageView: UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFit return imageView }() let placeholderVideo: UILabel = { let label = UILabel() label.textColor = .black label.text = "No video" label.backgroundColor = UIColor.lightGray.withAlphaComponent(0.8) return label }() let label: UILabel = { let label = UILabel() label.textColor = .black label.backgroundColor = UIColor.lightGray.withAlphaComponent(0.8) return label }() let muteLabel: UILabel = { let label = UILabel() label.text = "Mute" label.textColor = .black label.backgroundColor = UIColor.lightGray.withAlphaComponent(0.8) return label }() func setupUI() { backgroundColor = .lightGray imageView.removeFromSuperview() placeholderVideo.removeFromSuperview() label.removeFromSuperview() muteLabel.removeFromSuperview() imageView.translatesAutoresizingMaskIntoConstraints = false placeholderVideo.translatesAutoresizingMaskIntoConstraints = false label.translatesAutoresizingMaskIntoConstraints = false muteLabel.translatesAutoresizingMaskIntoConstraints = false addSubview(imageView) addSubview(placeholderVideo) addSubview(label) addSubview(muteLabel) //Image NSLayoutConstraint.activate([ imageView.topAnchor.constraint(equalTo: topAnchor), imageView.leadingAnchor.constraint(equalTo: leadingAnchor), imageView.bottomAnchor.constraint(equalTo: bottomAnchor), imageView.trailingAnchor.constraint(equalTo: trailingAnchor) ]) //Placeholder Image NSLayoutConstraint.activate([ placeholderVideo.centerYAnchor.constraint(equalTo: centerYAnchor), placeholderVideo.centerXAnchor.constraint(equalTo: centerXAnchor), ]) //Label NSLayoutConstraint.activate([ label.heightAnchor.constraint(equalToConstant: 20), label.heightAnchor.constraint(equalToConstant: 100), label.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -10), label.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -10) ]) //Mute image NSLayoutConstraint.activate([ muteLabel.heightAnchor.constraint(equalToConstant: 20), muteLabel.heightAnchor.constraint(equalToConstant: 20), muteLabel.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -10), muteLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 10) ]) } func update(_ value: ContactsViewState) { if let data = value.image, value.hasVideo { imageView.isHidden = false imageView.image = UIImage(data: data) placeholderVideo.isHidden = true } else { imageView.isHidden = true placeholderVideo.isHidden = false } label.text = value.name muteLabel.isHidden = value.hasAudio.not } } <file_sep>/ContactsList/Package.swift // swift-tools-version:5.3 import PackageDescription let package = Package( name: "ContactsList", products: [ .library( name: "ContactsList", targets: ["ContactsList"]), ], dependencies: [ .package(path: "../ACMESecureStore"), .package(path: "../Architecture"), .package(path: "../Entities"), .package(path: "../NetworkingCommon"), .package(url: "https://github.com/ReactiveX/RxSwift.git", from: "5.1.0"), .package(url: "https://github.com/facile-it/FunctionalKit.git", from: "0.22.0") ], targets: [ .target( name: "ContactsList", dependencies: [ "ACMESecureStore", "NetworkingCommon", "Entities", "Architecture", "FunctionalKit", "RxSwift" ]), .testTarget( name: "ContactsListTests", dependencies: ["ContactsList"]), ] ) <file_sep>/Room/Sources/Room/Networking/RoomNetworking.swift import NetworkingCommon import Entities import RxSwift import Foundation public protocol RoomNetworking: WebRepository { func startCall(with: Contact) -> Observable<Result<ACMEStream, ClientError>> } public struct RoomNetworkingImpl: RoomNetworking { public var session: URLSession public var baseURL: String public init(session: URLSession, baseURL: String) { self.session = session self.baseURL = baseURL } public func startCall(with contact: Contact) -> Observable<Result<ACMEStream, ClientError>> { let response: Observable<Result<WSRoomModel.Response, ClientError>> = call(endpoint: API.startCallWith(id: contact.id)) return response.map { result -> Result<ACMEStream, ClientError> in result.map { response in ACMEStream( hasAudio: response.streamStatus.hasAudio, hasVideo: response.streamStatus.hasVideo, stream: response.streamStatus.stream) } } } } fileprivate extension RoomNetworkingImpl { enum API { case startCallWith(id: String) } } extension RoomNetworkingImpl.API: APICall { var path: String { switch self { case let .startCallWith(id: id): return "path/to/get/stream?contactid=\(id)" } } var method: String { "GET" } var headers: [String : String]? { ["jwt-token": "TE<PASSWORD>"] } func body() throws -> Data? { nil } } <file_sep>/Entities/Sources/Entities/Contact.swift import Foundation public struct Contact: Codable, Equatable { public let id: String public let firstName: String public let lastName: String public let imageData: Data public init( id: String, firstName: String, lastName: String, imageData: Data ) { self.id = id self.firstName = firstName self.lastName = lastName self.imageData = imageData } } <file_sep>/ACME/Common/PropertyWrappers/CustomObjectUserDefault.swift import Foundation @propertyWrapper struct CustomObjectUserDefault<T: Codable> { let key: String init(_ key: String) { self.key = key } var wrappedValue: T? { get { let otpData = UserDefaults.standard.object(forKey: key) as? Data guard let data = otpData else { return nil } return try? JSONDecoder().decode(T.self, from: data) } set { if let data = try? JSONEncoder().encode(newValue) { UserDefaults.standard.set(data, forKey: key) } else { UserDefaults.standard.removeObject(forKey: key) } } } } <file_sep>/ContactsList/Sources/ContactsList/Networking/WSContactsListModel.swift import Foundation enum WSContactsModel { struct Request: Encodable {} struct Response: Decodable { var contacts: [WSContactsModel.Contact] } struct Contact: Decodable { var id: String var firstName: String var lastName: String var age: String var address: String var avatar: Data } } <file_sep>/Architecture/Sources/Architecture/Presentable.swift import UIKit public protocol Presentable: class { func presented() -> UIViewController } <file_sep>/ContactsList/Sources/ContactsList/View/ContactListPage.swift import UIKit import FunctionalKit import Architecture import ACMESecureStore import Entities public class ContactListPage: UIViewController, PageType { public typealias ViewState = ContactsListViewState public typealias Presenter = ContactsListPresenter let environment: Environment let networking: ContactsListNetworking public var presenter: ContactsListPresenter? let getLogin: Effect<Presentable> let getConversationPage: Effect<Presentable> let secureStore: ACMESecureStore let generateLocalContact: Effect<Contact> private let tableView: UITableView = { let tableView = UITableView() tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 85, right: 0) return tableView }() private let startCallButton: UIButton = { let button = UIButton() button.setTitle("Start call", for: .normal) button.backgroundColor = .black button.tintColor = .white button.layer.cornerRadius = 10 button.addTarget(self, action: #selector(startButtonTapped), for: .touchUpInside) return button }() private lazy var adapter = ContactsListAdapter() public init( environment: Environment, networking: ContactsListNetworking, getLogin: Effect<Presentable>, getConversationPage: Effect<Presentable>, secureStore: ACMESecureStore, generateLocalContact: Effect<Contact> ) { self.environment = environment self.networking = networking self.getLogin = getLogin self.getConversationPage = getConversationPage self.secureStore = secureStore self.generateLocalContact = generateLocalContact super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } public override func viewDidLoad() { super.viewDidLoad() self.navigationItem.setHidesBackButton(true, animated: false) navigationItem.leftBarButtonItem = UIBarButtonItem( title: "Logout", style: .plain, target: self, action: #selector(logoutTapped) ) navigationItem.rightBarButtonItem = UIBarButtonItem( title: "+", style: .plain, target: self, action: #selector(addLocalContact) ) presenter = ContactsListPresenter( environment: environment, contactsListInteractor: ContactsListIteractor( configuration: .init( environment: environment, repository: networking ) ), router: ContactListRouterImpl( router: self.navigationController!, getLoginPage: getLogin, getConversationPage: getConversationPage ), update: update, removeAllLocalPassword: secureStore.removeAll) adapter.attach(tableView: tableView, presenter: presenter) setupTableView() setupUIButton() } public override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) presenter?.showContactsList() } public func update(_ viewState: ContactsListViewState) { startCallButton.isHidden = viewState.isButtonEnabled.not adapter.contactListViewState = viewState.contacts } @objc func logoutTapped() { presenter?.logout() } @objc func addLocalContact() { presenter?.addNewLocalContact(generateLocalContact.run()) } @objc func startButtonTapped() { presenter?.startCall() } private func setupUIButton() { startCallButton.translatesAutoresizingMaskIntoConstraints = false view.addSubview(startCallButton) NSLayoutConstraint.activate([ startCallButton.heightAnchor.constraint(equalToConstant: 50), startCallButton.widthAnchor.constraint(equalToConstant: 200), startCallButton.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -10), startCallButton.centerXAnchor.constraint(equalTo: view.centerXAnchor) ]) } private func setupTableView() { tableView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(tableView) NSLayoutConstraint.activate([ tableView.topAnchor.constraint(equalTo: view.topAnchor), tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor), tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor), tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor) ]) } } <file_sep>/Login/Tests/LoginTests/Presenter/LoginPresenterTests.swift import XCTest @testable import Login import RxSwift import Entities class LoginPresenterTests: XCTestCase { var sut: LoginPresenter! override func tearDown() { sut = nil super.tearDown() } func testloginChange_OnlyUsername() { let usr: String? = "USER" let pwd: String? = nil let expected = LoginViewState( errorMessage: nil, isLoading: false, buttonEnabled: false ) let loginInteractor = LoginIteractor( configuration: LoginInterarctorConfiguration( environment: MockEnvironment( asserDeleteUser: { XCTFail() }, asserUpdateUser: { _ in XCTFail() } ), repository: MockFailureLoginNetworking.shared, saveCredential: { _,_ in XCTFail() fatalError() } )) let sut = LoginPresenter( loginInteractor: loginInteractor, router: MockLoginRouter( assertMoveOnLoginSucced: { XCTFail() }), update: { newVS in XCTAssertEqual(newVS, expected) }) sut.loginChange(username: usr, password: pwd) } func testloginChange_OnlyPassword() { let usr: String? = nil let pwd: String? = "PWD" let expected = LoginViewState( errorMessage: nil, isLoading: false, buttonEnabled: false ) let loginInteractor = LoginIteractor( configuration: LoginInterarctorConfiguration( environment: MockEnvironment( asserDeleteUser: { XCTFail() }, asserUpdateUser: { _ in XCTFail() } ), repository: MockFailureLoginNetworking.shared, saveCredential: { _,_ in XCTFail() fatalError() } )) let sut = LoginPresenter( loginInteractor: loginInteractor, router: MockLoginRouter( assertMoveOnLoginSucced: { XCTFail() }), update: { newVS in XCTAssertEqual(newVS, expected) }) sut.loginChange(username: usr, password: pwd) } func testloginChange_BothField() { let usr: String? = "USR" let pwd: String? = "PWD" let expected = LoginViewState( errorMessage: nil, isLoading: false, buttonEnabled: true ) let loginInteractor = LoginIteractor( configuration: LoginInterarctorConfiguration( environment: MockEnvironment( asserDeleteUser: { XCTFail() }, asserUpdateUser: { _ in XCTFail() } ), repository: MockFailureLoginNetworking.shared, saveCredential: { _,_ in XCTFail() fatalError() } )) var finalVS: LoginViewState! let sut = LoginPresenter( loginInteractor: loginInteractor, router: MockLoginRouter(assertMoveOnLoginSucced: { XCTFail() }), update: { newVS in finalVS = newVS }) sut.loginChange(username: usr, password: pwd) XCTAssertEqual(finalVS, expected) } func testAskToLogin_Success() { let usr: String = "USR" let pwd: String = "PWD" let responseUser = User(username: "USR", firstName: "FN", lastName: "LN") let expected = LoginViewState( errorMessage: nil, isLoading: false, buttonEnabled: false ) let loginInteractor = LoginIteractor( configuration: LoginInterarctorConfiguration( environment: MockEnvironment( asserDeleteUser: { XCTFail() }, asserUpdateUser: { user in XCTAssertEqual(responseUser, user) } ), repository: MockSuccessLoginNetworking(user: responseUser), saveCredential: { _,_ in XCTAssertTrue(true) return .success(()) } )) var finalVS: LoginViewState! let sut = LoginPresenter( loginInteractor: loginInteractor, router: MockLoginRouter( assertMoveOnLoginSucced: { XCTAssertTrue(true) } ), update: { newVS in finalVS = newVS }) sut.askToLogin(username: usr, password: pwd) XCTAssertEqual(finalVS, expected) } func testAskToLogin_Failure() { let usr: String = "USR" let pwd: String = "PWD" let expected = LoginViewState( errorMessage: "Credenziali errate", isLoading: false, buttonEnabled: false ) let loginInteractor = LoginIteractor( configuration: LoginInterarctorConfiguration( environment: MockEnvironment( asserDeleteUser: { XCTFail() }, asserUpdateUser: { _ in XCTFail() } ), repository: MockFailureLoginNetworking.shared, saveCredential: { _,_ in XCTFail() fatalError() } )) var finalVS: LoginViewState! let sut = LoginPresenter( loginInteractor: loginInteractor, router: MockLoginRouter( assertMoveOnLoginSucced: { XCTFail() } ), update: { newVS in finalVS = newVS }) sut.askToLogin(username: usr, password: pwd) XCTAssertEqual(finalVS, expected) } } <file_sep>/ACMESecureStore/Sources/ACMESecureStore/ACMESecureStore.swift import SecureStore public enum ACMECredentialSecureStore { public static func getSecureStore() -> ACMESecureStore { SecureStore( secureStoreQueryable: CredentialSecureStore( service: "ACMECredential", accessGroup: nil) ) } } extension SecureStore: ACMESecureStore { public func set(_ value: String, for userAccount: String) -> Result<Void, Error> { return setValue(value, for: userAccount) .mapError { _ in ACMESecureStoreError.failure } } public func get(for userAccount: String) -> Result<String?, Error> { self.getValue(for: userAccount) .mapError { _ in ACMESecureStoreError.failure } } public func remove(for userAccount: String) -> Result<Void, Error> { self.removeValue(for: userAccount) .mapError { _ in ACMESecureStoreError.failure } } public func removeAll() -> Result<Void, Error> { self.removeAllValues() .mapError { _ in ACMESecureStoreError.failure } } } <file_sep>/Login/Sources/Login/Interactor/LoginInteractor.swift import Foundation import Entities import RxSwift import FunctionalKit import Architecture import NetworkingCommon struct LoginInterarctorConfiguration { let environment: Environment let repository: LoginNetworking let saveCredential: (_ value: String, _ userAccount: String) -> Result<Void, Error> } class LoginIteractor { let configuration: LoginInterarctorConfiguration init(configuration: LoginInterarctorConfiguration) { self.configuration = configuration } func doLogin(username: String, password: String) -> Observable<Result<User, ClientError>> { configuration.repository.askToLogin(user: username, password: password) .map { response -> Result<User, ClientError> in switch response { case let .success(user): return self.configuration.saveCredential("ACMEPassword", password) .fold(onSuccess: { self.configuration.environment.updateLoggedUser(user: user) return .success(user) }, onFailure: { error in //Missing error management return .failure(.badRequest) }) //Missing error management case .failure: return .failure(.badRequest) } } } } <file_sep>/NetworkingCommon/Sources/NetworkingCommon/ClientError.swift public enum ClientError: Error, Equatable { case undefined case badRequest case serverError case unauthorize } <file_sep>/Room/Sources/Room/Room/ACMEStream.swift import Foundation public struct ACMEStream: Stream { public var hasAudio: Bool public var hasVideo: Bool public var stream: Data public init( hasAudio: Bool, hasVideo: Bool, stream: Data ) { self.hasAudio = hasAudio self.hasVideo = hasVideo self.stream = stream } } <file_sep>/Entities/Sources/Entities/User.swift public struct User: Codable, Equatable { public let username: String? public let firstName: String? public let lastName: String? public init(username: String?, firstName: String?, lastName: String?) { self.username = username self.firstName = firstName self.lastName = lastName } } <file_sep>/ACME/App/PageFactory.swift import Foundation import UIKit import ACMESecureStore import Login import Entities import RxSwift import NetworkingCommon import ContactsList import FunctionalKit import Room class PageFactory { let secureStore: ACMESecureStore let environment: AppState let session: URLSession let baseURL: String let mainNavController: UINavigationController init( secureStore: ACMESecureStore, environment: AppState, session: URLSession = .shared, baseURL: String = "BASE_URL", mainNavController: UINavigationController ) { self.secureStore = secureStore self.environment = environment self.session = session self.baseURL = baseURL self.mainNavController = mainNavController } private(set) lazy var rootPage: UINavigationController = mainNavController |> f.with { (navController) in navController.setViewControllers([self.contactsListPage], animated: false) self.showLoginIfNeeded() } private lazy var loginPage = LoginPage( environment: environment, networking: LoginiNetworkingMock(), secureStore: secureStore ) private lazy var contactsListPage = ContactListPage( environment: environment, networking: ContactsListNetworkingMock(), getLogin: .pure(loginPage), getConversationPage: .pure(roomPage), secureStore: secureStore, generateLocalContact: Effect { Contact( id: "\(Int.random(in: 0...99999))", firstName: String.getRanomName(), lastName: String.getRanomName(), imageData: ["1","2","3","4"].randomElement()!.getImageName().jpegData(compressionQuality: 1)! ) } ) private lazy var roomPage = RoomPage( environment: environment, networking: RoomNetworkingMock() ) private func showLoginIfNeeded() { if self.environment.loggedUser.isNil { DispatchQueue.main.async { self.loginPage.modalPresentationStyle = .fullScreen self.mainNavController.present(self.loginPage, animated: true, completion: nil) } } } } fileprivate struct LoginiNetworkingMock: LoginNetworking { func askToLogin(user: String, password: String) -> Observable<Result<User, ClientError>> { .just(.success(User(username: "arinaldi", firstName: "Andrea", lastName: "Rinaldi"))) } var session: URLSession = .shared var baseURL: String = "" } fileprivate struct ContactsListNetworkingMock: ContactsListNetworking { func getContacts() -> Observable<Result<[Contact], ClientError>> { .just(.success([ Contact( id: "1", firstName: "Andrea", lastName: "Rinaldi", imageData: UIImage(named: "image")!.jpegData(compressionQuality: 1)!), Contact( id: "2", firstName: "Chiara", lastName: "Boccia", imageData: UIImage(named: "image2")!.jpegData(compressionQuality: 1)!), Contact( id: "3", firstName: "Marisa", lastName: "Bianchi", imageData: UIImage(named: "image3")!.jpegData(compressionQuality: 1)!), Contact( id: "4", firstName: "Giorgio", lastName: "Mastrota", imageData: UIImage(named: "image4")!.jpegData(compressionQuality: 1)!), Contact( id: "5", firstName: "Maria", lastName: "Morrone", imageData: UIImage(named: "image3")!.jpegData(compressionQuality: 1)!) ])) } var session: URLSession = .shared var baseURL: String = "" } fileprivate struct RoomNetworkingMock: RoomNetworking { var session: URLSession = .shared var baseURL: String = "" func startCall(with contact: Contact) -> Observable<Result<ACMEStream, ClientError>> { Observable .just( Result.success( ACMEStream( hasAudio: Bool.random(), hasVideo: Bool.random(), stream: contact.id.getImageName().jpegData(compressionQuality: 0)!) )) } } fileprivate extension String { func getImageName() -> UIImage { guard let id = Int(self) else { return UIImage() } switch id { case 1: return UIImage(named: "image")! case 2: return UIImage(named: "image2")! case 3: return UIImage(named: "image3")! case 4: return UIImage(named: "image4")! default: return UIImage(named: "image")! } } } fileprivate extension String { static func getRanomName() -> String { [ "CaioCalogero", "Calypso", "Camelia", "Cameron", "Camilla", "Camillo", "Candida", "Candido", "Carina", "Carla", "Carlo", "Carmela", "Carmelo", "Carolina", "Cassandra", "Caterina", "Cecilia", "Cedric", "Celesta", "Celeste", "Cesara", "Cesare", "Chandra", "Chantal", "Chiara", "Cino", "Cinzia", "Cirillo", "Ciro", "Claudia", "Claudio", "Clelia", "Clemente", "Clio", "Clizia", "Cloe", "Clorinda", "Clotilde", "Concetta", "Consolata", "Contessa", "Cora", "Cordelia", "Corinna", "Cornelia", "Corrado", "Cosetta", "Cosimo", "Costantino", "Costanza", "Costanzo", "Cristal", "Cristiana", "Cristiano", "Cristina", "Cristoforo", "Cruz", "Curzio" ].randomElement()! } } <file_sep>/ContactsList/Sources/ContactsList/View/ContactsListAdapter.swift import UIKit import RxSwift final class ContactsListAdapter: NSObject { private weak var tableView: UITableView? { didSet { tableView?.dataSource = self tableView?.delegate = self tableView?.allowsMultipleSelection = true tableView?.register(ContactCell.self, forCellReuseIdentifier: ContactCell.identifier) } } private weak var presenter: ContactsListPresenter? var contactListViewState: [ConctactCellViewState] = [] { didSet { guard oldValue != contactListViewState else { return } tableView?.reloadData() } } func attach(tableView: UITableView, presenter: ContactsListPresenter?) { self.tableView = tableView self.presenter = presenter } } extension ContactsListAdapter: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { contactListViewState.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: ContactCell.identifier) as? ContactCell else { fatalError("Error on dequeue") } cell.update(contactListViewState[indexPath.row]) return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { ContactCell.height } func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if (editingStyle == .delete) { presenter?.removeLocalContact(contactListViewState[indexPath.row].contactsId) } } } extension ContactsListAdapter: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) presenter?.itemSelected(contactId: contactListViewState[indexPath.row].contactsId) } } <file_sep>/NetworkingCommon/Tests/LinuxMain.swift import XCTest import NetworkingCommonTests var tests = [XCTestCaseEntry]() tests += NetworkingCommonTests.allTests() XCTMain(tests) <file_sep>/SecureStore/Sources/SecureStore/CredentialSecureStore.swift import Foundation import LocalAuthentication public struct CredentialSecureStore { let service: String let accessGroup: String? public init(service: String, accessGroup: String?) { self.service = service self.accessGroup = accessGroup } } extension CredentialSecureStore: SecureStoreQueryable { public var query: [String : Any] { var query: [String:Any] = [:] query[String(kSecClass)] = kSecClassGenericPassword query[String(kSecAttrService)] = service // Access group if target environment is not simulator #if !targetEnvironment(simulator) if let accessGroup = accessGroup { query[String(kSecAttrAccessGroup)] = accessGroup } #endif return query } } <file_sep>/ContactsList/Sources/ContactsList/Interactor/ContactsListInteractor.swift import Foundation import RxSwift import FunctionalKit import Architecture import Entities struct ContactsListInterarctorConfiguration { let environment: Environment let repository: ContactsListNetworking } struct ContactsListIteractor { let configuration: ContactsListInterarctorConfiguration init(configuration: ContactsListInterarctorConfiguration) { self.configuration = configuration } func getContacts() -> Observable<[Contact]> { configuration.repository .getContacts() .map { result in switch result { case let .success(contacts): return contacts case .failure: return [] } } } func getSelectedItems(contact: Contact) -> [Contact] { var newList = configuration.environment.selectedContacts if let index = configuration.environment.selectedContacts.firstIndex(where: { contact.id == $0.id }) { newList.remove(at: index) } else { newList.append(contact) } return newList } func buttonIsEnabled(selectedItems: [Contact]) -> Bool { let count = selectedItems.count if count > 0 && count <= 4 { return true } else { return false } } } <file_sep>/ACMESecureStore/Sources/ACMESecureStore/SecureStore.swift public protocol ACMESecureStore { func set(_ value: String, for userAccount: String) -> Result<Void, Error> func get(for userAccount: String) -> Result<String?, Error> func remove(for userAccount: String) -> Result<Void, Error> func removeAll() -> Result<Void, Error> } public enum ACMESecureStoreError: Error { case failure } <file_sep>/Login/Tests/LoginTests/TestUtils.swift @testable import Login import Architecture import Entities import Foundation import RxSwift import NetworkingCommon import ACMESecureStore struct MockEnvironment: Environment { let asserDeleteUser: () -> () let asserUpdateUser: (_ user: User) -> () func deleteLoggedUser() { asserDeleteUser() } var loggedUser: User? = nil func updateLoggedUser(user: User) { asserUpdateUser(user) } } struct MockFailureLoginNetworking: LoginNetworking { static let shared = MockFailureLoginNetworking() var session: URLSession = .shared var baseURL: String = "TEST" func askToLogin(user: String, password: String) -> Observable<Result<User, ClientError>> { .just(.failure(.badRequest)) } } struct MockSuccessLoginNetworking: LoginNetworking { let user: User var session: URLSession = .shared var baseURL: String = "TEST" func askToLogin(user: String, password: String) -> Observable<Result<User, ClientError>> { .just(.success(self.user)) } } struct MockLoginRouter: LoginRouter { var assertMoveOnLoginSucced: () -> () func moveOnLoginSucced() { assertMoveOnLoginSucced() } } struct MockACMESecureStore: ACMESecureStore { var set: Result<Void, Error> = .success(()) var get: Result<String?, Error> = .success("VALUE") var remove: Result<Void, Error> = .success(()) var removeAllValues: Result<Void, Error> = .success(()) func set(_ value: String, for userAccount: String) -> Result<Void, Error> { set } func get(for userAccount: String) -> Result<String?, Error> { get } func remove(for userAccount: String) -> Result<Void, Error> { remove } func removeAll() -> Result<Void, Error> { removeAllValues } } <file_sep>/ContactsList/Sources/ContactsList/View/ContactCell.swift import UIKit import Architecture import FunctionalKit class ContactCell: UITableViewCell, Updatable { typealias UpdateType = ConctactCellViewState static let identifier = "ContactCell" static let height: CGFloat = 90 private var contactImageView = UIImageView() private var contactLabel = UILabel() private var selectedLabe: UILabel = { let label = UILabel() label.textColor = .darkGray label.text = "Added" return label }() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) contactImageView.translatesAutoresizingMaskIntoConstraints = false contactLabel.translatesAutoresizingMaskIntoConstraints = false selectedLabe.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(contactImageView) contentView.addSubview(contactLabel) contentView.addSubview(selectedLabe) setupImage() setupLabel() setupSelectedImage() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func update(_ value: ConctactCellViewState) { contactImageView.image = UIImage(data: value.image) contactLabel.text = "\(value.firstName) \(value.lastName)" selectedLabe.isHidden = value.isSelected.not } private func setupImage() { NSLayoutConstraint.activate([ contactImageView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 10), contactImageView.heightAnchor.constraint(equalToConstant: 30), contactImageView.widthAnchor.constraint(equalToConstant: 30), contactImageView.centerYAnchor.constraint(equalTo: contentView.centerYAnchor) ]) } private func setupLabel() { NSLayoutConstraint.activate([ contactLabel.leadingAnchor.constraint(equalTo: contactImageView.trailingAnchor, constant: 10), contactLabel.centerYAnchor.constraint(equalTo: contentView.centerYAnchor) ]) } private func setupSelectedImage() { NSLayoutConstraint.activate([ selectedLabe.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -10), selectedLabe.centerYAnchor.constraint(equalTo: contentView.centerYAnchor) ]) } } <file_sep>/Login/Sources/Login/Networking/WSLoginModel.swift enum WSLoginModel { struct Request: Encodable { let username: String let password: String } struct Response: Decodable { let username: String let firstName: String let lastName: String } } <file_sep>/Architecture/Sources/Architecture/Environment.swift import Entities public protocol Environment { var loggedUser: User? { get } var selectedContacts: [Contact] { get } var localContacts: [Contact]? { get } func updateLoggedUser(user: User) func deleteLoggedUser() func updateRoomsPartecipand(contacts: [Contact]) func addLocalContact(_ contact: Contact) func removeLocalContact(_ contactId: String) func removeAll() } <file_sep>/Login/Sources/Login/View/LoginPage.swift import UIKit import RxSwift import Entities import ACMESecureStore import Architecture import FunctionalKit public class LoginPage: UIViewController, PageType { public typealias ViewState = LoginViewState typealias Presesnter = LoginPresenter public var presenter: LoginPresenter? let environment: Environment let networking: LoginNetworking let secureStore: ACMESecureStore let disposeBag = DisposeBag() public init( environment: Environment, networking: LoginNetworking, secureStore: ACMESecureStore ) { self.environment = environment self.networking = networking self.secureStore = secureStore super.init(nibName: "LoginPage", bundle: Bundle.module) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } @IBOutlet weak var userTextField: UITextField! { didSet { userTextField.addTarget(self, action: #selector(textFieldChange), for: .editingChanged) } } @IBOutlet weak var passwordTextField: UITextField! { didSet { passwordTextField.addTarget(self, action: #selector(textFieldChange), for: .editingChanged) } } @IBOutlet weak var loginButton: UIButton! { didSet { loginButton.setTitle("Sign in", for: .normal) loginButton.addTarget(self, action: #selector(askToLogin), for: .allEvents) } } @IBOutlet weak var errorLabel: UILabel! { didSet { errorLabel.textAlignment = .center } } public override func viewDidLoad() { super.viewDidLoad() presenter = LoginPresenter( loginInteractor: LoginIteractor( configuration: LoginInterarctorConfiguration( environment: environment, repository: networking, saveCredential: secureStore.set ) ), router: LoginRouterImpl(router: self), update: update ) } public func update(_ viewState: LoginViewState) { loginButton.isEnabled = viewState.buttonEnabled errorLabel.text = viewState.errorMessage } @objc private func textFieldChange() { self.presenter?.loginChange(username: self.userTextField.text, password: self.passwordTextField.text) } @objc private func askToLogin() { guard let username = self.userTextField.text, let password = self.passwordTextField.text else { return } self.presenter?.askToLogin(username: username, password: password) } } <file_sep>/NetworkingCommon/README.md # NetworkingCommon A description of this package. <file_sep>/Room/Sources/Room/Router/RoomRouter.swift import Architecture public protocol RoomRouter { func closeRoom() } public class RoomRouterImpl: RoomRouter { let router: Router init(router: Router) { self.router = router } public func closeRoom() { router.dismissPage(animated: true, completion: nil) } } <file_sep>/ContactsList/Sources/ContactsList/Presenter/ContactsListPresenter.swift import Foundation import RxSwift import Entities import Architecture public class ContactsListPresenter { var environment: Environment var contactsListInteractor: ContactsListIteractor var router: ContactsListRouter var contactsListViewState: ContactsListViewState = .starting { didSet { update(contactsListViewState) } } var update: (ContactsListViewState) -> () var removeAllLocalPassword: () -> Result<Void, Error> private let disposebag = DisposeBag() private var contacts: [Contact] = [] init( environment: Environment, contactsListInteractor: ContactsListIteractor, router: ContactsListRouter, update: @escaping (ContactsListViewState) -> (), removeAllLocalPassword: @escaping () -> Result<Void, Error> ) { self.environment = environment self.contactsListInteractor = contactsListInteractor self.router = router self.update = update self.removeAllLocalPassword = removeAllLocalPassword } func logout() { environment.deleteLoggedUser() environment.removeAll() contacts = .empty updateList() router.showLogin() } func showContactsList() { contactsListInteractor .getContacts() .subscribe(onNext: { [weak self] contacts in guard let self = self else { return } self.contacts = contacts + self.environment.localContacts.get(or: .empty) self.updateList() }).disposed(by: disposebag) } func itemSelected(contactId: String) { guard let contact = contacts.first(where: { $0.id == contactId }) else { return } environment.updateRoomsPartecipand( contacts: contactsListInteractor .getSelectedItems(contact: contact) ) contactsListViewState.update( contacts: contacts.map { contact in ConctactCellViewState( firstName: contact.firstName, lastName: contact.lastName, image: contact.imageData, isSelected: environment.selectedContacts.contains(contact), contactsId: contact.id ) } ) contactsListViewState.buttonIsVisible( contactsListInteractor .buttonIsEnabled(selectedItems: environment.selectedContacts) ) } func startCall() { router.startConversation() } func addNewLocalContact(_ contact: Contact) { environment.addLocalContact(contact) showContactsList() } func removeLocalContact(_ contactId: String) { environment.removeLocalContact(contactId) contactsListViewState.buttonIsVisible( contactsListInteractor .buttonIsEnabled(selectedItems: environment.selectedContacts) ) showContactsList() } private func updateList() { contactsListViewState.update( contacts: contacts.map { contact in ConctactCellViewState( firstName: contact.firstName, lastName: contact.lastName, image: contact.imageData, isSelected: environment.selectedContacts.contains(contact), contactsId: contact.id ) } ) } } fileprivate extension ContactsListViewState { mutating func update(contacts: [ConctactCellViewState]) { self.contacts = contacts } mutating func buttonIsVisible(_ bool: Bool) { self.isButtonEnabled = bool } } <file_sep>/Architecture/Sources/Architecture/UIViewController+Router.swift import UIKit extension UIViewController: Router { public func presentPage(_ module: Presentable, animated: Bool, _ completion: (() -> Void)?) { let destination = module.presented() destination.modalPresentationStyle = .fullScreen present(destination, animated: animated, completion: completion) } public func dismissPage(animated: Bool, completion: (() -> Void)?) { self.dismiss(animated: true, completion: nil) } public func pushPage(_ module: Presentable, animated: Bool) { navigationController?.pushViewController(module.presented(), animated: animated) } public func popPage(animated: Bool) { navigationController?.popViewController(animated: animated) } public func setAsRoot(_ module: Presentable, animated: Bool) { navigationController?.setViewControllers([module.presented()], animated: animated) } public func popToRootPage(animated: Bool) { navigationController?.popToRootViewController(animated: animated) } } <file_sep>/NetworkingCommon/Sources/NetworkingCommon/WebRepository.swift import Foundation import RxSwift public protocol WebRepository { var session: URLSession { get } var baseURL: String { get } } public extension WebRepository { func call<Value>(endpoint: APICall, httpCodes: HTTPCodes = .success) -> Observable<Result<Value, ClientError>> where Value: Decodable { do { let request = try endpoint.urlRequest(baseURL: baseURL) return Observable<Result<Value, ClientError>>.create { observer -> Disposable in let task = session.dataTask(with: request) { (data, response, error) in guard let data = data, let value = try? JSONDecoder().decode(Value.self, from: data) else { return observer.onNext(.failure(.undefined)) } if error != nil { return observer.onNext(.failure(.badRequest)) } observer.onNext(.success(value)) } task.resume() return Disposables.create { task.cancel() } } } catch { return .just(.failure(.badRequest)) } } } <file_sep>/Architecture/Sources/Architecture/PageType.swift import UIKit public protocol PageType: UIViewController & Updatable { associatedtype ViewState associatedtype Presenter var presenter: Presenter? { get } func update(_ viewState: ViewState) } <file_sep>/Login/Sources/Login/Presenter/LoginPresenter.swift import Foundation import RxSwift public class LoginPresenter { var loginInteractor: LoginIteractor var router: LoginRouter var loginViewState: LoginViewState = .starting { didSet { update(loginViewState) } } var update: (LoginViewState) -> () private let disposebag = DisposeBag() init(loginInteractor: LoginIteractor, router: LoginRouter, update: @escaping (LoginViewState) -> ()) { self.loginInteractor = loginInteractor self.router = router self.update = update update(loginViewState) } func loginChange(username: String?, password: String?) { let usr = username?.isEmpty let psw = password?.isEmpty if usr == false && psw == false { loginViewState.setLoginButtonEnabled(true) } else { loginViewState.setLoginButtonEnabled(false) } } func askToLogin(username: String, password: String) { loginViewState.startLoading() loginViewState.setLoginButtonEnabled(false) loginViewState.showError(message: "") loginInteractor .doLogin(username: username, password: <PASSWORD>) .observeOn(MainScheduler()) .subscribe(onNext: { [weak self] result in guard let self = self else { return } self.loginViewState.stopLoading() self.loginViewState.setLoginButtonEnabled(true) switch result { case .success: self.loginViewState.startLoading() self.router.moveOnLoginSucced() case .failure: self.loginViewState.showError(message: "Credenziali errate") } }) .disposed(by: disposebag) } } fileprivate extension LoginViewState { mutating func setLoginButtonEnabled(_ value: Bool) { buttonEnabled = value } mutating func startLoading() { isLoading = true } mutating func stopLoading() { isLoading = false } mutating func showError(message: String) { errorMessage = message } } <file_sep>/Login/Tests/LoginTests/View/LoginPageTests.swift @testable import Login import XCTest import Entities class LoginPageTests: XCTestCase { var sut: LoginPage! override func setUp() { super.setUp() sut = LoginPage( environment: MockEnvironment( asserDeleteUser: { XCTFail() }, asserUpdateUser: { _ in XCTFail() }), networking: MockSuccessLoginNetworking( user: User(username: nil, firstName: nil, lastName: nil) ), secureStore: MockACMESecureStore() ) _ = sut.view } override func tearDown() { sut = nil super.tearDown() } func testUpdate_EmptyPage() { let vs = LoginViewState( errorMessage: nil, isLoading: false, buttonEnabled: false ) sut.update(vs) } } <file_sep>/NetworkingCommon/Sources/NetworkingCommon/APICall.swift import Foundation public protocol APICall { var path: String { get } var method: String { get } var headers: [String:String]? { get } func body() throws -> Data? } public enum APIError: Swift.Error { case invalidURL case httpCode(HTTPCode) case unexpectedResponse } extension APIError: LocalizedError { public var errorDescription: String? { switch self { case .invalidURL: return "Invalid URL" case let .httpCode(code): return "Unexpected HTTP code: \(code)" case .unexpectedResponse: return "Unexpected response from the server" } } } extension APICall { public func urlRequest(baseURL: String) throws -> URLRequest { guard let url = URL(string: baseURL + path) else { throw APIError.invalidURL } var components = URLComponents(url: url, resolvingAgainstBaseURL: true) components?.queryItems = headers?.map { (key, value) in URLQueryItem(name: key, value: value) } guard let urlComponents = components?.url else { throw APIError.invalidURL } var request = URLRequest(url: urlComponents) request.httpMethod = method request.allHTTPHeaderFields = headers request.httpBody = try body() return request } } public typealias HTTPCode = Int public typealias HTTPCodes = Range<HTTPCode> public extension HTTPCodes { static let success = 200 ..< 300 } <file_sep>/Architecture/Sources/Architecture/Updatable.swift public protocol Updatable { associatedtype UpdateType func update(_ value: UpdateType) } <file_sep>/ContactsList/Sources/ContactsList/Router/ContactsListRouter.swift import Architecture import FunctionalKit protocol ContactsListRouter { func showLogin() func startConversation() } class ContactListRouterImpl: ContactsListRouter { let router: Router let getLoginPage: Effect<Presentable> let getConversationPage: Effect<Presentable> init( router: Router, getLoginPage: Effect<Presentable>, getConversationPage: Effect<Presentable> ) { self.router = router self.getLoginPage = getLoginPage self.getConversationPage = getConversationPage } func showLogin() { router.presentPage(getLoginPage.run(), animated: true, nil) } func startConversation() { router.presentPage(getConversationPage.run(), animated: true, nil) } } <file_sep>/Login/Sources/Login/Networking/LoginNetworking.swift import Foundation import RxSwift import Entities import NetworkingCommon public protocol LoginNetworking: WebRepository { func askToLogin(user: String, password: String) -> Observable<Result<User, ClientError>> } public struct LoginNetworkingImpl: LoginNetworking { public var session: URLSession public var baseURL: String public init(session: URLSession, baseURL: String) { self.session = session self.baseURL = baseURL } public func askToLogin(user: String, password: String) -> Observable<Result<User, ClientError>> { call(endpoint: API.askToLogin(user: user, password: password)) } } fileprivate extension LoginNetworkingImpl { enum API { case askToLogin(user: String, password: String) } } extension LoginNetworkingImpl.API: APICall { var path: String { switch self { case .askToLogin: return "path/to/login" } } var method: String { "POST" } var headers: [String : String]? { nil } func body() throws -> Data? { switch self { case let .askToLogin(user: user, password: <PASSWORD>): let user = WSLoginModel.Request(username: user, password: <PASSWORD>) return try? JSONEncoder().encode(user) } } } <file_sep>/Architecture/Package.swift // swift-tools-version:5.3 import PackageDescription let package = Package( name: "Architecture", products: [ .library( name: "Architecture", targets: ["Architecture"]), ], dependencies: [ .package(path: "../Entities") ], targets: [ .target( name: "Architecture", dependencies: ["Entities"]), .testTarget( name: "ArchitectureTests", dependencies: ["Architecture"]), ] ) <file_sep>/ACME/Operators/Operators.swift infix operator |> func |> <A, B>(a: A, f: (A) -> B) -> B { return f(a) } <file_sep>/ContactsList/Sources/ContactsList/Networking/ContactsListNetworking.swift import Foundation import NetworkingCommon import RxSwift import Entities public protocol ContactsListNetworking: WebRepository { func getContacts() -> Observable<Result<[Contact], ClientError>> } public struct ContactsListNetworkingImpl: ContactsListNetworking { public var session: URLSession public var baseURL: String public init(session: URLSession, baseURL: String) { self.session = session self.baseURL = baseURL } public func getContacts() -> Observable<Result<[Contact], ClientError>> { let response: Observable<Result<WSContactsModel.Response, ClientError>> = call(endpoint: API.getContacts) return response.map { result -> Result<[Contact], ClientError> in result.map { contacts -> [Contact] in contacts.contacts.map { Contact( id: $0.id, firstName: $0.firstName, lastName: $0.lastName, imageData: $0.avatar ) } } } } } fileprivate extension ContactsListNetworkingImpl { enum API { case getContacts } } extension ContactsListNetworkingImpl.API: APICall { var path: String { switch self { case .getContacts: return "path/to/get/contacts" } } var method: String { "GET" } var headers: [String : String]? { ["jwt-token": "TE<PASSWORD>"] } func body() throws -> Data? { nil } } <file_sep>/ACMESecureStore/README.md # ACMESecureStore A description of this package. <file_sep>/Room/Sources/Room/Presenter/RoomPresenter.swift import RxSwift import Entities import Architecture import FunctionalKit public class RoomPresenter { var interactor: RoomInteractor var router: RoomRouter var environment: Environment var viewState: RoomViewState = .starting { didSet { update(viewState) } } var update: (RoomViewState) -> () private let disposeBag = DisposeBag() init(interactor: RoomInteractor, router: RoomRouter, environment: Environment, update: @escaping (RoomViewState) -> () ) { self.interactor = interactor self.router = router self.environment = environment self.update = update } func closeRoom() { router.closeRoom() } func startCall() { interactor .startCall(with: environment.selectedContacts) .subscribe(onNext: { self.viewState.updateRoomContacts(contacts: $0) }) .disposed(by: disposeBag) } func addStreamToCall(stream: Stream) { //Manage adding } func removeStreamFromCall(stream: Stream) { //Manage removing } } fileprivate extension RoomViewState { mutating func updateRoomContacts(contacts: [Pair<Contact, Stream>]) { self.contacts = contacts } } <file_sep>/SecureStore/Sources/SecureStore/SecureStoreQueryable.swift import Foundation public protocol SecureStoreQueryable { var query: [String: Any] { get } } <file_sep>/Room/Sources/Room/Interactor/RoomIntearctor.swift import Entities import RxSwift import Architecture import FunctionalKit struct RoomInteractorConfiguration { let environment: Environment let repository: RoomNetworking } struct RoomInteractor { let configuration: RoomInteractorConfiguration func startCall(with contacts: [Contact]) -> Observable<[Pair<Contact, Stream>]> { Observable.combineLatest( contacts.map { contact in configuration.repository .startCall(with: contact) .compactMap { $0.toOptionalValue() } .map { stream in Pair(contact, stream) } } ) } } <file_sep>/Login/Sources/Login/View/LoginViewState.swift import Foundation public struct LoginViewState: Equatable { public var errorMessage: String? public var isLoading: Bool public var buttonEnabled: Bool } extension LoginViewState { static let starting = LoginViewState(isLoading: false, buttonEnabled: false) } <file_sep>/ContactsList/Sources/ContactsList/View/ContactCellViewState.swift import Foundation struct ConctactCellViewState: Equatable { var firstName: String var lastName: String var image: Data var isSelected: Bool var contactsId: String } <file_sep>/Room/README.md # Room A description of this package. <file_sep>/Architecture/Sources/Architecture/UIViewController+Presenttable.swift import UIKit extension UIViewController: Presentable { public func presented() -> UIViewController { return self } } extension Presentable where Self: UIViewController { public func presented() -> Self { return self } } <file_sep>/Room/Sources/Room/View/ContactViewState.swift import Foundation struct ContactsViewState { let name: String let hasVideo: Bool let hasAudio: Bool let image: Data? } <file_sep>/ACMESecureStore/Tests/LinuxMain.swift import XCTest import ACMESecureStoreTests var tests = [XCTestCaseEntry]() tests += ACMESecureStoreTests.allTests() XCTMain(tests) <file_sep>/Room/Sources/Room/View/RoomPage.swift import Foundation import UIKit import Architecture import AVFoundation public class RoomPage: UIViewController, PageType, CameraSession { public typealias ViewState = RoomViewState public typealias Presenter = RoomPresenter //MARK: CameraSession var previewFrame: CGRect { rearCameraView.frame} var captureSession = AVCaptureSession() var stillImageOutput = AVCapturePhotoOutput() lazy var videoPreviewLayer: AVCaptureVideoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession) //MARK: Views private let closeButton: UIButton = { let button = UIButton() button.setTitle("CLOSE", for: .normal) button.backgroundColor = .white button.setTitleColor(.gray, for: .normal) button.layer.cornerRadius = 10 button.addTarget(self, action: #selector(closeButtonTapped), for: .touchUpInside) return button }() private let rearCameraView: UIView = { let view = UIView() view.backgroundColor = .gray view.layer.cornerRadius = 10 return view }() private let firstContactCameraView: ContactView = { let view = ContactView() view.setupUI() return view }() private let secondContactCameraView: ContactView = { let view = ContactView() view.setupUI() return view }() private let thirdContactCameraView: ContactView = { let view = ContactView() view.setupUI() return view }() private let fourthContactCameraView: ContactView = { let view = ContactView() view.setupUI() return view }() public var presenter: RoomPresenter? public let environment: Environment public let networking: RoomNetworking private let room = Room() public init( environment: Environment, networking: RoomNetworking ) { self.environment = environment self.networking = networking super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } public override func viewDidLoad() { super.viewDidLoad() presenter = RoomPresenter( interactor: RoomInteractor( configuration: RoomInteractorConfiguration( environment: environment, repository: networking)), router: RoomRouterImpl(router: self), environment: environment, update: update ) room.delegate = self } public override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) presenter?.startCall() setupRearCamera() setupCloseButton() } public override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) frontCamerarRunning() } public override func viewDidDisappear(_ animated: Bool) { frontCameraStop() } func setupLivePreview() { DispatchQueue.main.async { [weak self] in self?.videoPreviewLayer.frame = self?.rearCameraView.bounds ?? .zero } videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession) videoPreviewLayer.videoGravity = .resizeAspect videoPreviewLayer.connection?.videoOrientation = .portrait rearCameraView.layer.addSublayer(videoPreviewLayer) } public func update(_ value: RoomViewState) { switch value.contacts.count { case 1: setupOneContact() let (contact, stream) = value.contacts[0].unwrap firstContactCameraView .update(ContactsViewState( name: contact.firstName, hasVideo: stream.hasVideo, hasAudio: stream.hasAudio, image: stream.stream) ) case 2: setupTwoContacts() let (contact1, stream1) = value.contacts[0].unwrap firstContactCameraView .update(ContactsViewState( name: contact1.firstName, hasVideo: stream1.hasVideo, hasAudio: stream1.hasAudio, image: stream1.stream) ) let (contact2, stream2) = value.contacts[1].unwrap secondContactCameraView .update(ContactsViewState( name: contact2.firstName, hasVideo: stream2.hasVideo, hasAudio: stream2.hasAudio, image: stream2.stream) ) case 3: setupThreeContacts() let (contact1, stream1) = value.contacts[0].unwrap firstContactCameraView .update(ContactsViewState( name: contact1.firstName, hasVideo: stream1.hasVideo, hasAudio: stream1.hasAudio, image: stream1.stream) ) let (contact2, stream2) = value.contacts[1].unwrap secondContactCameraView .update(ContactsViewState( name: contact2.firstName, hasVideo: stream2.hasVideo, hasAudio: stream2.hasAudio, image: stream2.stream) ) let (contact3, stream3) = value.contacts[2].unwrap thirdContactCameraView .update(ContactsViewState( name: contact3.firstName, hasVideo: stream3.hasVideo, hasAudio: stream3.hasAudio, image: stream3.stream) ) case 4: setupFourContacts() let (contact1, stream1) = value.contacts[0].unwrap firstContactCameraView .update(ContactsViewState( name: contact1.firstName, hasVideo: stream1.hasVideo, hasAudio: stream1.hasAudio, image: stream1.stream) ) let (contact2, stream2) = value.contacts[1].unwrap secondContactCameraView .update(ContactsViewState( name: contact2.firstName, hasVideo: stream2.hasVideo, hasAudio: stream2.hasAudio, image: stream2.stream) ) let (contact3, stream3) = value.contacts[2].unwrap thirdContactCameraView .update(ContactsViewState( name: contact3.firstName, hasVideo: stream3.hasVideo, hasAudio: stream3.hasAudio, image: stream3.stream) ) let (contact4, stream4) = value.contacts[3].unwrap fourthContactCameraView .update(ContactsViewState( name: contact4.firstName, hasVideo: stream4.hasVideo, hasAudio: stream4.hasAudio, image: stream4.stream) ) default: fatalError("You can't show more than four contacts") } } @objc func closeButtonTapped() { presenter?.closeRoom() } private func setupCloseButton() { closeButton.removeFromSuperview() closeButton.translatesAutoresizingMaskIntoConstraints = false view.addSubview(closeButton) NSLayoutConstraint.activate([ closeButton.heightAnchor.constraint(equalToConstant: 50), closeButton.widthAnchor.constraint(equalToConstant: 100), closeButton.topAnchor.constraint(equalTo: view.topAnchor, constant: 20), closeButton.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 10) ]) } private func setupRearCamera() { rearCameraView.removeFromSuperview() rearCameraView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(rearCameraView) NSLayoutConstraint.activate([ rearCameraView.heightAnchor.constraint(equalToConstant: 120), rearCameraView.widthAnchor.constraint(equalToConstant: 100), rearCameraView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -30), rearCameraView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20) ]) } private func setupOneContact() { firstContactCameraView.removeFromSuperview() firstContactCameraView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(firstContactCameraView) NSLayoutConstraint.activate([ firstContactCameraView.topAnchor.constraint(equalTo: view.topAnchor), firstContactCameraView.leadingAnchor.constraint(equalTo: view.leadingAnchor), firstContactCameraView.bottomAnchor.constraint(equalTo: view.bottomAnchor), firstContactCameraView.trailingAnchor.constraint(equalTo: view.trailingAnchor) ]) } private func setupTwoContacts() { firstContactCameraView.removeFromSuperview() firstContactCameraView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(firstContactCameraView) NSLayoutConstraint.activate([ firstContactCameraView.heightAnchor .constraint(equalToConstant: view.bounds.height/2), firstContactCameraView.topAnchor .constraint(equalTo: view.topAnchor), firstContactCameraView.leadingAnchor .constraint(equalTo: view.leadingAnchor), firstContactCameraView.trailingAnchor .constraint(equalTo: view.trailingAnchor) ]) secondContactCameraView.removeFromSuperview() secondContactCameraView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(secondContactCameraView) NSLayoutConstraint.activate([ secondContactCameraView.topAnchor .constraint(equalTo: firstContactCameraView.bottomAnchor), secondContactCameraView.leadingAnchor .constraint(equalTo: view.leadingAnchor), secondContactCameraView.bottomAnchor .constraint(equalTo: view.bottomAnchor), secondContactCameraView.trailingAnchor .constraint(equalTo: view.trailingAnchor) ]) } private func setupThreeContacts() { firstContactCameraView.removeFromSuperview() secondContactCameraView.removeFromSuperview() thirdContactCameraView.removeFromSuperview() firstContactCameraView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(firstContactCameraView) secondContactCameraView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(secondContactCameraView) thirdContactCameraView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(thirdContactCameraView) NSLayoutConstraint.activate([ firstContactCameraView.heightAnchor .constraint(equalToConstant: view.bounds.height/2), firstContactCameraView.topAnchor .constraint(equalTo: view.topAnchor), firstContactCameraView.leadingAnchor .constraint(equalTo: view.leadingAnchor), firstContactCameraView.trailingAnchor .constraint(equalTo: view.trailingAnchor) ]) NSLayoutConstraint.activate([ secondContactCameraView.leadingAnchor .constraint(equalTo: view.leadingAnchor), secondContactCameraView.bottomAnchor .constraint(equalTo: view.bottomAnchor), secondContactCameraView.heightAnchor .constraint(equalToConstant: view.bounds.height/2), secondContactCameraView.widthAnchor .constraint(equalToConstant: view.bounds.width/2) ]) NSLayoutConstraint.activate([ thirdContactCameraView.heightAnchor .constraint(equalToConstant: view.bounds.height/2), thirdContactCameraView.widthAnchor .constraint(equalToConstant: view.bounds.width/2), thirdContactCameraView.bottomAnchor .constraint(equalTo: view.bottomAnchor), thirdContactCameraView.trailingAnchor .constraint(equalTo: view.trailingAnchor) ]) } private func setupFourContacts() { firstContactCameraView.removeFromSuperview() firstContactCameraView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(firstContactCameraView) secondContactCameraView.removeFromSuperview() secondContactCameraView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(secondContactCameraView) thirdContactCameraView.removeFromSuperview() thirdContactCameraView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(thirdContactCameraView) fourthContactCameraView.removeFromSuperview() fourthContactCameraView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(fourthContactCameraView) NSLayoutConstraint.activate([ firstContactCameraView.heightAnchor .constraint(equalToConstant: view.bounds.height/2), firstContactCameraView.widthAnchor .constraint(equalToConstant: view.bounds.width/2), firstContactCameraView.topAnchor .constraint(equalTo: view.topAnchor), firstContactCameraView.leadingAnchor .constraint(equalTo: view.leadingAnchor) ]) NSLayoutConstraint.activate([ secondContactCameraView.heightAnchor .constraint(equalToConstant: view.bounds.height/2), secondContactCameraView.widthAnchor .constraint(equalToConstant: view.bounds.width/2), secondContactCameraView.topAnchor .constraint(equalTo: view.topAnchor), secondContactCameraView.trailingAnchor .constraint(equalTo: view.trailingAnchor) ]) NSLayoutConstraint.activate([ thirdContactCameraView.heightAnchor .constraint(equalToConstant: view.bounds.height/2), thirdContactCameraView.widthAnchor .constraint(equalToConstant: view.bounds.width/2), thirdContactCameraView.bottomAnchor .constraint(equalTo: view.bottomAnchor), thirdContactCameraView.leadingAnchor .constraint(equalTo: view.leadingAnchor) ]) NSLayoutConstraint.activate([ fourthContactCameraView.heightAnchor .constraint(equalToConstant: view.bounds.height/2), fourthContactCameraView.widthAnchor .constraint(equalToConstant: view.bounds.width/2), fourthContactCameraView.bottomAnchor .constraint(equalTo: view.bottomAnchor), fourthContactCameraView.trailingAnchor .constraint(equalTo: view.trailingAnchor) ]) } } extension RoomPage: RoomDelegate { public func didConnect() { frontCamerarRunning() } public func didDisconnect() { frontCameraStop() } public func didAddStrem(_ stream: Stream) { presenter?.addStreamToCall(stream: stream) } public func didRemoveSteram(_ stream: Stream) { presenter?.removeStreamFromCall(stream: stream) } } <file_sep>/Login/Sources/Login/Router/LoginRouter.swift import Architecture protocol LoginRouter { func moveOnLoginSucced() } class LoginRouterImpl: LoginRouter { let router: Router init(router: Router) { self.router = router } func moveOnLoginSucced() { router.dismissPage(animated: true, completion: nil) } } <file_sep>/Room/Sources/Room/Room/Room.swift class Room { var delegate: RoomDelegate? func connect() { delegate?.didConnect() } func disconnet() { delegate?.didConnect() } } <file_sep>/Room/Sources/Room/Room/Stream.swift import Foundation public protocol Stream { var hasAudio: Bool { get } var hasVideo: Bool { get } var stream: Data { get } } <file_sep>/ContactsList/Sources/ContactsList/View/ContactsListViewState.swift import Entities public struct ContactsListViewState { var isButtonEnabled: Bool var contacts: [ConctactCellViewState] } extension ContactsListViewState { static let starting = ContactsListViewState( isButtonEnabled: false, contacts: [] ) } <file_sep>/Room/Sources/Room/View/RoomViewState.swift import Entities import FunctionalKit public struct RoomViewState { var contacts: [Pair<Contact, Stream>] } extension RoomViewState { static let starting = RoomViewState(contacts: []) } <file_sep>/ACME/App/AppState.swift import Entities import Architecture class AppState: Environment { var selectedContacts: [Contact] = [] @CustomObjectUserDefault("logged_user") var loggedUser: User? @CustomObjectUserDefault("local_contacts") var localContacts: [Contact]? func updateRoomsPartecipand(contacts: [Contact]) { selectedContacts = contacts } func updateLoggedUser(user: User) { loggedUser = user } func deleteLoggedUser() { loggedUser = nil } func addLocalContact(_ contact: Contact) { localContacts?.append(contact) } func removeLocalContact(_ contactId: String) { localContacts?.removeAll(where: { $0.id == contactId }) selectedContacts.removeAll(where: { $0.id == contactId }) print(selectedContacts) } func removeAll() { localContacts?.removeAll() selectedContacts.removeAll() } }
1cfa18e410f96d5ca9c067d8707fa4fbcbfb9993
[ "Swift", "Markdown" ]
64
Swift
AndreaRR18/ACME-App
2e7cf804ba89026aa6a7dfe94dc015e5c1181621
b7c0f460cc626c4597b188ced4c4e8c39f781f08
refs/heads/master
<file_sep>#!/usr/bin/env node /* ----------------------------------------------------------------------------- * Sass Director: generate Sass directory structures from Sass manifest files * * Bash script: <NAME>, <NAME> * Licensed MIT: https://github.com/una/sass-director * -------------------------------------------------------------------------- */ function init(argv) { var fullpath = path.resolve(argv[2]); cached = { directory: [], fullpath: [] }; created = { directory: [], fullpath: [] }; manifest = { basename: path.basename(fullpath), directory: path.dirname(fullpath), fullpath: fullpath, prefix: argv.includes('--no-underscore') ? '' : '_', suffix: argv.includes('--sass') ? '.sass' : '.scss', watch: argv.includes('--watch') }; matches = { commentMultiline: /\/\*[\W\w]+?\*\//g, commentSingleline: /\/\/[^\n]+/g, importAll: /(?:^\s*|;\s+|\n)@import[ \t]+(['"])(.+?)\1/g, importOne: /@import[ \t]+(['"])(.+?)\1/ }; message = { created: 'Created "$1"', deleted: 'Deleted "$1"', failed: ' FAILED', reading: 'Reading "$1"', watching: 'Watching "$1"' }; // watch manifest directory if --watch argument exists if (manifest.watch) { var log = message.watching.replace('$1', manifest.basename); try { fs.watch(manifest.directory, function () { // run if manifest was modified if (manifest.fullpath === manifest.directory + '/' + arguments[1]) { main(); } }); console.log(log); } catch (error) { console.log(log + message.failed); } } // otherwise, run else { main(); } } function main() { var data; // read manifest and strip comments try { data = fs.readFileSync(manifest.fullpath, 'utf8').replace(matches.commentMultiline, '').replace(matches.commentSingleline, ''); if (!manifest.watch) { console.log(message.reading.replace('$1', manifest.basename)); } } // exit on read error catch (error) { console.log(message.reading.replace('$1', manifest.basename) + failed); process.exit(1); } // match all import statements (data.match(matches.importAll) || []).forEach(function (importStatement) { // get relative path of import statement var relpath = importStatement.match(matches.importOne)[2], // set import path basename = relpath.slice(-5) === manifest.suffix ? relpath : relpath + manifest.suffix, directory = path.resolve(manifest.directory + '/' + path.dirname(basename)), fullpath = path.resolve(directory + '/' + manifest.prefix + path.basename(basename)); // conditionally create every directory required directory.split('/').reduce(function (lastDirectory, directory) { directory = lastDirectory + '/' + directory; if (!fs.isDirectorySync(directory) && !created.directory.includes(directory)) { var log = message.created.replace('$1', path.basename(directory)); try { fs.mkdirSync(directory); created.directory.push(directory); console.log(log); } catch (error) { console.log(log + message.failed); process.exit(1); } } return directory; }); // conditionally create every file required if (!fs.isFileSync(fullpath) && !created.fullpath.includes(fullpath)) { var log = message.created.replace('$1', path.basename(fullpath)); try { fs.writeFileSync(fullpath, ''); created.fullpath.push(fullpath); console.log(log); } catch (error) { console.log(log + message.failed); process.exit(1); } } }); // remove files in cache that are empty and not recently created cached.fullpath.forEach(function (fullpath) { var log = message.deleted.replace('$1', path.basename(fullpath)); try { if (fs.isEmptySync(fullpath) && created.fullpath.indexOf(fullpath) === -1) { fs.unlinkSync(fullpath); console.log(log); } } catch (error) { console.log(log + message.failed); } }); // remove directories in cache that are empty or not recently created cached.directory.forEach(function (directory) { var log = message.deleted.replace('$1', path.basename(directory)); try { if (fs.isEmptySync(directory) || created.directory.indexOf(directory) === -1) { fs.rmdirSync(directory); console.log(log); } } catch (error) { console.log(log + message.failed); } }); // reset cached cached.directory = created.directory.splice(0); cached.fullpath = created.fullpath.splice(0); } /* Setup * -------------------------------------------------------------------------- */ var fs = require('fs'), path = require('path'), cached, created, manifest, matches, message; if (!Array.prototype.includes) { Object.defineProperty(Array.prototype, 'includes', { value: function includes() { return Array.prototype.indexOf.apply(this, arguments) !== -1; } }); } if (!fs.isDirectorySync) { fs.isDirectorySync = function isDirectorySync(path) { return fs.existsSync(path) && fs.statSync(path).isDirectory(); }; } if (!fs.isEmptySync) { fs.isEmptySync = function isEmptySync(path) { try { if (fs.statSync(path).isDirectory()) { return !(fs.readdirSync(path) || []).length; } return !(fs.readFileSync(path) || []).length; } catch (error) { return true; } }; } if (!fs.isFileSync) { fs.isFileSync = function isFileSync(path) { return fs.existsSync(path) && fs.statSync(path).isFile(); }; } init(process.argv);
9decfdd2cdc69bb5aebeda9dff9e727d0ec95285
[ "JavaScript" ]
1
JavaScript
jonathantneal/sass-director
5c828b22a4c885ddaff7d913b8d478bda98c1e98
7d40da6c95d9cc352c9fb3d749df0b676d5d7c7b
refs/heads/main
<repo_name>mayur-keswani/MugglePexels-using-useState-hook<file_sep>/src/Components/UI/Navigation/Navigation.js import React, { Fragment , useState , useContext} from 'react' import Logo from '../Logo/Logo' import UserContext from '../../../Context/UserContext' import { Link } from 'react-router-dom'; // import {BsSearch} from 'react-icons/bs' // import {MdCollectionsBookmark} from 'react-icons/md' import { Collapse, Navbar, NavbarToggler, NavbarBrand, Nav, NavItem, NavLink, Button, NavbarText } from 'reactstrap'; const Navigation = () =>{ const [isOpen, setIsOpen] = useState(false); // const [searchInput,setSearchInput] = useState("") const context=useContext(UserContext) const toggle = () => setIsOpen(!isOpen); return( <Fragment> <Navbar dark className="m-0 p-0" expand="sm"> <div><Logo height="50px"/></div> <NavbarBrand href="/" className="companyName font-weight-bold">MugglePexels</NavbarBrand> <NavbarToggler onClick={toggle} /> <Collapse isOpen={isOpen} className="collapse-navbar" navbar style={{backgroundColor:(isOpen && window.innerWidth<576) ?"#242B2E":"transparent"}}> <NavbarText>{context.user?`Hello ${context.user.email}`:"Hello Muggle !!"}</NavbarText> <Nav className="ml-auto p-3 auto text-white" navbar> { context.user? (<NavItem > <NavLink tag={Link} to="/" className="text-white" onClick={()=>{ localStorage.removeItem("user"); context.setUser(null) }}> {isOpen?"Logout": <Button color="info" size="lg"> Logout </Button>} </NavLink> </NavItem>): (<NavItem > <NavLink tag={Link} to="/signup" className="text-white"> {isOpen?"Join":<Button color="info" size="lg">Join</Button>} </NavLink> </NavItem>) } </Nav> </Collapse> </Navbar> </Fragment> ) } export default Navigation<file_sep>/src/Components/Collections/CollectionItem.js import React , {Fragment} from 'react' import { Button , Row } from 'reactstrap' // import {IoIosRemoveCircle} from 'react-icons/io' const CollectionItem = ({collection_items,addInCollection}) =>{ let content=null console.log(collection_items.items) if(typeof collection_items.items.length !== typeof undefined){ content=(collection_items.items.map(prod=>{ if(prod) return ( <img src={prod.small_image} className="img-thumbnail img-fluid p-2" alt={prod.id} width="220px" height="300px"/> ) else return null })) }else{ content=(<h2>No items in this collection</h2>) } return( <Fragment> <Row> <div> <label>{collection_items.name}</label> <Button color="info" onClick={addInCollection} className="btn-add p-2" >Add Here</Button> <span className="triangle-topright"></span> </div> <div className="collection-row" > { content } </div> </Row> </Fragment> ) } export default CollectionItem<file_sep>/src/Components/Image_Details/ImageDetail.js import axios from 'axios'; import React, { Fragment, useEffect, useState } from 'react' import { Card , CardBody , CardImg , CardTitle , CardText , Button, Row , Col} from 'reactstrap' const ImageDetail = () =>{ const [imageDetails,setImageDetails]=useState(null) useEffect(()=>{ const item=JSON.parse(localStorage.getItem("item")) setImageDetails(item) },[]) var downloadImage = async (uri)=>{ const {data}=await axios.get(uri,{ responseType:"blob" }) console.log(data) const url=window.URL.createObjectURL(new Blob([data])) const link=document.createElement('a') link.href=url link.setAttribute('download','image.jpeg'); document.body.appendChild(link) link.click() }; return( <Fragment> { (imageDetails)? <> <Row className="w-100 m-0 p-0"> <Col lg={4} className="offset-lg-8 text-center "> <div id="btn-download" className="float-right"> <Button outline color="light" size="md" className="text-dark" onClick={()=> downloadImage(imageDetails.small_image)}> Download </Button> </div> </Col> </Row> <Card className="card-imgDetail" > <CardImg top width="80%" className="img-thumbnail img-fluid" src={imageDetails.small_image} alt="Card-image cap" /> <CardBody> <CardTitle className="h5 text-muted">{`ID: ${imageDetails.id}`}</CardTitle> <CardText>{imageDetails.picture_description}</CardText> <CardText> <small className="text-muted">Image By: {imageDetails.artist} (unsplash.com)</small> </CardText> </CardBody> </Card> </>:<Card> <CardBody>Sorry!, No post-selected :(</CardBody> </Card> } </Fragment> ) } export default ImageDetail<file_sep>/README.md # MugglePexels App to get the best free stock,beautiful photos , ✓ High-quality ✓ 100% free ✓ No attribution needed, for your project and store it into collection for later use This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). ## To Run do git clone of the repository https://github.com/mayur-keswani/MugglePexels.git In the project directory, you can run: #### `npm start` Runs the app in the development mode.\ Open [http://localhost:3000](http://localhost:3000) to view it in the browser. ## Assets 🔨 - firebase auth - masonry-layout - react-icons - axios - uuid - reactstrap ## Features - Get photos of any topic just by typing keyword _eg: nature,car,sunset,home_ - Get Random-New Photos with each page refresh [NOTE: This images are retrived from unsplash-API. ] - Get brief-description about each image just by clicking on it. - Download Image-Offline - Pick the image and store them into your collection for later use ## Topics-Covered - Getting random photos from unsplash-api based on keyword user type in seach-box. - Create Separate Space for your stored photos and group them into specific collection. ## How you can contribute to this repository 🤝: 1) Star this repository 2) Fork this repository 3) Open any JS file inside src folder then add the explanation of any line of code as a comment line. 4) Commit changes with a meaningful commit message like "Added Expanation to line number 1 in index.html". 5) Create a pull request. Sit back and relax while your pull request is reviewed and merged. >>MugglePexels is clone of Pexel , Unsplash for learning purpose only. ### Need help? ```Javascript if (needHelp === true) { var emailId = "<EMAIL>"; // email is the best way to reach out to me. sendEmail(emailId); } ``` Glad to see you here! Show some love by starring this repo. ```Javascript if (isAwesome) { // thanks in advance starThisRepository(); } ``` <file_sep>/src/Components/Collections/Collection.js import React, { Fragment } from 'react' import {Button, Row , Col} from 'reactstrap' import CollectionItem from './CollectionItem.js' import './Collection.css' const Collection = ({collectionList,createCollection,addInCollection}) =>{ let collectionRowItems; if(Object.keys(collectionList).length>0){ let collectionIDArray = Object.keys(collectionList) console.log(collectionIDArray) collectionRowItems=collectionIDArray.map((row,index)=> <CollectionItem key={collectionIDArray[index]} collection_items={ collectionList[collectionIDArray[index]] } addInCollection={()=>addInCollection(collectionIDArray[index])}/> ) }else{ collectionRowItems=(<p>You have no collection saved!</p>) } return( <Fragment> <div id="collection-section" className="p-0 m-0"> <Row> <Col sm={4} > <div className="collection-header p-1"> <h4>Save to Collection</h4> </div> </Col> <Col sm={4} className="text-right offset-sm-4" > <Button color="success" onClick={createCollection}>Create New-Collection</Button> </Col> </Row> <Row> <Col> <div className="collection-body p-5"> {collectionRowItems} </div> </Col> </Row> </div> </Fragment> ) } export default Collection<file_sep>/src/App.js import React, { Fragment, useEffect, useState } from 'react' // css/styling components import 'bootstrap/dist/css/bootstrap.min.css' import 'bootstrap/dist/js/bootstrap.min' import { ToastContainer } from 'react-toastify'; import 'react-toastify/dist/ReactToastify.css'; // react functional component import Products from './Components/Products/Products'; import Header from './Components/UI/Header/Header'; import Collection from './Components/Collections/Collection'; import Signup from './Pages/Signup/Signup'; import Login from './Pages/Login/Login'; import ModalWrapper from './Components/UI/ModalWrapper/ModalWrapper'; import ImageDetail from './Components/Image_Details/ImageDetail'; // some dependencies import { v4 } from 'uuid'; import UserContext from './Context/UserContext' import { BrowserRouter, Route, Switch } from 'react-router-dom'; import firebase from 'firebase/app' import 'firebase/auth' import firebaseConfig from './Config/firebaseConfig' firebase.initializeApp(firebaseConfig) function App() { // state hook const [user,setUser]=useState(null) const [collections,setCollections]=useState({}); const [ criterion , setCriterion]=useState("products"); const [modalIsOpen, setModalOpen] = useState(false); const [showImageDetail,setShowFullImage]=useState(false) useEffect(()=>{ const localUser=localStorage.getItem("user") if(typeof localUser !== typeof undefined){ setUser(JSON.parse(localUser)) } },[]) const toggleModal = () => setModalOpen(!modalIsOpen); const createCollection=()=>{ // fetching items from localStorage const item=JSON.parse(localStorage.getItem("item")) localStorage.removeItem("item") //generating unique id from new-collection object let newId=v4().toString(); // Storing item into object let object; if(item){ object={ name:"",items:[{...item}] } }else{ object={ name:"",items:[]} } // Creating copy of prev. collections let collections_Copy=collections collections_Copy[newId]=object setCollections({...collections_Copy}) } const addInCollection=(id)=>{ // getting item from local storage const item=JSON.parse(localStorage.getItem("item")) localStorage.removeItem("item") // creating copy of collections const collections_Copy={...collections} const selected_collection={...collections_Copy[id]} // push new item into collections->items array selected_collection.items.push(item); collections_Copy[id]=selected_collection setCollections({...collections_Copy}) } const addInLocalStorage=(item,action)=>{ // adding item into localStorage for temporary localStorage.setItem("item",JSON.stringify(item)) setModalOpen(true) if(action==="show-image-detail"){ // console("Show full image ") setShowFullImage(true) } // setCollectionVisible(true); } return ( <Fragment> <BrowserRouter> <ToastContainer/> <UserContext.Provider value={{user:user,setUser:setUser}}> <Switch> <Route path="/signup" exact render={()=> <> <Signup/> </> }> </Route> <Route path="/signin" exact render={()=> <> <Login/> </> }> </Route> <Route path="/" render={()=> <> <Header setCriterion={(value)=>setCriterion(value)} toggleModal={toggleModal}/> {/* <Navigation setCriterion={(value)=>setCriterion(value)}/> */} <Products addInLocalStorage={(item,action)=>addInLocalStorage(item,action)} searchedProduct={criterion}/> <ModalWrapper show={modalIsOpen} toggleModal={toggleModal} closeImgDetails={()=>setShowFullImage(false)}> { showImageDetail? <ImageDetail/>: <Collection collectionList={collections} createCollection={createCollection} addInCollection={(id)=>addInCollection(id)}/> } </ModalWrapper> </> }> </Route> </Switch> </UserContext.Provider> </BrowserRouter> </Fragment> ); } export default App;
e3fe6eb17d3df7bea900cdf5c022813fa64e61ed
[ "JavaScript", "Markdown" ]
6
JavaScript
mayur-keswani/MugglePexels-using-useState-hook
dae67739a34bcac9617792269ee3c6777a5c8a95
c683184b96416b2a16e3cabbb8eabfbffc9e4868
refs/heads/master
<repo_name>jDebu/Connection<file_sep>/test_volley.php <?php error_reporting(0); header('Content-Type: text/html; charset=utf-8'); date_default_timezone_set('America/Lima'); $response= array(); $response["data"]= array(); $data = array(); $data["variable1"]= $_GET["variablexUrlGet"]; $data["variable2"]= $_GET["variablexUrlGet2"]; $data["variableDeseableQueAparezca"] = $_POST["variablexPost"]; array_push($response["data"], $data); echo json_encode($response);
b91fa7abdf088111adb582cd5ae33769ad5a8153
[ "PHP" ]
1
PHP
jDebu/Connection
8c3dea1837e64b425499616307a0aa9937f9789e
00fe73b2fee51754f4344fe20aca2133d0a677d1
refs/heads/master
<repo_name>u-yeong/re2021oss<file_sep>/another.c another file from tutorial 1+1=2 //리뷰실습 <file_sep>/test.c 787878754445 from test
6752f471ef9cbd28074bbd6739265c3f12c0f6e4
[ "C" ]
2
C
u-yeong/re2021oss
c3fdfcd70dab7aac8163b65e1e54fde1ed105a12
9803af5dbb850ee78accfbc5cf8408297e696b95
refs/heads/master
<repo_name>IkuzakIkuzok/PandA-for-iOS<file_sep>/credential.py USERNAME = 'XXXXXXXX' PASSWORD = '<PASSWORD>' <file_sep>/main.py # (c) 2020 __guanine import appex import json import os import re import requests import ui from datetime import datetime, timedelta from credential import * from html import unescape from objc_util import ObjCInstance LOGIN_URL = 'https://cas.ecs.kyoto-u.ac.jp/cas/login?service=https%3A%2F%2Fpanda.ecs.kyoto-u.ac.jp%2Fsakai-login-tool%2Fcontainer' JSON_URL = 'https://panda.ecs.kyoto-u.ac.jp/direct/assignment/my.json' class TableSource(): def __init__(self, data): self.data = data self.danger = timedelta(days=1) self.warning = timedelta(days=5) self.success = timedelta(days=14) def tableview_number_of_rows(self, tv, s): return len(self.data) def tableview_cell_for_row(self, tv, s, r): cell = ui.TableViewCell('subtitle') ObjCInstance(cell.text_label).setAdjustsFontSizeToFitWidth_(True) remain = self.data[r][2] if remain < self.danger: cell.bg_color = '#f1cdcd' cell.border_color = '#e85555' elif remain < self.warning: cell.bg_color = '#d7aa57' cell.border_color = '#e2d4bf' elif remain < self.success: cell.bg_color = '#62b665' cell.border_color = '#cce6cf' else: cell.bg_color = '#777777' cell.border_color = '#dad6d6' cell.text_label.text = self.data[r][0] cell.detail_text_label.text = self.data[r][1] cell.border_width = 1 return cell class ComfortablePandA(ui.View): def __init__(self, *args, **kwargs): super().__init__(self, *args, **kwargs) self.bounds = (0, 0, 350, 500) self.btn = ui.Button(title='Load', action=self.load, background_color=(0, 0, 0, .1), tint_color='black', font=('HelveticaNeue-Light', 24), corner_radius=3 ) self.add_subview(self.btn) self.btn.frame = (100, 10, 150, 30) self.list = ui.TableView(frame=(20, 50, 310, 440), hidden=True) self.add_subview(self.list) self.status = ui.Label(frame=(20, 50, 310, 30), hidden=True) self.add_subview(self.status) def set_status(self, message): self.status.text = message def get_lectures(self, tabs): lectures = {} for tab in tabs: try: id = re.search(r'href="(.+?)"', tab).group(1)[-17:] name = unescape(re.search(r'title="(.+?)"', tab).group(1).split(']')[1]) lectures[id] = name except: pass return lectures def get_assignments(self, items): assignments = [] for item in items: if item['status'] != '公開': continue lecture = item['context'] title = item['title'] due = datetime.fromtimestamp(item['dueTime']['time'] // 1000) dueStr = item['dueTime']['display'] assignments.append({ 'lecture_id': lecture, 'title': title, 'due': due, 'dueStr': dueStr }) return assignments def make_list_data(self, assignments, lectures): now = datetime.now() assignments = sorted(assignments, key=lambda x: x['due']) list_data = [] for assignment in assignments: remain = assignment['due'] - now lecture = lectures[assignment['lecture_id']] title = assignment['title'] due = assignment['dueStr'] list_data.append((f'{lecture}\t{title}', f'{due} ({remain})', remain)) return list_data @ui.in_background def load(self, sender): try: data = self.load_assignments() self.list.data_source = TableSource(data) self.list.reload() self.status.hidden = True self.list.hidden = False except RuntimeError as e: self.status.text_color = 'red' self.set_status(str(e)) def download_content(self, url, method, data=None): try: if method == 'post': res = self.session.post(url, data=data) else: res = self.session.get(url) res.raise_for_status() except HTTPError: raise RuntimeError('Could not access to PandA.') except Timeout: raise RuntimeError('Connection timed out.') except ConnectionError: raise RuntimeError('A network error occurred.') else: return res def load_assignments(self): self.list.hidden = True self.status.text_color = 'black' self.set_status('Logging in ...') self.status.hidden = False self.session = requests.session() res = self.download_content(LOGIN_URL, 'get') lt = re.search(r'<input type="hidden" name="lt" value="(.+?)".*>', res.text).group(1) login_info = { 'username': USERNAME, 'password': <PASSWORD>, 'warn': 'true', 'lt': lt, 'execution': 'e1s1', '_eventId': 'submit' } res = self.download_content(LOGIN_URL, 'post', data=login_info) self.set_status('Collecting lectures\' information ...') text = res.text.replace('\n', '') # Regular expression does not work as expected on multi-line string tabs = re.findall(r'<li class=".*?nav-menu.*?>.+?</li>', text)[1:] try: otherSiteList = re.search(r'<ul id="otherSiteList".*>.+?</ul>', text).group() except AttributeError: raise RuntimeError('Failed to log in to PandA.') tabs += re.findall(r'<li.*?>.+?</li>', otherSiteList) lectures = self.get_lectures(tabs) self.set_status('Downloading data ...') json_str = self.download_content(JSON_URL, 'get').text assignment_collection = json.loads(json_str)['assignment_collection'] self.set_status('Parsing data ...') assignments = self.get_assignments(assignment_collection) return self.make_list_data(assignments, lectures) def main(): widget_name = __file__ + str(os.stat(__file__).st_mtime) widget_view = appex.get_widget_view() if widget_view is None or widget_view.name != widget_name: widget_view = ComfortablePandA() widget_view.name = widget_name appex.set_widget_view(widget_view) if __name__ == '__main__': main() <file_sep>/README.md # PandA-for-iOS PandAから課題一覧を取得してウィジェットに表示します。 ## 使用方法 1. [Pythonista 3](https://apps.apple.com/jp/app/pythonista-3/id1085978097)を購入する。 2. ウィジェット画面で[編集]を選択し,Pythonistaを追加して完了。 3. [このあたり](https://qiita.com/maboy/items/cef5dee13d5b2e9ac843)を参考にStaShを入れる。 4. StaSh上で`pip install requests`する。 5. StaSh上で`git clone https://github.com/IkuzakIkuzok/PandA-for-iOS.git`する。 6. PandA-for-iOS/credential.pyのユーザー名(`USERNAME`)とパスワード(`PASSWORD`)を自分の情報に書き換える。 7. PandA-for-iOS/main.pyを実行し,[Use in "Today"]を選択しOK。 8. ウィジェット画面で[Load]を押すと課題の取得を行います。 ## 注意事項 - おそらくメモリ制限の都合で,表示できない場合があります。諦めてください。 - 提出済みの課題も併せて表示されます。諦めてください。 ## その他 何かありましたら[Twitter](https://twitter.com/__guanine)にてお知らせください。 (ここでIssueを立てられても見ていないかもしれないので)
3c3bd1e4e96ab08c35bb8495be278398ea429db2
[ "Markdown", "Python" ]
3
Python
IkuzakIkuzok/PandA-for-iOS
5fb3c3a288947777d909ac23a4d53a7933c2242e
f139c1163bf9787c77bb408ec348a9350eb929f3
refs/heads/master
<file_sep>/* * File: main.cpp * Author: John * * Created on January 26, 2015, 2:08 PM */ #include <cstdlib> #include <iostream> using namespace std; /* * */ int main(int argc, char** argv) { int n; cout << "Please enter a positive integer: "; cin >> n; int xAdd = 0; int tAdd = 0; int yAdd = 0; for (int t = 0; t < n; t += 3) { tAdd += t; } for (int x = 0; x < n; x += 5) { xAdd += x; } for (int y = 0; y < n; y += 15) { yAdd += y; } int z = xAdd + tAdd - yAdd; cout << "The sum of all multiples of 3 and 5 below " << n << ": " << z; }<file_sep>/* * File: main.cpp * Author: John * * Created on January 27, 2015, 2:11 PM */ #include <cstdlib> #include <iostream> using namespace std; /* * */ int main(int argc, char** argv) { int n; cout << "Please enter a positive integer: "; cin >> n; int a = n % 15; int b = n % 5; int c = n % 3; int x = (n - a) / 15; int y = (n - b) / 5; int z = (n - c) / 3; int xAdd = (((x * x) + x) / 2) * 15; int yAdd = (((y * y) + y) / 2) * 5; int zAdd = (((z * z) + z) / 2) * 3; int d = (yAdd + zAdd) - xAdd; if(a == 0 || b == 0 || c == 0) { d = d - n; } cout << "The sum of all multiples of 3 and 5 below " << n << ": " << d; }
96da4ba75b772574231f7c1e0801f29ff9e4382f
[ "C++" ]
2
C++
jstaleyunca/CSCI-372
624ff8864db59bfc5ee903fb36d0a377e4e7d207
8a37caba5dd0c6bf42f59fe216d2a01085b8905c
refs/heads/master
<repo_name>RakRic/SpringBootVizsga<file_sep>/src/main/java/com/example/demo/Service/JobSeekerService.java package com.example.demo.Service; import com.example.demo.Model.JobSeeker; import com.example.demo.Model.PriorityProfile; import com.example.demo.Model.ProgrammingLanguage; import com.example.demo.Repository.JobSeekerRepository; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; import java.util.Optional; @Service public class JobSeekerService { private final JobSeekerRepository jobSeekerRepository; public JobSeekerService(JobSeekerRepository jobSeekerRepository) { this.jobSeekerRepository = jobSeekerRepository; } // Create public JobSeeker create(JobSeeker jobseeker){ return jobSeekerRepository.save(jobseeker); } // Read public List<JobSeeker> getAll(){ return (List<JobSeeker>) jobSeekerRepository.findAll(); } //Update public JobSeeker update(JobSeeker jobseeker){ return jobSeekerRepository.save(jobseeker); } //Delete public void delete(Long id){ jobSeekerRepository.deleteById(id); } //GetJobseekerById public JobSeeker getJobseekerById(Long id){ Optional<JobSeeker> optionalJobSeeker = jobSeekerRepository.findById(id); if(optionalJobSeeker.isPresent()){ return optionalJobSeeker.get(); }else { throw new JobSeekerIdNotFound("There is no Jobseeker by this id"); } } //getPrioritiesByJobseekerId public List<PriorityProfile> getPrioritiesByJobseekerId(Long jobseekerId) { ArrayList<Object[]> returnedValues = new ArrayList<Object[]>(jobSeekerRepository.getPrioritiesByJobseekerId(jobseekerId)); ArrayList<PriorityProfile> priorities = new ArrayList<PriorityProfile>(); for(Object[] o : returnedValues) { priorities.add(new PriorityProfile( Long.parseLong(o[0].toString()), Long.parseLong(o[1].toString()), Long.parseLong(o[2].toString()), Integer.parseInt(o[3].toString()))); } return priorities; } //getProgLanguagesByJobseekerId public List<String> getProgLanguagesByJobseekerId(Long jobseekerId) { return jobSeekerRepository.getProgLanguagesByJobseekerId(jobseekerId); } } <file_sep>/src/main/java/com/example/demo/Service/BenefitService.java package com.example.demo.Service; import com.example.demo.Model.Benefit; import com.example.demo.Repository.BenefitRepository; import org.springframework.stereotype.Service; import java.util.List; @Service public class BenefitService { private final BenefitRepository benefitRepository; public BenefitService(BenefitRepository benefitRepository){ this.benefitRepository = benefitRepository; } // Create public Benefit create(Benefit benefit){ return benefitRepository.save(benefit); } // Read public List<Benefit> getAll(){ return (List<Benefit>) benefitRepository.findAll(); } // Update public Benefit update(Benefit benefit){ return benefitRepository.save(benefit); } // Delete public void delete(Long id){ benefitRepository.deleteById(id); } } <file_sep>/src/main/java/com/example/demo/Model/BenefitProfile.java package com.example.demo.Model; import lombok.Getter; import lombok.Setter; import javax.persistence.*; @Entity @Setter @Getter public class BenefitProfile { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "benefitProfile_generator") @SequenceGenerator(name = "benefitProfile_generator", sequenceName = "benefitProfile_seq") private long id; private Boolean value; private long companyId; private long benefitId; } <file_sep>/src/main/java/com/example/demo/Controller/PriorityProfileController.java package com.example.demo.Controller; import com.example.demo.Model.PriorityProfile; import com.example.demo.Service.PriorityProfileService; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController public class PriorityProfileController { private final PriorityProfileService priorityProfileService; public PriorityProfileController(PriorityProfileService priorityProfileService){ this.priorityProfileService = priorityProfileService; } // Create @PostMapping(path = "/createPriorityProfile") public PriorityProfile create(@RequestBody PriorityProfile priorityProfile){ return priorityProfileService.create(priorityProfile); } // Read @GetMapping(path = "/priorityProfiles") public List<PriorityProfile> getAll(){ return priorityProfileService.getAll(); } // Update @PostMapping(path = "/updatePriorityProfile") public PriorityProfile update(@RequestBody PriorityProfile priorityProfile){ return priorityProfileService.update(priorityProfile); } // Delete @RequestMapping(method = RequestMethod.DELETE, value = "/priorityProfile/{id}") public void delete(@PathVariable("id")Long id){ priorityProfileService.delete(id); } } <file_sep>/src/main/java/com/example/demo/Service/CompanyService.java package com.example.demo.Service; import com.example.demo.Model.Company; import com.example.demo.Repository.CompanyRepository; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; @Service public class CompanyService { private final CompanyRepository companyRepository; public CompanyService(CompanyRepository companyRepository) { this.companyRepository = companyRepository; } // Create public Company create(Company company){ return companyRepository.save(company); } // Read public List<Company> getAll(){ return (List<Company>) companyRepository.findAll(); } // Update public Company update(Company company){ return companyRepository.save(company); } // Delete public void delete(Long id){ companyRepository.deleteById(id); } //getBenefitsByCompanyId public List<String> getBenefitsByCompanyId(Long id) { return companyRepository.getBenefitsByCompanyId(id); } //GetCompanyById public Company getCompanyById(Long id){ Optional<Company> optionalCompany = companyRepository.findById(id); if(optionalCompany.isPresent()){ return optionalCompany.get(); } else { throw new IdNotFoundException("There is no Company by this id"); } } } <file_sep>/README.md # Final project made in Spring boot. A simple project that uses an h2 database to store entites with Spring boot.<file_sep>/src/main/java/com/example/demo/Service/PriorityProfileService.java package com.example.demo.Service; import com.example.demo.Model.PriorityProfile; import com.example.demo.Repository.PriorityProfileRepository; import org.springframework.stereotype.Service; import java.util.List; @Service public class PriorityProfileService { private final PriorityProfileRepository priorityProfileRepository; public PriorityProfileService(PriorityProfileRepository priorityProfileRepository){ this.priorityProfileRepository = priorityProfileRepository; } // Create public PriorityProfile create(PriorityProfile priorityProfile){ return priorityProfileRepository.save(priorityProfile); } // Read public List<PriorityProfile> getAll(){ return (List<PriorityProfile>) priorityProfileRepository.findAll(); } // Update public PriorityProfile update(PriorityProfile priorityProfile){ return priorityProfileRepository.save(priorityProfile); } // Delete public void delete(Long id){ priorityProfileRepository.deleteById(id); } } <file_sep>/src/main/java/com/example/demo/Service/JobSeekerIdNotFound.java package com.example.demo.Service; public class JobSeekerIdNotFound extends RuntimeException{ public JobSeekerIdNotFound(String errorMessage){ super(errorMessage); } }<file_sep>/src/main/java/com/example/demo/Repository/BenefitRepository.java package com.example.demo.Repository; import com.example.demo.Model.Benefit; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; @Repository public interface BenefitRepository extends CrudRepository<Benefit, Long> { } <file_sep>/src/main/java/com/example/demo/Controller/BenefitProfileController.java package com.example.demo.Controller; import com.example.demo.Model.BenefitProfile; import com.example.demo.Service.BenefitProfileService; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController public class BenefitProfileController { private final BenefitProfileService benefitProfileService; public BenefitProfileController(BenefitProfileService benefitProfileService){ this.benefitProfileService = benefitProfileService; } // Create @PostMapping(path = "/createBenefitProfile") public BenefitProfile create(@RequestBody BenefitProfile benefitProfile){ return benefitProfileService.create(benefitProfile); } // Read @GetMapping(path = "/benefitProfiles") public List<BenefitProfile> getAll(){ return benefitProfileService.getAll(); } // Update @PostMapping(path = "/updateBenefitProfile") public BenefitProfile update(BenefitProfile benefitProfile){ return benefitProfileService.update(benefitProfile); } // Delete @RequestMapping(method = RequestMethod.DELETE, value = "/benefitProfile/{id}") public void delete(@PathVariable("id")Long id){ benefitProfileService.delete(id); } } <file_sep>/src/main/java/com/example/demo/Repository/ProgrammingLanguageRepository.java package com.example.demo.Repository; import com.example.demo.Model.ProgrammingLanguage; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; @Repository public interface ProgrammingLanguageRepository extends CrudRepository<ProgrammingLanguage, Long> { } <file_sep>/src/main/java/com/example/demo/Controller/BenefitController.java package com.example.demo.Controller; import com.example.demo.Model.Benefit; import com.example.demo.Service.BenefitService; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController public class BenefitController { private final BenefitService benefitService; public BenefitController(BenefitService benefitService){ this.benefitService = benefitService; } // Create @PostMapping(path = "/createBenefit") public Benefit create(@RequestBody Benefit benefit){ return benefitService.create(benefit); } // Read @GetMapping(path = "/benefits") public List<Benefit> getAll(){ return benefitService.getAll(); } // Update @PostMapping(path = "/updateBenefit") public Benefit update(@RequestBody Benefit benefit){ return benefitService.update(benefit); } // Delete @RequestMapping(method = RequestMethod.DELETE, value = "/benefit/{id}") public void delete(@PathVariable("id")Long id){ benefitService.delete(id); } }
2705e5887e76253633ac3f2bc17922780cc4ac93
[ "Markdown", "Java" ]
12
Java
RakRic/SpringBootVizsga
b2915a3b057098b73839a27314671f76cc6bc46a
90e1aad386614f1d29841e309accc65fc34ff1e5
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Security.Cryptography; namespace SampleBlockchain { public class BlockUtility { /// <summary> /// Gets the sha256 hash. /// </summary> /// <param name="rawData">The raw data.</param> /// <returns></returns> public static string GetSha256Hash(string rawData) { // Create a SHA256 using (SHA256 sha256Hash = SHA256.Create()) { // ComputeHash() - returns byte array byte[] bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(rawData)); // Convert byte array to a string var sb = new StringBuilder(); foreach (var bt in bytes) { sb.Append(String.Format("{0:X2}", bt)); } return sb.ToString(); } } } } <file_sep># Blockchains Blockchain samples <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SampleBlockchain { /// <summary> /// a block in a blockchain /// </summary> public class Block { /// <summary> /// The index /// </summary> public string index; /// <summary> /// The timestamp /// </summary> public string timestamp; /// <summary> /// The proof of work /// </summary> public string proof; /// <summary> /// The previous hash /// </summary> public string previousHash; /// <summary> /// Returns a <see cref="System.String" /> that represents this instance. /// </summary> /// <returns> /// A <see cref="System.String" /> that represents this instance. /// </returns> public string ToString() { return String.Format("index:{0}, timestamp:{1}, proof:{2}, previousHash:{3}", index, timestamp, proof, previousHash); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using Nancy.Hosting.Self; namespace SampleBlockchain { public class Program { /// <summary> /// The instance of the blockchain /// </summary> public static Blockchain blockchain = new Blockchain(); /// <summary> /// The URI /// </summary> public static String Uri; static void Main(string[] args) { if (args.Length > 0) Uri = String.Format("http://localhost:{0}", args[0]); else Uri = "http://localhost:8877"; // initialize an instance of NancyHost (found in the Nancy.Hosting.Self package) var host = new NancyHost(new Uri(Uri)); host.Start(); Console.WriteLine("Server started, now listening on " + Uri); Console.WriteLine("Press any key to stop the server..."); Console.ReadKey(); host.Stop(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SampleBlockchain { /// <summary> /// My Blockchain class, implementing one possible ways to create a blockchain from scratch /// </summary> public class Blockchain { /// <summary> /// The chain /// </summary> public List<Block> chain; /// <summary> /// Initializes a new instance of the <see cref="Blockchain"/> class. /// </summary> public Blockchain() { // allocate memory to the list chain = new List<Block>(); // create a genesis block CreateBlock("1", "0"); } /// <summary> /// Creates the block. /// </summary> /// <param name="newProof">The new Proof.</param> /// <param name="previousHash">The previous hash.</param> /// <returns></returns> public Block CreateBlock(string newProof, string previoushash) { // create a new block and add it to the blockchain var block = new Block(); block.index = String.Format("{0}", chain.Count + 1); block.timestamp = GetTimestamp(); block.proof = newProof; block.previousHash = previoushash; // add the new block to the blockchain chain.Add(block); // return the new block for display purpose return block; } /// <summary> /// Proofs the of work. /// </summary> /// <param name="previousProof">The previous Proof.</param> /// <returns></returns> public string ProofOfWork(string previousProof) { int newProof = 1; var prevProof = Convert.ToInt32(previousProof); var newProofFound = false; while (!newProofFound) { var proof = CalculateProof(prevProof, newProof); if (IsProofHashValid(proof)) { newProofFound = true; } else { newProof++; } } return newProof.ToString(); } /// <summary> /// Calculates the hash. /// </summary> /// <param name="block">The block.</param> /// <returns></returns> public string CalculateHash(Block block) { return BlockUtility.GetSha256Hash(block.ToString()); } /// <summary> /// Determines whether [is chain valid]. /// </summary> /// <returns></returns> public bool IsChainValid() { Block previousBlock = null; foreach (var block in this.chain) { if (previousBlock == null && block.previousHash.Equals("0")) { // this block is the genesis block previousBlock = block; // continue with the loop continue; } // check the current block's previous hash with the calculated hash of the previous block if (!block.previousHash.Equals(CalculateHash(previousBlock))) { // return false since the previous hash of current block did not match wht calculated hash of previous block return false; } // get the Proof of previous block var previousProof = Convert.ToInt32(previousBlock.proof); // get the Proof of the current block var currentProof = Convert.ToInt32(block.proof); // validate Proof of previous block with the Proof of the current block var calculatedProof = CalculateProof(previousProof, currentProof); var isProofValid = IsProofHashValid(calculatedProof); if (!isProofValid) { return false; } // set previous block as current block previousBlock = block; } return true; } /// <summary> /// Mines the block. /// </summary> /// <returns></returns> public Block MineBlock() { // previous block is the last block in the blockchain var previousBlock = chain[chain.Count - 1]; var previousProof = previousBlock.proof; var newProof = ProofOfWork(previousProof); var previousHash = CalculateHash(previousBlock); var newBlock = CreateBlock(newProof, previousHash); return newBlock; } /// <summary> /// Gets the timestamp. /// </summary> /// <returns></returns> private string GetTimestamp() { // get the unix time, number of seconds from Jan 1, 1970 return string.Format("{0}", (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds); } /// <summary> /// Determines whether [is hash valid] /// </summary> /// <param name="hash">The hash.</param> /// <returns></returns> private bool IsProofHashValid(string hash) { // this is the difficulty level (in bitcoin this is determined by the algorithm.) // The more the number of 0s the higher the difficulty and the lower the value of the hash. return hash.StartsWith("0000"); } /// <summary> /// Calculates the Proof. /// </summary> /// <param name="previousProof">The previous Proof.</param> /// <param name="currentProof">The current Proof.</param> /// <returns></returns> private string CalculateProof(int previousProof, int currentProof) { // this is a random calculation to find out the new Proof which would satisfy the validation criteria // in this example I am using (a^2 - b^2 - 2ab) return BlockUtility.GetSha256Hash(String.Format("{0}", (Math.Pow(currentProof, 2) - Math.Pow(previousProof, 2) - 2 * currentProof * previousProof))); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using Nancy; namespace SampleBlockchain { /// <summary> /// Main module for nancy /// </summary> public class MainModule : NancyModule { /// <summary> /// Initializes a new instance of the <see cref="MainModule"/> class. /// </summary> public MainModule() { // get the blockchain instance var blockchain = Program.blockchain; // request handler for the root request Get["/"] = x => { return "Hello friends!!"; }; // request handler for mine block in the blockchain Get["/mineblock"] = _ => { // mine a new block for this blockchain var block = blockchain.MineBlock(); // create a new dictionary for response in JSON format var dict = new Dictionary<string, object>() { {"message", "Congratulations, you have successfully mined a block!"}, {"block", block} }; return Response.AsJson<Dictionary<String, object>>(dict); }; // request handler to get the entire chain Get["/getchain"] = x => { // create a new dictionary for response in JSON format var dict = new Dictionary<string, object>() { {"chain", blockchain.chain}, {"length", blockchain.chain.Count} }; return Response.AsJson<Dictionary<String, object>>(dict); }; // request handler for validating if the blockchain is valid Get["/ischainvalid"] = x => { // check if the blockchain is valid var isValid = blockchain.IsChainValid(); // create a new dictionary for response in JSON format var dict = new Dictionary<string, object>() { {"is_blockchain_valid", isValid}, {"length", blockchain.chain.Count} }; return Response.AsJson<Dictionary<String, object>>(dict); }; } } }
387fa0a5aeee7f0d94220f4c7ff13b2853a4b16c
[ "Markdown", "C#" ]
6
C#
saurabhvirdi/Blockchains
0ac79e8d5cf47b39dc3ed6e7d147c8a5b7190760
2e248d0ecd9536280344f48eb4bebe1e51cba0a4
refs/heads/main
<repo_name>alexmalynovskyi/ecommerce_shop_react<file_sep>/src/components/product/Product.jsx import { mockedProducts } from "./mocked-products"; import ProductCard from "./ProductCard"; import GridContainer from "../grid/GridContainer"; import Griditem from "../grid/Griditem"; export default function Product() { console.log(mockedProducts); const renderProductCads = () => { if (mockedProducts && mockedProducts.length > 0) { return mockedProducts.map(prod => <Griditem xs={4}> <ProductCard key={prod.id} id={prod.id} title={prod.title} description={prod.description} img={prod.img} price={prod.price} code={prod.code} /> </Griditem> ) } } return ( <GridContainer spacing={5}> {renderProductCads()} </GridContainer> ) }<file_sep>/src/pages/Homepage.jsx import GridContainer from "../components/grid/GridContainer"; import Griditem from "../components/grid/Griditem"; import { makeStyles } from '@material-ui/core/styles'; import Product from "../components/product/Product"; const useStyles = makeStyles((theme) => ({ container: { marginTop: '100px' } })); export default function Homepage(props) { const classes = useStyles(); return <GridContainer className={classes.container}> <Griditem xs={3}>filter section</Griditem> <Griditem xs={9}> <Product></Product> </Griditem> </GridContainer> }<file_sep>/src/App.jsx import logo from './logo.svg'; import './App.css'; import { BrowserRouter as Router, Route } from 'react-router-dom'; import Homepage from './pages/Homepage'; import Header from './components/layout/Header'; function App() { return ( <Router> <Header /> <Route exact path='/' component={Homepage} /> </Router> ); } export default App; <file_sep>/src/components/grid/Griditem.jsx import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import Grid from '@material-ui/core/Grid'; import classnames from 'classnames'; const useStyles = makeStyles((theme) => ({ })); // eslint-disable-next-line import/no-anonymous-default-export export default ({ xs = 12, children, className, ...props }) => { const classes = useStyles(); const gridContainerClassNames = classnames(classes.root, className) return ( <Grid className={gridContainerClassNames} item xs={xs} {...props} > {children} </Grid> ); } <file_sep>/src/components/grid/GridContainer.jsx import Grid from '@material-ui/core/Grid'; import { makeStyles } from '@material-ui/core/styles'; import classnames from 'classnames'; const useStyles = makeStyles((theme) => ({ root: { flexGrow: 1, } })); export default function GridContainer ({ spacing= 2, children, className, ...props }) { const classes = useStyles(); const gridContainerClassNames = classnames(classes.root, className) return <Grid container className={gridContainerClassNames} spacing={spacing} {...props}> {children} </Grid> }
aa9d80075b41018e175dd1eabda72577558b5063
[ "JavaScript" ]
5
JavaScript
alexmalynovskyi/ecommerce_shop_react
f0ed6cf0b76173355cfbbcdc6127f71d46e0c993
d42f3c5c20b4c416385790214cb6b5288e4d6740
refs/heads/master
<file_sep>'use strict'; var Alexa = require("alexa-sdk"); var appId = 'amzn1.ask.skill.ce19d66c-b1d2-40b9-987a-ea1c13916b14'; //'amzn1.echo-sdk-ams.app.your-skill-id'; var https = require('https'); //var apiKey = /* YOUR_KEY */; var alexa; exports.handler = function(event, context, callback) { alexa = Alexa.handler(event, context); alexa.appId = appId; //alexa.dynamoDBTableName = 'highLowGuessUsers'; alexa.registerHandlers(newSessionHandlers, drivingModeHandlers, transitModeHandlers, findModeHandlers, startModeHandlers); //, guessAttemptHandlers); alexa.execute(); }; var states = { DRIVINGMODE: '_DRIVINGMODE', TRANSITMODE: '_TRANSITMODE', FINDMODE: '_FINDMODE', STARTMODE: '_STARTMODE' }; var newSessionHandlers = { 'NewSession': function() { /* if(Object.keys(this.attributes).length === 0) { this.attributes['endedSessionCount'] = 0; this.attributes['gamesPlayed'] = 0; } */ this.handler.state = states.STARTMODE; this.emit(':ask', 'Welcome to the Directions App. Would you like to know directions?', 'Say yes to start or no to quit.'); }, "AMAZON.StopIntent": function() { this.emit(':tell', "Goodbye!"); }, "AMAZON.CancelIntent": function() { this.emit(':tell', "Goodbye!"); }, 'SessionEndedRequest': function () { console.log('session ended!'); //this.attributes['endedSessionCount'] += 1; this.emit(":tell", "Goodbye!"); } }; var startModeHandlers = Alexa.CreateStateHandler(states.STARTMODE, { 'NewSession': function () { this.emit('NewSession'); // Uses the handler in newSessionHandlers }, 'AMAZON.HelpIntent': function() { var message = 'I can help you find directions. Tell me where you are now and where you want to go.'; this.emit(':ask', message, message); }, 'AMAZON.YesIntent': function() { this.handler.state = states.FINDMODE; this.emit(':ask', 'Great! ' + 'Are you driving?', 'Please say yes or no.'); }, 'AMAZON.NoIntent': function() { console.log("NOINTENT"); this.emit(':tell', 'Ok, see you next time!'); }, "AMAZON.StopIntent": function() { console.log("STOPINTENT"); this.emit(':tell', "Goodbye!"); }, "AMAZON.CancelIntent": function() { console.log("CANCELINTENT"); this.emit(':tell', "Goodbye!"); }, 'SessionEndedRequest': function () { console.log("SESSIONENDEDREQUEST"); //this.attributes['endedSessionCount'] += 1; this.emit(':tell', "Goodbye!"); }, 'Unhandled': function() { console.log("UNHANDLED"); var message = 'Say yes to know directions, or no to exit.'; this.emit(':ask', message, message); } }); var findModeHandlers = Alexa.CreateStateHandler(states.FINDMODE, { 'NewSession': function () { this.emit('NewSession'); // Uses the handler in newSessionHandlers }, 'AMAZON.HelpIntent': function() { var message = 'I can help you find directions. Tell me where you are now and where you want to go.'; this.emit(':ask', message, message); }, 'AMAZON.YesIntent': function() { this.handler.state = states.DRIVINGMODE; this.emit(':ask', 'Great! ' + 'Tell me where you are now and where you want to go. For example, you can say, Get me directions from Gaithursburg, Maryland to Rockefeller, New York', 'Please say the source and destination addresses.'); }, 'AMAZON.NoIntent': function() { this.handler.state = states.TRANSITMODE; this.emit(':ask', 'Alright! ' + 'Tell me where you are now and where you want to go. For example, you can say, Get me directions from 10 Commercial Avenue, New Brunswick to Times Square, New York', 'Please say the source and destination addresses.'); }, "AMAZON.StopIntent": function() { console.log("STOPINTENT"); this.emit(':tell', "Goodbye!"); }, "AMAZON.CancelIntent": function() { console.log("CANCELINTENT"); this.emit(':tell', "Goodbye!"); }, 'SessionEndedRequest': function () { console.log("SESSIONENDEDREQUEST"); //this.attributes['endedSessionCount'] += 1; this.emit(':tell', "Goodbye!"); }, 'Unhandled': function() { console.log("UNHANDLED"); var message = 'Say yes to know directions, or no to exit.'; this.emit(':ask', message, message); } }); var drivingModeHandlers = Alexa.CreateStateHandler(states.DRIVINGMODE, { 'NewSession': function () { this.handler.state = ''; this.emitWithState('NewSession'); // Equivalent to the Start Mode NewSession handler }, 'GetDirectionsIntent': function() { var source = this.event.request.intent.slots.src.value; var destination = this.event.request.intent.slots.dest.value; for (var i = 0; i < source.length; i++) if (source[i] == ' ') source[i] = '+'; for (var i = 0; i < destination.length; i++) if (destination[i] == ' ') destination[i] = '+'; var url = 'https://maps.googleapis.com/maps/api/directions/json?origin='+source+'&destination='+destination+'&key='+apiKey; httpsGet(url, function(response) { var output = ''; var result = JSON.parse(response); var cardContent = "\nDirections provided by Google\n\n"; var json = result.routes[0].legs[0].steps; for (var i = 0; i < json.length; i++) { var index = i + 1; var inst = (json[i].html_instructions).replace(/<b>/g, "").replace(/<\/b>/g, "").replace(/<\/div>/g, "").replace(/<div style="font-size:0.9em">/g, ". "); cardContent += index + ". " + inst + " for " + json[i].distance.text + ".\n"; } output += "The total travel time is " + result.routes[0].legs[0].duration.text + ". See your Alexa app for directions."; var cardTitle = "Directions"; console.log(cardContent); alexa.emit(':tellWithCard', output, cardTitle, cardContent); }); }, 'AMAZON.HelpIntent': function() { this.emit(':ask', 'I can help you find directions. Tell me where you are now and where you want to go.', 'Tell me where you are now and where you want to go.'); }, "AMAZON.StopIntent": function() { console.log("STOPINTENT"); this.emit(':tell', "Goodbye!"); }, "AMAZON.CancelIntent": function() { console.log("CANCELINTENT"); }, 'SessionEndedRequest': function () { console.log("SESSIONENDEDREQUEST"); this.attributes['endedSessionCount'] += 1; this.emit(':tell', "Goodbye!"); }, 'Unhandled': function() { console.log("UNHANDLED"); this.emit(':ask', 'Sorry, I didn\'t get that.', 'Please repeat properly.'); } }); var transitModeHandlers = Alexa.CreateStateHandler(states.TRANSITMODE, { 'NewSession': function () { this.handler.state = ''; this.emitWithState('NewSession'); // Equivalent to the Start Mode NewSession handler }, 'GetDirectionsIntent': function() { var source = this.event.request.intent.slots.src.value; var destination = this.event.request.intent.slots.dest.value; for (var i = 0; i < source.length; i++) if (source[i] == ' ') source[i] = '+'; for (var i = 0; i < destination.length; i++) if (destination[i] == ' ') destination[i] = '+'; var url = 'https://maps.googleapis.com/maps/api/directions/json?mode=transit&transit_mode=train&origin='+source+'&destination='+destination+'&key='+apiKey; httpsGet(url, function(response) { var output = ''; var result = JSON.parse(response); var cardContent = "\nDirections provided by Google\n\n"; var jsonOne = result.routes[0].legs[0].steps; for (var i = 0; i < jsonOne.length; i++) { var index = i + 1; cardContent += index + ". " + jsonOne[i].html_instructions + "\n"; if (jsonOne[i].travel_mode === "WALKING") // if ((jsonOne[i].html_instructions).search("Walk") != -1) { var jsonTwo = jsonOne[i].steps; for (var j = 0; j < jsonTwo.length; j++) { if (jsonTwo[j].html_instructions === undefined) continue; var inst = (jsonTwo[j].html_instructions).replace(/<b>/g, "").replace(/<\/b>/g, "").replace(/<\/div>/g, "").replace(/<div style="font-size:0.9em">/g, ". "); cardContent += "-> " + inst + " (" + jsonTwo[j].distance.text + ")\n"; } } else if (jsonOne[i].travel_mode === "TRANSIT") { var jsonTwo = jsonOne[i].transit_details; cardContent += "-> Line name: " + jsonTwo.line.name + "\n"; cardContent += "-> Number of stops: " + jsonTwo.num_stops + "\n"; cardContent += "-> Departure Stop: " + jsonTwo.departure_stop.name + "\n"; cardContent += "-> Departure Time: " + jsonTwo.departure_time.text + "\n"; cardContent += "-> Arrival Stop: " + jsonTwo.arrival_stop.name + "\n"; cardContent += "-> Arrival Time: " + jsonTwo.arrival_time.text + "\n"; } } output += "The total travel time is " + result.routes[0].legs[0].duration.text + ". See your Alexa app for directions."; var cardTitle = "Directions"; console.log(cardContent); alexa.emit(':tellWithCard', output, cardTitle, cardContent); }); }, 'AMAZON.HelpIntent': function() { this.emit(':ask', 'I can help you find directions. Tell me where you are now and where you want to go.', 'Tell me where you are now and where you want to go.'); }, "AMAZON.StopIntent": function() { console.log("STOPINTENT"); this.emit(':tell', "Goodbye!"); }, "AMAZON.CancelIntent": function() { console.log("CANCELINTENT"); }, 'SessionEndedRequest': function () { console.log("SESSIONENDEDREQUEST"); this.attributes['endedSessionCount'] += 1; this.emit(':tell', "Goodbye!"); }, 'Unhandled': function() { console.log("UNHANDLED"); this.emit(':ask', 'Sorry, I didn\'t get that.', 'Please repeat properly.'); } }); function httpsGet(url, callback) { https.get(url, function(res) { var body = ''; res.on('data', function(data) { body += data; }); res.on('end', function() { callback(body); }); }); } <file_sep># AlexaSkill-Google-Directions A Directions App with the new Alexa SDK.
b04b2de1a09199cd6a686571e5cb4c4167474f44
[ "JavaScript", "Markdown" ]
2
JavaScript
govind94/AlexaSkill-Google-Directions
9b65cb61f134ddda4a831e0b1ced066d591f2f4f
952a19d78acdfbe3a160c92eacc197a5f14dabdd
refs/heads/master
<repo_name>tim90721/Project<file_sep>/main/scripts/evaluateResult.py #/usr/bin/python3 import os import csv import sys import matplotlib.pyplot as plt import numpy as np from plot_result import collectDataUE, getSubframePeriod import math ####################### # plot each prach-configurationIndex uniform and beta distribution result ####################### # plot source folder organization # # candidateResult - ./prach-16-simulation-uniform # ./prach-16-simulation-beta # ./prach-19-simulation-uniform # ./prach-19-simulation-beta # ./prach-22-simulation-uniform # ./prach-22-simulation-beta # ./prach-25-simulation-uniform # ./prach-25-simulation-beta # ./prach-27-simulation-uniform # ./prach-27-simulation-beta # ./others configuration with uniform and beta # ... figureCount = 0 line_width = 3.0 marker_size = 10.0 label_font_size = 20 title_font_size = 24 legend_font_size = 16 plot_optimized = False def getPreambleLength(preambleSCS): if preambleSCS == 1.25 or preambleSCS == 5: return 839 else: return 139 def collectCellMsg1FDM(filename): timing = [] msg1FDM = [] if plot_optimized: msg1FDMOp = [] with open(filename, newline='') as csvfile: rows = csv.DictReader(csvfile) #next(rows) for row in rows: preambleSCS = row['Preamble SCS'] timing.append(int(row['Current Frame']) * 10 + int(row['Current Subframe'])) msg1FDM.append(int(row['msg1-FDM'])) if plot_optimized: msg1FDMOp.append(int(row['msg1-FDM Optimized'])) if plot_optimized: return preambleSCS, timing, msg1FDM, msg1FDMOp return preambleSCS, timing, msg1FDM def plotAverageResult(average, filename=""): global figureCount fig = plt.figure(figureCount) figureCount = figureCount + 1 #fig.subplots_adjust(top = 0.9) fig.set_size_inches(9.375, 7.3) ax = plt.subplot(1, 1, 1) plt.plot(average.keys(), average.values(), 'b-o', linewidth=line_width, markersize=marker_size) plt.xlabel("RA Subframe Period (ms)", fontsize=label_font_size) plt.ylabel("Average Latency (ms)", fontsize=label_font_size) for label in (ax.get_xticklabels() + ax.get_yticklabels()): label.set_fontsize(16) #plt.suptitle("Average UE Latency vs RA Subframe Period", fontsize=title_font_size, fontweight="bold") plt.axis([0, max(average.keys()) + 2, 0, max(average.values()) + 10]) plt.grid(True) if filename: plt.savefig(filename) plt.close #plt.show() def plotLantencyCDF(uedata, saveFolderName=""): global figureCount fig = plt.figure(figureCount) figureCount = figureCount + 1 #fig.subplots_adjust(top=0.83) fig.set_size_inches(9.375, 7.3) ax = plt.subplot(1, 1, 1) plt.xlabel("Latency (ms)", fontsize=label_font_size) plt.ylabel("CDF", fontsize=label_font_size) #plt.suptitle("UE Latency CDF", fontsize=title_font_size, fontweight="bold") for data in uedata: latency = data['latency'] prachIndex = data['prachIndex'] simulationTime = data['simulationTime'] arrivalMode = data['arrivalMode'] arrival = data['arrival'] subTitle = "Simulation Time: {0}s\n".format(str(int(simulationTime))) \ + "Arrival Mode: {0}, ".format(arrivalMode) if arrivalMode == "uniform": subTitle = subTitle + "Arrival Rate: {0}".format(arrival) else: subTitle = subTitle + "Totle UE: {0}".format(arrival) filenameFig = "CDF_simu-{0}_{1}_arrival-{2}".format(simulationTime, arrivalMode, arrival) #ax.set_title(subTitle, fontsize=title_font_size) latency.insert(0, 0) X = np.linspace(min(latency), max(latency), max(latency) - min(latency)) hist, bin_edges = np.histogram(latency, bins=max(latency) - min(latency), density=True) hist = np.cumsum(hist) plt.plot(X, hist, label="RA Subframe Period="+str(getSubframePeriod(prachIndex))+"ms", linewidth=line_width) ax.legend(loc="lower right", fontsize=legend_font_size) for label in (ax.get_xticklabels() + ax.get_yticklabels()): label.set_fontsize(16) plt.axis([0, max(latency), 0, 1.1]) plt.grid(True) if saveFolderName: plt.savefig(saveFolderName + filenameFig) plt.close() del X del hist del bin_edges def plotEachLantencyCDF(uedata, saveFolderName=""): global figureCount for data in uedata: fig = plt.figure(figureCount) figureCount = figureCount + 1 fig.set_size_inches(9.375, 7.3) #fig.subplots_adjust(top=0.83) fig.set_size_inches(9.375, 7.3) ax = plt.subplot(1, 1, 1) plt.xlabel("Latency (ms)", fontsize=label_font_size) plt.ylabel("CDF", fontsize=label_font_size) #plt.suptitle("UE Latency CDF", fontsize=title_font_size, fontweight="bold") latency = data['latency'] prachIndex = data['prachIndex'] simulationTime = data['simulationTime'] arrivalMode = data['arrivalMode'] arrival = data['arrival'] subTitle = "RA Subframe Period: {0}ms, ".format(getSubframePeriod(prachIndex)) \ + "Simulation Time: {0}s\n".format(str(int(simulationTime))) \ + "Arrival Mode: {0}, ".format(arrivalMode) if arrivalMode == "uniform": subTitle = subTitle + "Arrival Rate: {0}".format(arrival) else: subTitle = subTitle + "Totle UE: {0}".format(arrival) filenameFig = "CDF_prach-{0}_simu-{1}_{2}_arrival-{3}".format(prachIndex, simulationTime, arrivalMode, arrival) #ax.set_title(subTitle, fontsize=title_font_size) latency.insert(0, 0) X = np.linspace(min(latency), max(latency), max(latency) - min(latency)) hist, bin_edges = np.histogram(latency, bins=max(latency) - min(latency), density=True) hist = np.cumsum(hist) for label in (ax.get_xticklabels() + ax.get_yticklabels()): label.set_fontsize(16) plt.plot(X, hist, 'b-', linewidth=line_width) plt.axis([0, max(latency), 0, 1.1]) plt.grid(True) if saveFolderName: plt.savefig(saveFolderName + filenameFig) plt.close() del X del hist del bin_edges def plotCellMsg1FDM(celldatas, folderName=""): global figureCount fig = plt.figure(figureCount) fig.set_size_inches(9.375, 7.3) #fig.subplots_adjust(top=0.83) simulationTime = celldatas[0]['simulationTime'] arrivalMode = celldatas[0]['arrivalMode'] arrival = celldatas[0]['arrival'] maxTiming = max([max(t['timing']) for t in celldatas]) ax = plt.subplot(1, 1, 1) figureCount = figureCount + 1 attr = ['b-o', 'm-D', 'c-s', 'r-^', 'g-*'] i = 0 for data in celldatas: preambleBW = [fdm*data['preambleLength']*float(data['preambleSCS'])/1000 for fdm in data['msg1FDM']] if i == 0: ax.plot(data['timing'], preambleBW, attr[i], label='RA Subframe Period='+str(getSubframePeriod(int(data['prachIndex'])))+"ms", linewidth=line_width, markersize=marker_size) elif i == 1: ax.plot(data['timing'], preambleBW, attr[i], label='RA Subframe Period='+str(getSubframePeriod(int(data['prachIndex'])))+"ms", linewidth=line_width, markersize=marker_size + 10, fillstyle="none", markeredgewidth=3.0) elif i == 2: ax.plot(data['timing'], preambleBW, attr[i], label='RA Subframe Period='+str(getSubframePeriod(int(data['prachIndex'])))+"ms", linewidth=line_width, markersize=marker_size + 5) elif i == 4: ax.plot(data['timing'], preambleBW, attr[i], label='RA Subframe Period='+str(getSubframePeriod(int(data['prachIndex'])))+"ms", linewidth=line_width, markersize=marker_size + 5) else: ax.plot(data['timing'], preambleBW, attr[i], label='RA Subframe Period='+str(getSubframePeriod(int(data['prachIndex'])))+"ms", linewidth=line_width, markersize=marker_size) i = i + 1 newYTick = [fdm*celldatas[0]['preambleLength']*float(celldatas[0]['preambleSCS'])/1000 for fdm in [1, 2, 4, 8]] xtick = math.ceil(maxTiming / 160) xtick = [(x * 160) for x in range(xtick + 1)] #plt.xticks(xtick) plt.yticks(newYTick) ax.legend(loc='upper left', fontsize=legend_font_size) ax.set_xlim(0, maxTiming) ax.set_ylim(0, math.ceil(max(newYTick) / 10) * 2 * 10) for label in (ax.get_xticklabels() + ax.get_yticklabels()): label.set_fontsize(16) ax.grid(True) plt.xlabel("Subframe Index", fontsize=label_font_size) plt.ylabel("Preamble Occupied Bandwidth (MHz)",fontsize=label_font_size) #plt.suptitle("RA Used Bandwidth", fontsize=title_font_size, fontweight="bold") title = "Simulation Time: {0}s\nArrival Mode:{1}".format(simulationTime, arrivalMode) if arrivalMode == "uniform": title = title + ", Arrival Rate:{0}".format(arrival) else: title = title + ", Total UE:{0}".format(arrival) filename = "msg1FDM_simu-{0}_{1}_arrival-{2}.png".format(simulationTime, arrivalMode, arrival) #plt.title(title, fontsize=title_font_size) plt.savefig(folderName + filename) plt.close() def plotCellMsg1FDMwithOptimized(celldatas, folderName=""): #fig.subplots_adjust(top=0.83) simulationTime = celldatas[0]['simulationTime'] arrivalMode = celldatas[0]['arrivalMode'] arrival = celldatas[0]['arrival'] maxTiming = max([max(t['timing']) for t in celldatas]) attr = ['b-s', 'r-o', 'm-D', 'c-^', 'g-*'] i = 0 for data in celldatas: global figureCount fig = plt.figure(figureCount) fig.set_size_inches(9.375, 7.3) ax = plt.subplot(1, 1, 1) figureCount = figureCount + 1 preambleBW = [fdm*data['preambleLength']*float(data['preambleSCS'])/1000 for fdm in data['msg1FDM']] preambleBWOp = [fdm*data['preambleLength']*float(data['preambleSCS']) / 1000 for fdm in data['msg1FDMOp']] ax.plot(data['timing'], preambleBW, attr[0], label=r'$F_{RAO}$', linewidth=line_width, markersize=marker_size + 7) ax.plot(data['timing'], preambleBWOp, attr[1], label=r'$F_{RAO} optimized$', linewidth=line_width, markersize=marker_size + 7) newYTick = [fdm*celldatas[0]['preambleLength']*float(celldatas[0]['preambleSCS'])/1000 for fdm in [1, 2, 4, 8]] plt.yticks(newYTick) ax.legend(loc='upper left', fontsize=legend_font_size) ax.set_xlim(0, maxTiming) ax.set_ylim(0, math.ceil(max(newYTick) / 10) * 10) for label in (ax.get_xticklabels() + ax.get_yticklabels()): label.set_fontsize(16) ax.grid(True) plt.xlabel("Subframe Index", fontsize=label_font_size) plt.ylabel("Preamble Occupied Bandwidth (MHz)",fontsize=label_font_size) #plt.suptitle("RA Used Bandwidth", fontsize=title_font_size, fontweight="bold") #title = "Simulation Time: {0}s\nArrival Mode:{1}".format(simulationTime, arrivalMode) #if arrivalMode == "uniform": # title = title + ", Arrival Rate:{0}".format(arrival) #else: # title = title + ", Total UE:{0}".format(arrival) filename = "msg1FDM_prach-{0}_simu-{1}_{2}_arrival-{3}.png".format(data['prachIndex'], simulationTime, arrivalMode, arrival) #plt.title(title, fontsize=title_font_size) plt.savefig(folderName + filename) plt.close() if __name__ == '__main__': command = sys.argv if 'plot_op' in command: plot_optimized = True print('plot optimized') ueFile = 'UE.csv' cellFile = 'Cell.csv' resultSourceFolder = "./candidateResult/" savefigureNameUniform = "result_uniform.png" savefigurenameBeta = "result_beta.png" folderNameUniform = "uniform/" folderNameBeta = "beta/" if not os.path.exists(resultSourceFolder + folderNameUniform): os.makedirs(resultSourceFolder + folderNameUniform) if not os.path.exists(resultSourceFolder + folderNameBeta): os.makedirs(resultSourceFolder + folderNameBeta) folderName = [name for name in os.listdir(resultSourceFolder)] folderName = [name for name in folderName if "png" not in name] folderName.remove('beta') folderName.remove('uniform') #if savefigureName in folderName: # folderName.remove(savefigureName) ############# get parameters ############ prachIndex = [name.split("prach-")[1] for name in folderName] prachIndex = [name.split("_")[0] for name in prachIndex] simulationTime = [name.split("simu-")[1] for name in folderName] simulationTime = [name.split("_")[0] for name in simulationTime] arrivalMode = [name.split("_")[4] for name in folderName] arrival = [name.split("_")[5] for name in folderName] arrival = [name.split("-")[1] for name in arrival] #for i in range(len(folderName)): # print(prachIndex[i]) # print(simulationTime[i]) # print(arrivalMode[i]) # print(arrival[i]) ############ get parameters ############ avgs_uniform = {} avgs_beta = {} ue_uniform = [] ue_beta = [] cell_uniform = [] cell_beta = [] while(len(prachIndex) > 0): maxIndex = prachIndex.index(max(prachIndex)) #### get ue data #### filename = resultSourceFolder + folderName[maxIndex] + "/" + ueFile latency = [x['latency'] for x in collectDataUE(filename).values()] ue_data = {'latency':latency, 'prachIndex':prachIndex[maxIndex], 'simulationTime':simulationTime[maxIndex], 'arrivalMode':arrivalMode[maxIndex], 'arrival':arrival[maxIndex]} #### get ue data #### #### get cell data #### filename = resultSourceFolder + folderName[maxIndex] + "/" + cellFile if plot_optimized: preambleSCS, timing, msg1FDM, msg1FDMOp = collectCellMsg1FDM(filename) else: preambleSCS, timing, msg1FDM = collectCellMsg1FDM(filename) cell_data = {'prachIndex':prachIndex[maxIndex], 'preambleSCS':preambleSCS, 'preambleLength':getPreambleLength(float(preambleSCS)), 'timing':timing, 'msg1FDM':msg1FDM, 'simulationTime':simulationTime[maxIndex], 'arrivalMode': arrivalMode[maxIndex], 'arrival':arrival[maxIndex]} if plot_optimized: cell_data['msg1FDMOp'] = msg1FDMOp #### get cell data #### if arrivalMode[maxIndex] == "uniform": avgs_uniform[getSubframePeriod(int(prachIndex[maxIndex]))] = np.mean(latency) cell_uniform.append(cell_data) ue_uniform.append(ue_data) else: avgs_beta[getSubframePeriod(int(prachIndex[maxIndex]))] = np.mean(latency) cell_beta.append(cell_data) ue_beta.append(ue_data) # plotLantencyCDF(latency, prachIndex[maxIndex], simulationTime[maxIndex], arrivalMode[maxIndex], arrival[maxIndex], resultSourceFolder) del prachIndex[maxIndex] del simulationTime[maxIndex] del arrivalMode[maxIndex] del arrival[maxIndex] del folderName[maxIndex] print(avgs_uniform) plotLantencyCDF(ue_uniform, resultSourceFolder + folderNameUniform) plotEachLantencyCDF(ue_uniform, resultSourceFolder + folderNameUniform) plotAverageResult(avgs_uniform, resultSourceFolder + folderNameUniform + savefigureNameUniform) plotCellMsg1FDM(cell_uniform, resultSourceFolder + folderNameUniform) if plot_optimized: plotCellMsg1FDMwithOptimized(cell_uniform, resultSourceFolder + folderNameUniform) #plotLantencyCDF(ue_beta, resultSourceFolder + folderNameBeta) #plotEachLantencyCDF(ue_beta, resultSourceFolder + folderNameBeta) #plotAverageResult(avgs_beta, resultSourceFolder + folderNameBeta+ savefigurenameBeta) #plotCellMsg1FDM(cell_beta, resultSourceFolder + folderNameBeta) #if plot_optimized: # plotCellMsg1FDMwithOptimized(cell_beta, resultSourceFolder + folderNameBeta) #plt.show() del avgs_uniform del avgs_beta del cell_uniform del cell_beta del ue_uniform del ue_beta <file_sep>/project_test/src_test/RAOtestPrachConfig22.cpp #ifndef PRACH_INDEX_22_TEST #define PRACH_INDEX_22_TEST #include "general_definition.h" extern Cell* cell; extern UE* ue; void testPrachIndex22_24(){ int prachConfigIndex = 22; int msg1FDM = 8; double ssbPerRAO = 4; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; for(int k = 0;k < 3;++k){ while(j % (associationFrame * 10) < 1 + k * 3){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(0); subframeExpect->push_back(1); subframeExpect->push_back(2); subframeExpect->push_back(3); subframeExpect->push_back(4); subframeExpect->push_back(5); subframeExpect->push_back(6); subframeExpect->push_back(7); expected.push_back(*subframeExpect); j++; } while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); //destoryExpects(expected); destory(); } void testPrachIndex22_23(){ int prachConfigIndex = 22; int msg1FDM = 4; double ssbPerRAO = 4; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; for(int k = 0;k < 3;++k){ while(j % (associationFrame * 10) < 1 + k * 3){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(0); subframeExpect->push_back(1); subframeExpect->push_back(2); subframeExpect->push_back(3); expected.push_back(*subframeExpect); j++; } while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); //destoryExpects(expected); destory(); } void testPrachIndex22_22(){ int prachConfigIndex = 22; int msg1FDM = 2; double ssbPerRAO = 4; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; for(int k = 0;k < 3;++k){ while(j % (associationFrame * 10) < 1 + k * 3){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(0); subframeExpect->push_back(1); expected.push_back(*subframeExpect); j++; } while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); //destoryExpects(expected); destory(); } void testPrachIndex22_21(){ int prachConfigIndex = 22; int msg1FDM = 1; double ssbPerRAO = 4; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; for(int k = 0;k < 3;++k){ while(j % (associationFrame * 10) < 1 + k * 3){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(0); expected.push_back(*subframeExpect); j++; } while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); //destoryExpects(expected); destory(); } void testPrachIndex22_20(){ int prachConfigIndex = 22; int msg1FDM = 8; double ssbPerRAO = 2; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; for(int k = 0;k < 3;++k){ while(j % (associationFrame * 10) < 1 + k * 3){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(0); subframeExpect->push_back(2); subframeExpect->push_back(4); subframeExpect->push_back(6); expected.push_back(*subframeExpect); j++; } while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); //destoryExpects(expected); destory(); } void testPrachIndex22_19(){ int prachConfigIndex = 22; int msg1FDM = 4; double ssbPerRAO = 2; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; for(int k = 0;k < 3;++k){ while(j % (associationFrame * 10) < 1 + k * 3){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(0); subframeExpect->push_back(2); expected.push_back(*subframeExpect); j++; } while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); //destoryExpects(expected); destory(); } void testPrachIndex22_18(){ int prachConfigIndex = 22; int msg1FDM = 2; double ssbPerRAO = 2; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; for(int k = 0;k < 3;++k){ while(j % (associationFrame * 10) < 1 + k * 3){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(0); expected.push_back(*subframeExpect); j++; } while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); //destoryExpects(expected); destory(); } void testPrachIndex22_17(){ int prachConfigIndex = 22; int msg1FDM = 1; double ssbPerRAO = 2; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 1){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(0); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); //destoryExpects(expected); destory(); } void testPrachIndex22_16(){ int prachConfigIndex = 22; int msg1FDM = 8; double ssbPerRAO = 0.125; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 2; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int rao = 8; int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 4){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(rao++); subframeExpect->push_back(rao++); subframeExpect->push_back(rao++); subframeExpect->push_back(rao++); subframeExpect->push_back(rao++); subframeExpect->push_back(rao++); subframeExpect->push_back(rao++); subframeExpect->push_back(rao++); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); //destoryExpects(expected); destory(); } void testPrachIndex22_15(){ int prachConfigIndex = 22; int msg1FDM = 4; double ssbPerRAO = 0.125; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 4; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int rao = 8; int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 7){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(rao++); subframeExpect->push_back(rao++); subframeExpect->push_back(rao++); subframeExpect->push_back(rao++); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) < 11){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(rao++); subframeExpect->push_back(rao++); subframeExpect->push_back(rao++); subframeExpect->push_back(rao++); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); //destoryExpects(expected); destory(); } void testPrachIndex22_14(){ int prachConfigIndex = 22; int msg1FDM = 2; double ssbPerRAO = 0.125; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 8; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int rao = 8; int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 14){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(rao++); subframeExpect->push_back(rao++); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) < 17){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(rao++); subframeExpect->push_back(rao++); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) < 21){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(rao++); subframeExpect->push_back(rao++); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) < 24){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(rao++); subframeExpect->push_back(rao++); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); //destoryExpects(expected); destory(); } void testPrachIndex22_13(){ int prachConfigIndex = 22; int msg1FDM = 1; double ssbPerRAO = 0.125; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 16; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 27){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(8); expected.push_back(*subframeExpect); j++; int rao = 9; for(int k = 0;k < 2;k++){ while(j % (associationFrame * 10) < 31 + k * 10){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(rao++); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) < 34 + k * 10){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(rao++); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) < 37 + k * 10){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(rao++); expected.push_back(*subframeExpect); j++; } while(j % (associationFrame * 10) < 51){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(15); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); //destoryExpects(expected); destory(); } void testPrachIndex22_12(){ int prachConfigIndex = 22; int msg1FDM = 8; double ssbPerRAO = 0.25; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 1){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(4); subframeExpect->push_back(5); subframeExpect->push_back(6); subframeExpect->push_back(7); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); //destoryExpects(expected); destory(); } void testPrachIndex22_11(){ int prachConfigIndex = 22; int msg1FDM = 4; double ssbPerRAO = 0.25; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 2; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 4){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(4); subframeExpect->push_back(5); subframeExpect->push_back(6); subframeExpect->push_back(7); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); //destoryExpects(expected); destory(); } void testPrachIndex22_10(){ int prachConfigIndex = 22; int msg1FDM = 2; double ssbPerRAO = 0.25; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 4; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 7){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(4); subframeExpect->push_back(5); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) < 11){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(6); subframeExpect->push_back(7); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); //destoryExpects(expected); destory(); } void testPrachIndex22_9(){ int prachConfigIndex = 22; int msg1FDM = 1; double ssbPerRAO = 0.25; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 8; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 14){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(4); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) < 17){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(5); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) < 21){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(6); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) < 24){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(7); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); //destoryExpects(expected); destory(); } void testPrachIndex22_8(){ int prachConfigIndex = 22; int msg1FDM = 8; double ssbPerRAO = 0.5; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; for(int k = 0;k < 3;k++){ while(j % (associationFrame * 10) < 1 + k * 3){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(2); subframeExpect->push_back(3); expected.push_back(*subframeExpect); j++; } while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); //destoryExpects(expected); destory(); } void testPrachIndex22_7(){ int prachConfigIndex = 22; int msg1FDM = 4; double ssbPerRAO = 0.5; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 1){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(2); subframeExpect->push_back(3); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); //destoryExpects(expected); destory(); } void testPrachIndex22_6(){ int prachConfigIndex = 22; int msg1FDM = 2; double ssbPerRAO = 0.5; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 2; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 4){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(2); subframeExpect->push_back(3); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); //destoryExpects(expected); destory(); } void testPrachIndex22_5(){ int prachConfigIndex = 22; int msg1FDM = 1; double ssbPerRAO = 0.5; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 4; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 7){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(2); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) < 11){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(3); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); //destoryExpects(expected); destory(); } void testPrachIndex22_4(){ int prachConfigIndex = 22; int msg1FDM = 8; double ssbPerRAO = 1; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; for(int k = 0;k < 3;k++){ while(j % (associationFrame * 10) < 1 + k * 3){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(1); subframeExpect->push_back(5); expected.push_back(*subframeExpect); j++; } while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); //destoryExpects(expected); destory(); } void testPrachIndex22_3(){ int prachConfigIndex = 22; int msg1FDM = 4; double ssbPerRAO = 1; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; for(int k = 0;k < 3;k++){ while(j % (associationFrame * 10) < 1 + k * 3){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(1); expected.push_back(*subframeExpect); j++; } while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); //destoryExpects(expected); destory(); } void testPrachIndex22_2(){ int prachConfigIndex = 22; int msg1FDM = 2; double ssbPerRAO = 1; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 1){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(1); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); //destoryExpects(expected); destory(); } void testPrachIndex22_1(){ int prachConfigIndex = 22; int msg1FDM = 1; double ssbPerRAO = 1; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 2; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 4){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(1); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); //destoryExpects(expected); destory(); } void testPrachIndex22(){ testPrachIndex22_1(); testPrachIndex22_2(); testPrachIndex22_3(); testPrachIndex22_4(); testPrachIndex22_5(); testPrachIndex22_6(); testPrachIndex22_7(); testPrachIndex22_8(); testPrachIndex22_9(); testPrachIndex22_10(); testPrachIndex22_11(); testPrachIndex22_12(); testPrachIndex22_13(); testPrachIndex22_14(); testPrachIndex22_15(); testPrachIndex22_16(); testPrachIndex22_17(); testPrachIndex22_18(); testPrachIndex22_19(); testPrachIndex22_20(); testPrachIndex22_21(); testPrachIndex22_22(); testPrachIndex22_23(); testPrachIndex22_24(); } #endif <file_sep>/project_test/src_test/RAOtestPrachConfig16.cpp #ifndef PRACH_INDEX_16_TEST #define PRACH_INDEX_16_TEST #include "general_definition.h" extern Cell* cell; extern UE* ue; void testPrachIndex16_8(){ int prachConfigIndex = 16; int msg1FDM = 8; double ssbPerRAO = 1.0 / 16.0; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 8; vector<vector<int>> expected; int round = getRound(simulationTime, associationFrame); vector<int> *subframeExpect; for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 21){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; for(int k = 16;k < 24;k++){ subframeExpect->push_back(k); } expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) < 31){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; for(int k = 24;k < 32;k++){ subframeExpect->push_back(k); } expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex16_7(){ int prachConfigIndex = 16; int msg1FDM = 8; double ssbPerRAO = 1.0 / 4.0; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 2; vector<vector<int>> expected; int round = getRound(simulationTime, associationFrame); vector<int> *subframeExpect; for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 1){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(4); subframeExpect->push_back(5); subframeExpect->push_back(6); subframeExpect->push_back(7); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex16_6(){ int prachConfigIndex = 16; int msg1FDM = 1; double ssbPerRAO = 1.0 / 4.0; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 16; vector<vector<int>> expected; int round = getRound(simulationTime, associationFrame); vector<int> *subframeExpect; for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 41){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(4); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) < 51){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(5); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) < 61){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(6); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) < 71){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(7); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex16_5(){ int prachConfigIndex = 16; int msg1FDM = 1; double ssbPerRAO = 1.0 / 2.0; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 60; int associationFrame = 8; vector<vector<int>> expected; int round = getRound(simulationTime, associationFrame); vector<int> *subframeExpect; for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 21){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(2); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) < 31){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(3); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex16_4(){ int prachConfigIndex = 16; int msg1FDM = 8; double ssbPerRAO = 1; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 60; int associationFrame = 1; vector<vector<int>> expected; int round = getRound(simulationTime, associationFrame); vector<int> *subframeExpect; for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 1){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(1); subframeExpect->push_back(5); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex16_3(){ int prachConfigIndex = 16; int msg1FDM = 4; double ssbPerRAO = 1; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 60; int associationFrame = 1; vector<vector<int>> expected; int round = getRound(simulationTime, associationFrame); vector<int> *subframeExpect; for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 1){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(1); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex16_2(){ int prachConfigIndex = 16; int msg1FDM = 2; double ssbPerRAO = 1; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 60; int associationFrame = 2; vector<vector<int>> expected; int round = getRound(simulationTime, associationFrame); vector<int> *subframeExpect; for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 1){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(1); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex16_1(){ int prachConfigIndex = 16; int msg1FDM = 1; double ssbPerRAO = 1; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 60; int associationFrame = 4; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) <= 10){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(1); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex16(){ testPrachIndex16_1(); testPrachIndex16_2(); testPrachIndex16_3(); testPrachIndex16_4(); testPrachIndex16_5(); testPrachIndex16_6(); testPrachIndex16_7(); testPrachIndex16_8(); } #endif <file_sep>/.projectenv #!/bin/bash export project_name=project export INCLUDEPATH="/home/daitor/Qt/5.12.0/gcc_64/include" export QT=widgets export workfile_UI="src/mainGUI.cpp src/SimulationCanvas.cpp src/Model.cpp src/MonitorRAFunction.cpp src/Cell.cpp src/Beam.cpp src/MacroCell.cpp src/FemtoCell.cpp src/UE.cpp src/CommonMath.cpp" export workfile_RA="src/IPRACHConfig.h src/PRACHConfig.cpp src/PRACHConfigFR1Paired.cpp src/PreambleFormat.h src/AvailiableRAO.cpp" export workfile_test_RA="src_test/RAOtest.cpp src_test/RAOtestPrachConfig27.cpp src_test/RAOtestPrachConfig16.cpp src_test/RAOtestPrachConfig101.cpp src_test/RAOtestPrachConfig106.cpp" <file_sep>/project_test/run_test.sh #!/bin/bash echo "project name: $project_name test" qt_project_filename="${project_name}.pro" buildDir=./build_test newestFileinTestSrc=$(ls -t src/ | head -1) echo "newest file $newestFileinTestSrc" newerFile=$(find ../main/src/ -newer src/$newestFileinTestSrc | grep -E '.*cpp$|.*h$') if [ "${newerFile}" != "" ]; then echo "newer file $newerFile" cp $newerFile ./src/ else echo "no new file" fi #cp ../main/src/*.h ./src/ test -e ./src/mainGUI.h && rm ./src/mainGUI.h test -e ./src/mainGUI.cpp && rm ./src/mainGUI.cpp test -e ./src/main.cpp && rm ./src/main.cpp #rm ./src/mainGUI.h #rm ./src/mainGUI.cpp #rm ./src/main.cpp qmake -project -o ${buildDir}/${qt_project_filename} sed -i '$a QT += widgets' ${buildDir}/${qt_project_filename} sed -i '$a DEFINES += "TESTING=1"' ${buildDir}/${qt_project_filename} sed -i 's/INCLUDEPATH.*$/INCLUDEPATH += \/home\/daitor\/Qt\/5.12.0\/gcc_64\/include \.\.\/src \.\.\/\.\.\/main\/include /g' ${buildDir}/${qt_project_filename} qmake ${buildDir}/${qt_project_filename} -o ${buildDir} make -C ${buildDir} && ./${buildDir}/${project_name} <file_sep>/main/src/FemtoCell.h #ifndef FEMTOCELL #define FEMTOCELL #include "Cell.h" #include "CommonMath.h" class FemtoCell : public Cell{ public: FemtoCell(int x, int y, int cellIndex, int nBeams, celltype::CellType cellType, int prachConfigIndex, int nPreambles, int cellBW, int ssbSCS, double preambleSCS); void draw(QPainter &painter); void initializeBeams(); void setBeamStartAngle(int diffX, int diffY); void updateBeamsAngle(int diffX, int diffY); ~FemtoCell(); }; #endif <file_sep>/main/src/random_access.cpp #include "random_access.h" using namespace std; // binary search a preamble index from RARs // subframeRars: rars stored in a cell // raoLeft: the left rao index in a range of subframeRars // raoRight: the right rao index in a range of subframeRars // raoIndex: the index of searching rao // preambleIndex: the index of searching preamble // return: the index of searching rao index and preamble index // if there is no rao index and preamble index // in this subframeRars, return the index that RAR should be // inserted to int binarySearchPreamble(const vector<RAR*>& subframeRars, const int raoLeft, const int raoRight, const int raoIndex, const int preambleIndex){ if(raoLeft == -1 && raoRight == -1) return raoIndex; int left = raoLeft; int right = raoRight; while(left <= right){ int mid = left + (right - left) / 2; if(subframeRars[mid]->preambleIndex > preambleIndex) right = mid - 1; else if(subframeRars[mid]->preambleIndex < preambleIndex) left = mid + 1; else return mid; } if((unsigned)left == subframeRars.size()) return left; else{ if(left < raoRight){ return (preambleIndex > subframeRars[left]->preambleIndex)?(left + 1):left; } else return (preambleIndex > subframeRars[raoRight]->preambleIndex)?(raoRight + 1):raoRight; } } // binary search an rao from RARs // subframeRars: rars stored in a cell // raoIndex: the search index of rao // return: raoLeft, raoRight, searched index // raoLeft: the left rao index in a range of subframeRars // raoRight: the right rao index in a range of subframeRars // searched index: if rao index is contained in subframeRars // return the searched index of rao index // if rao index is not contained in subframeRars // return the index of rao index should be inserted to int binarySearchRAO(const vector<RAR*>& subframeRars, int* raoLeft, int* raoRight, const int raoIndex){ *raoLeft = -1; *raoRight = -1; if(subframeRars.size() == 0){ return 0; } else{ int left = 0; int right = subframeRars.size() - 1; while(left <= right){ int mid = left + (right - left) / 2; //printf("left: %d, right: %d\n", left, right); //printf("mid: %d\n", mid); //printf("rar mid rao: %d, rao: %d\n", // subframeRars[mid]->raoIndex, // raoIndex); if(subframeRars[mid]->raoIndex < raoIndex) left = mid + 1; else if(subframeRars[mid]->raoIndex > raoIndex) right = mid - 1; else if(subframeRars[mid]->raoIndex == raoIndex){ *raoLeft = mid; *raoRight = mid; //printf("rao left: %d, rao right: %d\n", *raoLeft, *raoRight); while((*raoLeft) > 0 && subframeRars[(*raoLeft) - 1]->raoIndex == raoIndex) (*raoLeft)--; while((unsigned)(*raoRight) + 1 < subframeRars.size() && subframeRars[(*raoRight) + 1]->raoIndex == raoIndex) (*raoRight)++; return mid; } } //printf("left: %d, right: %d\n", left, right); //printf("rao left: %d, rao right: %d\n", *raoLeft, *raoRight); if((unsigned)left == subframeRars.size()) return left; else if(raoIndex > subframeRars[left]->raoIndex) return left + 1; else return left; } } //binary search msg3 //msg3s: the Msg3s stored in a cell //tc_rnti: the tc_rnti to be searched //return: the index of searched tc_rnti msg3 //if msg3 is not found in this msg3s //return the index of msg3 should be inserted to int binarySeachMsg3(const vector<Msg3*>& msg3s, const int tc_rnti){ if(msg3s.size() == 0) return 0; int left = 0; int right = msg3s.size() - 1; while(left <= right){ int mid = left + (right - left) / 2; if(msg3s[mid]->tc_rnti < tc_rnti) left = mid + 1; else if(msg3s[mid]->tc_rnti > tc_rnti) right = mid - 1; else return mid; } if((unsigned)left == msg3s.size()) return left; else if(tc_rnti > msg3s[left]->tc_rnti) return left + 1; else return left; } // search RAR // first search rao index with returned // rao range(raoLeft, raoRight) // then search preamble index in rao range // subframeRars: the rars stored in a cell // raoIndex: the rao index to be searched // preambleIndex: the preamble index to be searched int searchRAR(const vector<RAR*>& subframeRars, const int raoIndex, const int preambleIndex){ int raoLeft, raoRight; int raoInsertIndex = binarySearchRAO(subframeRars, &raoLeft, &raoRight, raoIndex); //printf("raoLeft: %d, raoRight: %d\n", // raoLeft, // raoRight); //printf("rao insert index: %d\n", raoInsertIndex); if((unsigned)raoInsertIndex == subframeRars.size()) return raoInsertIndex; int preambleInsertIndex = binarySearchPreamble(subframeRars, raoLeft, raoRight, raoInsertIndex, preambleIndex); return preambleInsertIndex; } // search RAR // subframeRars: rars stored in a cell // rar: the RAR to be searched int searchRAR(const vector<RAR*>& subframeRars, RAR &rar){ return searchRAR(subframeRars, rar.raoIndex, rar.preambleIndex); } // search Msg3 // msg3s: Msg3 stored in a cell // tc_rnti: the tc_rnti to be searched int searchMsg3(const vector<Msg3*>& msg3s, const int tc_rnti){ return binarySeachMsg3(msg3s, tc_rnti); } // search Msg3 // msg3s: Msg3s stored in a cell // msg3: the msg3 to be searched int searchMsg3(const vector<Msg3*>& msg3s, Msg3& msg3){ return searchMsg3(msg3s, msg3.tc_rnti); } <file_sep>/main/src/SimulationCanvas.cpp #include "SimulationCanvas.h" //#include "Cell.h" //#include "MacroCell.h" // Constructor // A canvas for painting // parent: parent QWidget // model: model for handle all things SimulationCanvas::SimulationCanvas(QWidget *parent, Model *model) : QWidget(parent){ setStyleSheet("QWidget{background : white;}"); setMouseTracking(true); this->model = model; model->registerPaintObservor(this); } // Mouse moving event void SimulationCanvas::mouseMoveEvent(QMouseEvent *event){ model->setMouseXY(event->x(), event->y()); } // Mouse press event void SimulationCanvas::mousePressEvent(QMouseEvent *event){ model->setMousePressed(true); model->setMouseXY(event->x(), event->y()); } // Mouse release event void SimulationCanvas::mouseReleaseEvent(QMouseEvent *event){ model->setMousePressed(false); } // Canvas painting event void SimulationCanvas::paintEvent(QPaintEvent *event){ QStyleOption opt; opt.init(this); QPainter painter(this); style()->drawPrimitive(QStyle::PE_Widget, &opt, &painter, this); QWidget::paintEvent(event); painter.setBrush(QBrush(QColor(128, 128, 255, 128), Qt::SolidPattern)); model->draw(painter); } // IPaintSubject notify IPaintObservor update canvas void SimulationCanvas::updateCanvas(){ repaint(); } <file_sep>/main/src/MonitorRAFunction.cpp #include "MonitorRAFunction.h" // constructor // availiableRAO: need ssb per rao etc. parameter // prachConfig: need RA configuration period etc. parameter MonitorRAFunction::MonitorRAFunction(AvailiableRAO *availiableRAO, IPRACHConfig *prachConfig) : successUEs(0), failedUEs(0), raCount(0), totalDelta(0), estimateUEs(0), availiableRAO(availiableRAO), prachConfig(prachConfig){ //setbuf(stdout, NULL); tau = getTau(); SPDLOG_DEBUG("tau: {0}", tau); nSSB = availiableRAO->getNumberofSSB(); ssbPerRAO = availiableRAO->getSSBPerRAO(); delta = calculateDelta(availiableRAO->getNumberofPreambles(), availiableRAO->getSSBPerRAO()); SPDLOG_DEBUG("delta: {0}", delta); } // record ra ues condition // success: successful ra ues in current subframe // failed: failed ra ues in current subframe void MonitorRAFunction::recordUEsCondition(const int success, const int failed){ successUEs += success; failedUEs += failed; historySlot.push_back(success); raCount++; } // update rao configurations // TODO: complete comment void MonitorRAFunction::updateRAOs(){ SPDLOG_TRACE("updating rao configurations\n"); //if(raCount == 0 || successUEs == 0 /*will remove successUEs condition when predict function is complete*/) // return; history.push_back(successUEs); estimateUEs = estimateNextUEsBySlot(); totalDelta = delta * raCount; //double estimateUEs = (double)successUEs * ssbPerRAO * exp(1); double newSSBPerRAO = calculateNewSSBPerRAO(); int newMsg1FDM = getNewMsg1FDMver2(&newSSBPerRAO); SPDLOG_TRACE("old tau: {0}", tau); SPDLOG_TRACE("success ues: {0}", successUEs); SPDLOG_TRACE("failed ues: {0}", failedUEs); //SPDLOG_TRACE("estimate ues: {0}", estimateUEs); SPDLOG_TRACE("total delta: {0}", totalDelta); SPDLOG_TRACE("old ssb per rao: {0}", ssbPerRAO); SPDLOG_TRACE("old msg1FDM: {0}", availiableRAO->getMsg1FDM()); SPDLOG_WARN("new ssb per rao: {0}", newSSBPerRAO); SPDLOG_TRACE("new msg1FDM: {0}", newMsg1FDM); SPDLOG_DEBUG("raCount: {0}", raCount); availiableRAO->setSSBPerRAO(newSSBPerRAO); availiableRAO->setMsg1FDM(newMsg1FDM); availiableRAO->updateAssociationFrame(); ssbPerRAO = newSSBPerRAO; tau = getTau(); delta = calculateDelta(availiableRAO->getNumberofPreambles(), newSSBPerRAO); //totalDelta = delta * raCount; successUEs = 0; failedUEs = 0; raCount = 0; } // restore ssb per rao and msg1-fdm to 1 void MonitorRAFunction::restore2Initial(){ availiableRAO->setSSBPerRAO(initSSBPerRAO); availiableRAO->setMsg1FDM(initMsg1FDM); availiableRAO->updateAssociationFrame(); ssbPerRAO = initSSBPerRAO; tau = getTau(); SPDLOG_WARN("tau: {0}", tau); delta = calculateDelta(availiableRAO->getNumberofPreambles(), availiableRAO->getSSBPerRAO()); successUEs = 0; failedUEs = 0; estimateUEs = 0; raCount = 0; totalDelta = 0; historySlot.erase(historySlot.begin(), historySlot.end()); history.erase(history.begin(), history.end()); } // get tau by current configuration // return: tau int MonitorRAFunction::getTau(){ return getTau(prachConfig->getX(), availiableRAO->getTotalNeedRAO(), availiableRAO->getTotalRAOPerSubframe(), prachConfig->getNumberofRASubframe()); } // get tau by the given configuration // RAConfigPeriod: ra configuration period // totalNeedRAO: total need raos for mapping all ssb once // totalRAOPerSubframe: total raos in a subframe // nRASubframe: number of ra subframe in a frame // return: tau int MonitorRAFunction::getTau(const int RAConfigPeriod, const int totalNeedRAO, const int totalRAOPerSubframe, const int nRASubframe){ double ssbTotalNeedSubframe = (ceil((double)totalNeedRAO / (double)totalRAOPerSubframe)) * ((double) (10 * RAConfigPeriod) / (double) nRASubframe); SPDLOG_TRACE("total need subframe for mapping all ssb in period: {0}", ssbTotalNeedSubframe); if(ssbTotalNeedSubframe > 10){ return (pow(2, ceil(log(ssbTotalNeedSubframe / 10.0) / log(2))) * 10); } else if(ssbTotalNeedSubframe <= 5){ return ceil(ssbTotalNeedSubframe); } else{ return 10; } } // get new msg1-FDM // abandoned // ============================ // if ssb per rao get smaller, it need to check the tau is getting larger // if so, msg1-FDM need to increase and not over 8 frequency-domain rao // ----------------------- // if ssb per rao get larger, check when msg1-FDM modify // to a bit smaller can still get the same or smaller tau // if so, msg1-FDM is modify to this value // ============================ // newSSBPerRAO: the new ssb per rao value // return: new msg1-FDM parameter int MonitorRAFunction::getNewMsg1FDM(const double newSSBPerRAO){ int newTau = getTau(prachConfig->getX(), nSSB / newSSBPerRAO, availiableRAO->getTotalRAOPerSubframe(), prachConfig->getNumberofRASubframe()); int msg1FDM = availiableRAO->getMsg1FDM(); int i = log(msg1FDM) / log(2); SPDLOG_TRACE("msg1fdm index: {0}", i); int newMsg1FDM = fRAO[i]; if(newSSBPerRAO < ssbPerRAO && newTau > tau && newTau > 5 && msg1FDM < 8){ while(newMsg1FDM < 8){ int newTotalRAOPerSubframe = prachConfig->getNumberofTimeDomainRAO() * newMsg1FDM; newTau = getTau(prachConfig->getX(), nSSB / newSSBPerRAO, newTotalRAOPerSubframe, prachConfig->getNumberofRASubframe()); if(newTau <= tau) break; else{ newMsg1FDM = fRAO[++i]; } } if(newMsg1FDM == fRAO[3]){ SPDLOG_INFO("msg1FDM reach maximum capacity\n"); } // method 1 improved else{ newMsg1FDM = fRAO[++i]; } } else if(newSSBPerRAO > ssbPerRAO){ while(newMsg1FDM > 1){ newMsg1FDM = fRAO[--i]; int newTotalRAOPerSubframe = prachConfig->getNumberofTimeDomainRAO() * newMsg1FDM; newTau = getTau(prachConfig->getX(), nSSB / newSSBPerRAO, newTotalRAOPerSubframe, prachConfig->getNumberofRASubframe()); if(newTau > tau){ newMsg1FDM = fRAO[++i]; break; } } if(newMsg1FDM == fRAO[0]) SPDLOG_INFO("msg1FDM reach minimum capacity\n"); } SPDLOG_TRACE("new tau: {0}", newTau); return newMsg1FDM; } int MonitorRAFunction::getNewMsg1FDMver2(double *newSSBPerRAO){ int newTau = getTau(prachConfig->getX(), nSSB / *newSSBPerRAO, availiableRAO->getTotalRAOPerSubframe(), prachConfig->getNumberofRASubframe()); SPDLOG_TRACE("new tau: {0}", newTau); int msg1FDM = availiableRAO->getMsg1FDM(); int i = log(msg1FDM) / log(2); SPDLOG_TRACE("msg1fdm index: {0}", i); double newMsg1FDM = pow(2, i); if(*newSSBPerRAO < ssbPerRAO && newTau > tau && newTau > 10 && msg1FDM < 8){ newMsg1FDM = (((double)(estimateUEs * ssbPerRAO * exp(1))) / ((double)availiableRAO->getNumberofPreambles() * nSSB)) * (((double)availiableRAO->getTotalNeedRAO()) / ((double)prachConfig->getNumberofTimeDomainRAO() * raCount)); SPDLOG_TRACE("new msg1FDM in double: {0}", newMsg1FDM); newMsg1FDM = pow(2, ceil(log(newMsg1FDM) / log(2))); SPDLOG_TRACE("new msg1FDM: {0}", newMsg1FDM); *newSSBPerRAO = ssbPerRAO; if(newMsg1FDM > 8){ *newSSBPerRAO = calculateNewSSBPerRAO(availiableRAO->getNumberofPreambles(), nSSB, estimateUEs, prachConfig->getNumberofTimeDomainRAO(), newMsg1FDM, availiableRAO->getTotalNeedRAO()); SPDLOG_TRACE("new ssb per rao: {0}", *newSSBPerRAO); SPDLOG_INFO("msg1-FDM reach maximum capacity"); newMsg1FDM = 8; } } else if(*newSSBPerRAO > ssbPerRAO){ newMsg1FDM = (((double)(estimateUEs * ssbPerRAO * exp(1))) / ((double)availiableRAO->getNumberofPreambles() * nSSB)) * (((double)availiableRAO->getTotalNeedRAO()) / ((double)prachConfig->getNumberofTimeDomainRAO() * raCount)); SPDLOG_TRACE("new msg1FDM in double: {0}", newMsg1FDM); if(newMsg1FDM < 1){ SPDLOG_INFO("msg1FDM reach minimum capacity\n"); newMsg1FDM = 1; } newMsg1FDM = pow(2, ceil(log(newMsg1FDM) / log(2))); SPDLOG_TRACE("new msg1FDM: {0}", newMsg1FDM); i = log(newMsg1FDM) / log(2); int j = log(ssbPerRAO) / log(2); SPDLOG_TRACE("msg1fdm index: {0}", i); *newSSBPerRAO = ssbPerRAO; while(newMsg1FDM < 8){ //newMsg1FDM = pow(2, --i); SPDLOG_TRACE("msg1fdm index: {0}", i); int newTotalRAOPerSubframe = prachConfig->getNumberofTimeDomainRAO() * newMsg1FDM; newTau = getTau(prachConfig->getX(), nSSB / *newSSBPerRAO, newTotalRAOPerSubframe, prachConfig->getNumberofRASubframe()); SPDLOG_TRACE("new tau: {0}", newTau); SPDLOG_TRACE("lod tau: {0}", tau); if(newTau > tau && newTau > 10){ newMsg1FDM = pow(2, ++i); *newSSBPerRAO = calculateNewSSBPerRAO(availiableRAO->getNumberofPreambles(), nSSB, estimateUEs, prachConfig->getNumberofTimeDomainRAO(), newMsg1FDM, availiableRAO->getTotalNeedRAO()); } else{ break; } } if(i == 3) SPDLOG_INFO("msg1FDM reach maximum capacity\n"); else if(i == 1) SPDLOG_INFO("msg1FDM reach minimum capacity\n"); } SPDLOG_TRACE("new tau: {0}", newTau); return newMsg1FDM; } // get delta by given configuration // nPreambles: number of CBRA preambles // ssbPerRAO: ssb per rao // return: delta double MonitorRAFunction::calculateDelta(const int nPreambles, const double ssbPerRAO){ //printf("nPreamble: %d\n", nPreambles); //printf("ssb per rao: %f\n", ssbPerRAO); double newDelta = ((double)(nPreambles * nSSB)) / (exp(1) * ssbPerRAO) * ((double)(prachConfig->getNumberofTimeDomainRAO() * availiableRAO->getMsg1FDM()) / (double)availiableRAO->getTotalNeedRAO()); SPDLOG_TRACE("time domain raos: {0}", prachConfig->getNumberofTimeDomainRAO()); SPDLOG_TRACE("msg1-FDM: {0}", availiableRAO->getMsg1FDM()); SPDLOG_TRACE("total need raos: {0}", availiableRAO->getTotalNeedRAO()); return newDelta; } // calculate new ssb per rao based on estimate ues // return: new ssb per rao double MonitorRAFunction::calculateNewSSBPerRAO(){ //double newSSBPerRAO = (availiableRAO->getNumberofPreambles() * nSSB) / (estimateUEs * exp(1)) // * ((double)(prachConfig->getNumberofTimeDomainRAO() * availiableRAO->getMsg1FDM()) / (double)availiableRAO->getTotalNeedRAO()) * raCount; //SPDLOG_TRACE("new ssb per rao in double: {0}", newSSBPerRAO); //if(newSSBPerRAO > nSSB && nSSB != 64){ // SPDLOG_WARN("new ssb per rao is larger than nSSB"); // SPDLOG_WARN("new ssb per rao: {0}", newSSBPerRAO); // return nSSB; //} //if(sRAO[0] > newSSBPerRAO){ // SPDLOG_INFO("maximum ssb per rao reached\n"); // return sRAO[0]; //} //double newsRAO = pow(2, ceil(log(newSSBPerRAO) / log(2))); ////int i = 0; ////while(i < 7 && !(sRAO[i] <= newSSBPerRAO && newSSBPerRAO <= sRAO[i + 1])) //// i++; //SPDLOG_WARN("new ssb per rao: {0}", newsRAO); return calculateNewSSBPerRAO(availiableRAO->getNumberofPreambles(), nSSB, estimateUEs, prachConfig->getNumberofTimeDomainRAO(), availiableRAO->getMsg1FDM(), availiableRAO->getTotalNeedRAO()); //return newsRAO; } // calculate new ssb per rao based on estimate ues // return: new ssb per rao double MonitorRAFunction::calculateNewSSBPerRAO(const double nPreambles, const double nSSB, const double estimateUEs, const double tRAO, const double fRAO, const double totalNeedRAO){ double newSSBPerRAO = (nPreambles * nSSB) / (estimateUEs * exp(1)) * ((tRAO * fRAO) / totalNeedRAO) * raCount; SPDLOG_TRACE("new ssb per rao in double: {0}", newSSBPerRAO); if(newSSBPerRAO > nSSB && nSSB != 64){ SPDLOG_WARN("new ssb per rao is larger than nSSB"); SPDLOG_WARN("new ssb per rao: {0}", newSSBPerRAO); return nSSB; } if(sRAO[0] > newSSBPerRAO){ SPDLOG_INFO("maximum ssb per rao reached\n"); return sRAO[0]; } double newsRAO = pow(2, floor(log(newSSBPerRAO) / log(2))); //int i = 0; //while(i < 7 && !(sRAO[i] <= newSSBPerRAO && newSSBPerRAO <= sRAO[i + 1])) // i++; SPDLOG_WARN("new ssb per rao: {0}", newsRAO); return newsRAO; } // estimate next period's arrival ues by AR unsigned long MonitorRAFunction::estimateNextUEsBySIBPeriod(){ if(history.size() <= 1){ SPDLOG_WARN("history is not enough, return first slot success UEs"); return successUEs; } //if(historySlot.size() > raCount * 3){ // SPDLOG_WARN("history maximum size reached"); // SPDLOG_WARN("historySlot size: {0}", historySlot.size()); // historySlot.erase(historySlot.begin(), historySlot.begin() + raCount); // SPDLOG_WARN("historySlot size: {0}", historySlot.size()); //} double average = 0; for(auto it = history.begin();it != history.end();it++) average += (*it); average /= history.size(); SPDLOG_INFO("success ues: {0}", successUEs); SPDLOG_INFO("average: {0}", average); long double numerator = 0; long double denominator = 0; for(decltype(history.size()) i = history.size() - 1;i > 0;--i){ SPDLOG_WARN("i: {0}", i); numerator += (history[i] - average) * (history[i - 1] - average); denominator += pow((history[i] - average), 2); } double beta = numerator / denominator; SPDLOG_WARN("beta: {0}", beta); auto yt = history.back() - average; double estimate = yt * beta + average; SPDLOG_WARN("estimate ues: {0}", estimateUEs); return estimate; } // estimate next period's arrival ues by AR unsigned long MonitorRAFunction::estimateNextUEsBySlot(){ if(historySlot.size() <= 1){ SPDLOG_WARN("historySlot is not enough, return first slot success UEs"); return successUEs; } if(historySlot.size() > raCount * 2){ SPDLOG_WARN("ra count: {0}", raCount); SPDLOG_WARN("history maximum size reached"); SPDLOG_WARN("historySlot size: {0}", historySlot.size()); historySlot.erase(historySlot.begin(), historySlot.begin() + raCount); SPDLOG_WARN("historySlot size: {0}", historySlot.size()); } double average = 0; for(auto it = historySlot.begin();it != historySlot.end();it++) average += (*it); average /= historySlot.size(); SPDLOG_INFO("success ues: {0}", successUEs); SPDLOG_INFO("average: {0}", average); long double numerator = 0; long double denominator = 0; for(decltype(historySlot.size()) i = historySlot.size() - 1;i > 0;--i){ //SPDLOG_WARN("i: {0}", i); numerator += (historySlot[i] - average) * (historySlot[i - 1] - average); denominator += pow((historySlot[i] - average), 2); } double beta = numerator / denominator; SPDLOG_WARN("beta: {0}", beta); if(beta > 1){ SPDLOG_WARN("beta > 1, fix beta to 1"); beta = 1; } else if(beta < -1){ SPDLOG_WARN("beta < -1, fix beta to -1"); beta = -1; } auto yt = historySlot.back() - average; SPDLOG_WARN("yt: {0}", yt); long double estimate = 0; SPDLOG_WARN("ra count: {0}", raCount); for(int i = 0;i < raCount;++i){ estimate = estimate + yt * beta + average; beta *= beta; SPDLOG_WARN("estimate ues: {0}", estimate); } SPDLOG_WARN("estimate ues: {0}", estimate); return estimate; } // get success UEs // return: success ues count unsigned long MonitorRAFunction::getSuccessUEs(){ return successUEs; } // get failed UEs // return: failed ues count unsigned long MonitorRAFunction::getFailedUEs(){ return failedUEs; } // get estimate UEs // return: estimate ues double MonitorRAFunction::getEstimateUEs(){ return estimateUEs; } // get delta // return: channel capacity delta double MonitorRAFunction::getTotalDelta(){ return totalDelta; } <file_sep>/main/src/main.cpp #include <stdlib.h> #include <QApplication> #include "mainGUI.h" #include "includefile.h" #include "include_log.h" void initialize_log(){ try{ auto console_log = std::make_shared<spdlog::sinks::stdout_color_sink_mt>(); console_log->set_level(spdlog::level::info); console_log->set_pattern("[Project-Logging] [%@] [ %^%l%$ ] %v"); //auto trace_log = std::make_shared<spdlog::sinks::basic_file_sink_mt>("./log/trace_log.log", true); //trace_log->set_level(spdlog::level::trace); //trace_log->set_pattern("[%Y-%m-%d %T] [Project-Logging] [%@] [ %^%l%$ ] %v"); auto debug_log = std::make_shared<spdlog::sinks::basic_file_sink_mt>("./log/debug_log.log", true); debug_log->set_level(spdlog::level::debug); debug_log->set_pattern("[Project-Logging] [%@] [ %^%l%$ ] %v"); std::vector<spdlog::sink_ptr> sinks; sinks.push_back(console_log); //sinks.push_back(trace_log); sinks.push_back(debug_log); auto combined = std::make_shared<spdlog::logger>("multi sinks", begin(sinks), end(sinks)); //combined->set_level(spdlog::level::trace); //combined->flush_on(spdlog::level::trace); spdlog::register_logger(combined); spdlog::set_default_logger(combined); SPDLOG_TRACE("start logging"); } catch(const spdlog::spdlog_ex& ex){ printf("log initialization failed\n"); abort(); } } int main(int argc, char *argv[]){ initialize_log(); QApplication a(argc, argv); MainGUI gui; gui.move(100, 100); gui.show(); return a.exec(); } <file_sep>/project_test/src_test/RAOtestPrachConfig25.cpp #ifndef PRACH_INDEX_25_TEST #define PRACH_INDEX_25_TEST #include "general_definition.h" extern Cell* cell; extern UE* ue; void testPrachIndex25_24(){ int prachConfigIndex = 25; int msg1FDM = 8; double ssbPerRAO = 4; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; for(int k = 0;k < 5;k++){ int rao = 0; while(j % (associationFrame * 10) < 0 + 2 * k){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(rao++); subframeExpect->push_back(rao++); subframeExpect->push_back(rao++); subframeExpect->push_back(rao++); subframeExpect->push_back(rao++); subframeExpect->push_back(rao++); subframeExpect->push_back(rao++); subframeExpect->push_back(rao++); expected.push_back(*subframeExpect); j++; } while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex25_23(){ int prachConfigIndex = 25; int msg1FDM = 4; double ssbPerRAO = 4; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; for(int k = 0;k < 5;k++){ int rao = 0; while(j % (associationFrame * 10) < 0 + 2 * k){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(rao++); subframeExpect->push_back(rao++); subframeExpect->push_back(rao++); subframeExpect->push_back(rao++); expected.push_back(*subframeExpect); j++; } while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex25_22(){ int prachConfigIndex = 25; int msg1FDM = 2; double ssbPerRAO = 4; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; for(int k = 0;k < 5;k++){ int rao = 0; while(j % (associationFrame * 10) < 0 + 2 * k){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(rao++); subframeExpect->push_back(rao++); expected.push_back(*subframeExpect); j++; } while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex25_21(){ int prachConfigIndex = 25; int msg1FDM = 1; double ssbPerRAO = 4; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; for(int k = 0;k < 5;k++){ while(j % (associationFrame * 10) < 0 + 2 * k){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(0); expected.push_back(*subframeExpect); j++; } while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex25_20(){ int prachConfigIndex = 25; int msg1FDM = 8; double ssbPerRAO = 2; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; for(int k = 0;k < 5;k++){ while(j % (associationFrame * 10) < 0 + 2 * k){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(0); subframeExpect->push_back(2); subframeExpect->push_back(4); subframeExpect->push_back(6); expected.push_back(*subframeExpect); j++; } while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex25_19(){ int prachConfigIndex = 25; int msg1FDM = 4; double ssbPerRAO = 2; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; for(int k = 0;k < 5;k++){ while(j % (associationFrame * 10) < 0 + 2 * k){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(0); subframeExpect->push_back(2); expected.push_back(*subframeExpect); j++; } while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex25_18(){ int prachConfigIndex = 25; int msg1FDM = 2; double ssbPerRAO = 2; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; for(int k = 0;k < 5;k++){ int rao = 0; while(j % (associationFrame * 10) < 0 + 2 * k){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(rao++); expected.push_back(*subframeExpect); j++; } while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex25_17(){ int prachConfigIndex = 25; int msg1FDM = 1; double ssbPerRAO = 2; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; for(int k = 0;k < 2;k++){ int rao = 0; while(j % (associationFrame * 10) < 0 + 4 * k){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(rao++); expected.push_back(*subframeExpect); j++; } while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex25_16(){ int prachConfigIndex = 25; int msg1FDM = 8; double ssbPerRAO = 0.125; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; int rao = 8; for(int k = 0;k < 1;k++){ while(j % (associationFrame * 10) < 2 + 2 * k){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(rao++); subframeExpect->push_back(rao++); subframeExpect->push_back(rao++); subframeExpect->push_back(rao++); subframeExpect->push_back(rao++); subframeExpect->push_back(rao++); subframeExpect->push_back(rao++); subframeExpect->push_back(rao++); expected.push_back(*subframeExpect); j++; } while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex25_15(){ int prachConfigIndex = 25; int msg1FDM = 4; double ssbPerRAO = 0.125; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 2; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; int rao = 8; for(int k = 0;k < 2;k++){ while(j % (associationFrame * 10) < 4 + 2 * k){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(rao++); subframeExpect->push_back(rao++); subframeExpect->push_back(rao++); subframeExpect->push_back(rao++); expected.push_back(*subframeExpect); j++; } while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex25_14(){ int prachConfigIndex = 25; int msg1FDM = 2; double ssbPerRAO = 0.125; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 4; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; int rao = 8; for(int k = 0;k < 4;k++){ while(j % (associationFrame * 10) < 8 + 2 * k){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(rao++); subframeExpect->push_back(rao++); expected.push_back(*subframeExpect); j++; } while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex25_13(){ int prachConfigIndex = 25; int msg1FDM = 1; double ssbPerRAO = 0.125; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 8; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; int rao = 8; for(int k = 0;k < 8;k++){ while(j % (associationFrame * 10) < 16 + 2 * k){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(rao++); expected.push_back(*subframeExpect); j++; } while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex25_12(){ int prachConfigIndex = 25; int msg1FDM = 8; double ssbPerRAO = 0.25; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; for(int k = 0;k < 2;k++){ int rao = 4; while(j % (associationFrame * 10) < 0 + 4 * k){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(rao++); subframeExpect->push_back(rao++); subframeExpect->push_back(rao++); subframeExpect->push_back(rao++); expected.push_back(*subframeExpect); j++; } while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex25_11(){ int prachConfigIndex = 25; int msg1FDM = 4; double ssbPerRAO = 0.25; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; int rao = 4; for(int k = 0;k < 1;k++){ while(j % (associationFrame * 10) < 2 + 2 * k){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(rao++); subframeExpect->push_back(rao++); subframeExpect->push_back(rao++); subframeExpect->push_back(rao++); expected.push_back(*subframeExpect); j++; } while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex25_10(){ int prachConfigIndex = 25; int msg1FDM = 2; double ssbPerRAO = 0.25; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 2; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; int rao = 4; for(int k = 0;k < 2;k++){ while(j % (associationFrame * 10) < 4 + 2 * k){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(rao++); subframeExpect->push_back(rao++); expected.push_back(*subframeExpect); j++; } while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex25_9(){ int prachConfigIndex = 25; int msg1FDM = 1; double ssbPerRAO = 0.25; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 4; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; int rao = 4; for(int k = 0;k < 4;k++){ while(j % (associationFrame * 10) < 8 + 2 * k){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(rao++); expected.push_back(*subframeExpect); j++; } while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex25_8(){ int prachConfigIndex = 25; int msg1FDM = 8; double ssbPerRAO = 0.5; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; for(int k = 0;k < 5;k++){ while(j % (associationFrame * 10) < 2 * k){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(2); subframeExpect->push_back(3); expected.push_back(*subframeExpect); j++; } while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex25_7(){ int prachConfigIndex = 25; int msg1FDM = 4; double ssbPerRAO = 0.5; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(2); subframeExpect->push_back(3); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) < 4){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(2); subframeExpect->push_back(3); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex25_6(){ int prachConfigIndex = 25; int msg1FDM = 2; double ssbPerRAO = 0.5; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 2){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(2); subframeExpect->push_back(3); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex25_5(){ int prachConfigIndex = 25; int msg1FDM = 1; double ssbPerRAO = 0.5; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 2; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 4){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(2); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) < 6){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(3); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex25_4(){ int prachConfigIndex = 25; int msg1FDM = 8; double ssbPerRAO = 1; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; for(int k = 0;k < 5;k++){ while(j % (associationFrame * 10) < k * 2){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(1); subframeExpect->push_back(5); expected.push_back(*subframeExpect); j++; } while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex25_3(){ int prachConfigIndex = 25; int msg1FDM = 4; double ssbPerRAO = 1; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; for(int k = 0;k < 5;k++){ while(j % (associationFrame * 10) < k * 2){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(1); expected.push_back(*subframeExpect); j++; } while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex25_2(){ int prachConfigIndex = 25; int msg1FDM = 2; double ssbPerRAO = 1; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(1); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) < 4){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(1); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex25_1(){ int prachConfigIndex = 25; int msg1FDM = 1; double ssbPerRAO = 1; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 2){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(1); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex25(){ testPrachIndex25_1(); testPrachIndex25_2(); testPrachIndex25_3(); testPrachIndex25_4(); testPrachIndex25_5(); testPrachIndex25_6(); testPrachIndex25_7(); testPrachIndex25_8(); testPrachIndex25_9(); testPrachIndex25_10(); testPrachIndex25_11(); testPrachIndex25_12(); testPrachIndex25_13(); testPrachIndex25_14(); testPrachIndex25_15(); testPrachIndex25_16(); testPrachIndex25_17(); testPrachIndex25_18(); testPrachIndex25_19(); testPrachIndex25_20(); testPrachIndex25_21(); testPrachIndex25_22(); testPrachIndex25_23(); testPrachIndex25_24(); } #endif <file_sep>/project_test/src_test/RAOtestPrachConfig101.cpp #ifndef PRACH_INDEX_101_TEST #define PRACH_INDEX_101_TEST #include "general_definition.h" extern Cell* cell; extern UE* ue; void testPrachIndex101_19(){ int prachConfigIndex = 101; int msg1FDM = 4; double ssbPerRAO = 4; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 1){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; for(int k = 0;k < 48;k++){ subframeExpect->push_back(k); } expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex101_18(){ int prachConfigIndex = 101; int msg1FDM = 1; double ssbPerRAO = 4; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 1){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; for(int k = 0;k < 12;k++){ subframeExpect->push_back(k); } expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex101_17(){ int prachConfigIndex = 101; int msg1FDM = 8; double ssbPerRAO = 2; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 1){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; for(int k = 0;k < 48;k++){ subframeExpect->push_back(k * 2); } expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex101_16(){ int prachConfigIndex = 101; int msg1FDM = 4; double ssbPerRAO = 2; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 1){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; for(int k = 0;k < 24;k++){ subframeExpect->push_back(k * 2); } expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex101_15(){ int prachConfigIndex = 101; int msg1FDM = 1; double ssbPerRAO = 2; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 1){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; for(int k = 0;k < 6;k++){ subframeExpect->push_back(k * 2); } expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex101_14(){ int prachConfigIndex = 101; int msg1FDM = 8; double ssbPerRAO = 1.0 / 8.0; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 1){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; for(int l = 0;l < 3;l++){ for(int k = 8;k < 16;k++){ subframeExpect->push_back(k + l * 32); } } expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex101_13(){ int prachConfigIndex = 101; int msg1FDM = 4; double ssbPerRAO = 1.0 / 8.0; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 1){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; for(int k = 8;k < 16;k++){ subframeExpect->push_back(k); } expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex101_12(){ int prachConfigIndex = 101; int msg1FDM = 2; double ssbPerRAO = 1.0 / 8.0; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 2; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 1){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; for(int k = 8;k < 16;k++){ subframeExpect->push_back(k); } expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex101_11(){ int prachConfigIndex = 101; int msg1FDM = 1; double ssbPerRAO = 1.0 / 8.0; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 4; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; for(int l = 0;l < 2;l++){ while(j % (associationFrame * 10) < 1 + l * 10){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; for(int k = 8 + l * 4;k < 12 + l * 4;k++){ subframeExpect->push_back(k); } expected.push_back(*subframeExpect); j++; } while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex101_10(){ int prachConfigIndex = 101; int msg1FDM = 8; double ssbPerRAO = 1.0 / 4.0; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 1){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; for(int l = 0;l < 6;l++){ for(int k = 4;k < 8;k++){ subframeExpect->push_back(k + l * 16); } } expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex101_9(){ int prachConfigIndex = 101; int msg1FDM = 1; double ssbPerRAO = 1.0 / 4.0; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 2; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 1){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; for(int l = 0;l < 1;l++){ for(int k = 4;k < 8;k++){ subframeExpect->push_back(k + l * 16); } } expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex101_8(){ int prachConfigIndex = 101; int msg1FDM = 8; double ssbPerRAO = 1.0 / 2.0; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 1){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; for(int l = 0;l < 12;l++){ for(int k = 2;k < 4;k++){ subframeExpect->push_back(k + l * 8); } } expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex101_7(){ int prachConfigIndex = 101; int msg1FDM = 4; double ssbPerRAO = 1.0 / 2.0; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 1){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; for(int l = 0;l < 6;l++){ for(int k = 2;k < 4;k++){ subframeExpect->push_back(k + l * 8); } } expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex101_6(){ int prachConfigIndex = 101; int msg1FDM = 2; double ssbPerRAO = 1.0 / 2.0; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 1){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; for(int l = 0;l < 3;l++){ for(int k = 2;k < 4;k++){ subframeExpect->push_back(k + l * 8); } } expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex101_5(){ int prachConfigIndex = 101; int msg1FDM = 1; double ssbPerRAO = 1.0 / 2.0; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 1){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; for(int k = 2;k < 4;k++){ subframeExpect->push_back(k); } //subframeExpect->push_back(1); //subframeExpect->push_back(5); //subframeExpect->push_back(9); //subframeExpect->push_back(13); //subframeExpect->push_back(17); //subframeExpect->push_back(21); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex101_4(){ int prachConfigIndex = 101; int msg1FDM = 8; double ssbPerRAO = 1; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 1){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; for(int k = 0;k < 24;k++){ subframeExpect->push_back(1 + k * 4); } //subframeExpect->push_back(1); //subframeExpect->push_back(5); //subframeExpect->push_back(9); //subframeExpect->push_back(13); //subframeExpect->push_back(17); //subframeExpect->push_back(21); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex101_3(){ int prachConfigIndex = 101; int msg1FDM = 4; double ssbPerRAO = 1; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 1){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; for(int k = 0;k < 12;k++){ subframeExpect->push_back(1 + k * 4); } //subframeExpect->push_back(1); //subframeExpect->push_back(5); //subframeExpect->push_back(9); //subframeExpect->push_back(13); //subframeExpect->push_back(17); //subframeExpect->push_back(21); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex101_2(){ int prachConfigIndex = 101; int msg1FDM = 2; double ssbPerRAO = 1; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 1){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(1); subframeExpect->push_back(5); subframeExpect->push_back(9); subframeExpect->push_back(13); subframeExpect->push_back(17); subframeExpect->push_back(21); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex101_1(){ int prachConfigIndex = 101; int msg1FDM = 1; double ssbPerRAO = 1; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 1){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(1); subframeExpect->push_back(5); subframeExpect->push_back(9); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex101(){ testPrachIndex101_1(); testPrachIndex101_2(); testPrachIndex101_3(); testPrachIndex101_4(); testPrachIndex101_5(); testPrachIndex101_6(); testPrachIndex101_7(); testPrachIndex101_8(); testPrachIndex101_9(); testPrachIndex101_10(); testPrachIndex101_11(); testPrachIndex101_12(); testPrachIndex101_13(); testPrachIndex101_14(); testPrachIndex101_15(); testPrachIndex101_16(); testPrachIndex101_17(); testPrachIndex101_18(); testPrachIndex101_19(); } #endif <file_sep>/main/src/UE.h #ifndef UE_DEFINE #define UE_DEFINE #include <QPainter> #include <random> #include "include_log.h" #include "Beam.h" #include "Cell.h" #include "IPRACHConfig.h" #include "IAvailiableRAO.h" #include "includefile.h" #include "CommonMath.h" #include "random_access.h" #include "IDrawable.h" class Cell; class UE : public IDrawable{ public: UE(int x, int y, unsigned long id); UE(int x, int y, unsigned long id, bool isTest); void setXY(int x, int y); void setBeam(int cellIndex, int beamIndex, int beamStrength); int receiveSI(Cell *beam); void doRA(); void receiveRAR(const std::vector<RAR*>& rars, const int cellIndex); void setActiveTime(const int frameIndex, const int subframeIndex); unsigned long getID(); int getX(); int getY(); int getBeamIndex(); int getCellIndex(); int getBeamStrength(); int getActiveFrame(); int getActiveSubframe(); int getDepartedFrame(); int getDepartedSubframe(); int getRAFrame(); int getRASubframe(); int getRAMsg1FDM(); int getSelectPreambleIndex(); int getSelectRAOIndex(); double getRASSBPerRAO(); bool receiveCR(const std::vector<Msg3*>& CRs, const int cellIndex); bool isBindCell(); bool isPreambleTransmit(); bool isRarReceived(); bool isMsg3Transmitted(); bool isRASuccess(); bool isCollided(); void draw(QPainter &painter); std::vector<int>& getRAOs(); ~UE(); private: void checkRA(); void updateRAOforRA(); void updateRAOforRA(const int startRAO, const int endRAO, const int subframeStartRAO, const int subframeEndRAO, const int totalNeedRAO); void storeRAOsforRA(int subframeStartRAO, int subframeEndRAO); void transmitMsg1(); void transmitMsg3(); unsigned long id; int x; int y; int beamIndex; int cellIndex; /////////// should modify to unsigned /////////// int beamStrength; int powerRamp; /////////// should modify to unsigned /////////// int UEPixelSize; int startRAO; int endRAO; int raStartRAO; int raEndRAO; int selectRAOIndex; int selectPreambleIndex; int uplinkResourceIndex; int tc_rnti; int activeFrame; int activeSubframe; int raFrame; int raSubframe; int msg3Frame; int msg3Subframe; int departedFrame; int departedSubframe; double raSSBPerRAO; int raMsg1FDM; bool preambleTransmitted; bool rarReceived; bool msg3Transmitted; bool raSuccess; bool collided; bool isTest; Cell *candidateCell; IPRACHConfig *prachConfig; IAvailiableRAO *availiableRAO; std::vector<int> raos; }; #endif <file_sep>/main/src/PRACHConfig.cpp #include "PRACHConfig.h" // constructor // prachConfigIndex: corresponding to TS 38.331 prach-ConfigurationIndex PRACHConfig::PRACHConfig(int prachConfigIndex){ this->prachConfigIndex = prachConfigIndex; } //destructor PRACHConfig::~PRACHConfig(){ } // set prach-ConfigurationIndex // and config RA parameters // prachConfigIndex: cooresponding to TS 38.331 prach-ConfigurationIndex void PRACHConfig::setPrachConfigIndex(int prachConfigIndex){ this->prachConfigIndex = prachConfigIndex; configRA(); } // set number of prach slot in a subframe void PRACHConfig::setNumberofPrachSlot(int nPRACHSlot){ this->nPRACHSlot = nPRACHSlot; } // set number of time domain RAO per prach slot void PRACHConfig::setNumberofTimeDomainRAO(int nTimeDomainRAOPerPrachSlot){ this->nTimeDomainRAOPerPrachSlot = nTimeDomainRAOPerPrachSlot; } // get prach-ConfigurationIndex // return: prach-ConfigurationIndex int PRACHConfig::getPrachConfigIndex(){ return this->prachConfigIndex; } // get x, x corresponding to TS 38.211 6.3.3.2 table int PRACHConfig::getX(){ return x; } // get y, y corresponding to TS 38.211 6.3.3.2 table int PRACHConfig::getY(){ return y; } // get prach configuration period // minimum is 10ms(1 frame) // maximum is 160ms(16 frame) // associated with SSB rate matching period int PRACHConfig::getPrachConfigPeriod(){ return this->prachConfigPeriod; } // get subframes that can perform RA // return: each subframe can perform RA vector<int>& PRACHConfig::getRASubframe(){ return raSubframes; } // get number of prach slot in a subframe // return: number of prach slot in a subframe int PRACHConfig::getNumberofPRACHSlotinSubframe(){ return this->nPRACHSlot; } // get number of time domain rao per prach slot // return: number of time domain rao per prach slot int PRACHConfig::getNumberofTimeDomainRAOPerPrachSlot(){ return this->nTimeDomainRAOPerPrachSlot; } // get number of time domain rao in a subframe // return: number of time domain rao in a subframe int PRACHConfig::getNumberofTimeDomainRAO(){ return (this->nTimeDomainRAOPerPrachSlot * this->nPRACHSlot); } // get number of subframe that can perform RA // return: number of subframe that can perform RA int PRACHConfig::getNumberofRASubframe(){ return raSubframes.size(); } <file_sep>/main/src/AvailiableRAO.cpp #include "AvailiableRAO.h" //AvailiableRAO::AvailiableRAO(int nSSB){ // this->nSSB = nSSB; // printf("%f", this->ssbPerRAO); //} // constructor // nSSB: number of ssb of the cell // ssbPerRAO: corresponding to TS 38.331 ssb-perRACH-Occasion // msg1FDM: corresponding to TS 38.331 msg1-FDM // nPreambles: total number of availiable contention preambles can use per rao per cell // ssbPeriod: corresponding to SSB rate matching period // prachConfig: PrachConfig AvailiableRAO::AvailiableRAO(int nSSB, double ssbPerRAO, int msg1FDM, int nPreambles, int ssbPeriod, IPRACHConfig *prachConfig) : nSSB(nSSB), nPreambles(nPreambles), ssbPeriod(ssbPeriod), prachConfig(prachConfig){ setSSBPerRAO(ssbPerRAO); setMsg1FDM(msg1FDM); updateAssociationFrame(); } // set number of ssb of a cell // nSSB: number of ssb of a cell void AvailiableRAO::setNumberofSSB(int nSSB){ this->nSSB = nSSB; } // set msg1FDM // and update the number of total rao persubframe and frame // msg1FDM: corresponding to TS 38.331 msg1-FDM void AvailiableRAO::setMsg1FDM(int msg1FDM){ this->msg1FDM = msg1FDM; this->totalRAOPerSubframe = prachConfig->getNumberofTimeDomainRAO() * msg1FDM; this->totalRAOPerFrame = this->totalRAOPerSubframe * prachConfig->getNumberofRASubframe(); //printf("number of time domain raos: %d\n", // prachConfig->getNumberofTimeDomainRAO()); //printf("number of ra subframe: %d\n", // prachConfig->getNumberofRASubframe()); } // set number of contention preambles can use per rao per cell // nPreambles: number of contention preambles void AvailiableRAO::setNumberofPreambles(int nPreambles){ this->nPreambles = nPreambles; } // set ssb period // ssbPeriod: corresponding to SSB rate matching period void AvailiableRAO::setSSBPeriod(int ssbPeriod){ this->ssbPeriod = ssbPeriod; } // set ssb per rao // ssbPerRAO: corresponding to TS 38.331 ssb-perRACH-Occasion void AvailiableRAO::setSSBPerRAO(double ssbPerRAO){ this->ssbPerRAO = ssbPerRAO; this->totalNeedRAO = this->nSSB / ssbPerRAO; if(totalNeedRAO == 0){ SPDLOG_CRITICAL("ssb per rao: {0}", ssbPerRAO); SPDLOG_CRITICAL("nSSB: {0}", nSSB); SPDLOG_CRITICAL("total need rao: {0}", totalNeedRAO); SPDLOG_CRITICAL("total need rao should not be 0"); exit(1); } } // update subframe start and end RAO of current subframe // if current frame of subframe does not have enough RAO for mapping all SSB one more time // startRAO and endRAO is -1 // frameIndex: frame index // subframeIndex: subframe index void AvailiableRAO::updateStartandEndRAOofSubframe(const int frameIndex, const int subframeIndex){ SPDLOG_TRACE("updating rao of subframe"); if(isRASubframe(frameIndex, subframeIndex)){ SPDLOG_TRACE("next subframe is ra subframe"); int frame = frameIndex % associationFrame; frame = frame / (prachConfig->getPrachConfigPeriod() / 10); startRAO = frame * totalRAOPerFrame; vector<int> RASubframe = prachConfig->getRASubframe(); for(unsigned int i = 0;subframeIndex != RASubframe[i];i++) startRAO += totalRAOPerSubframe; SPDLOG_INFO("nSSB: {0}, msg1FDM: {1}, ssb per rao: {2}, time domain rao per subframe: {3}, ra subframe in a frame: {4}", nSSB, msg1FDM, ssbPerRAO, prachConfig->getNumberofTimeDomainRAO(), prachConfig->getNumberofRASubframe()); if(associationFrame == 1){ SPDLOG_INFO("association frame is 1"); // when total rao per frame can map all ssb more than 1 time int times = totalRAOPerFrame / totalNeedRAO; if((startRAO / totalNeedRAO) >= times){ // when remaining rao in the frame is not enough for // mapping all ssb one more time // remaining rao can not use for RA // corresponding to TS 38.213 8.1 startRAO = -1; endRAO = -1; return; } else{ endRAO = startRAO + totalRAOPerSubframe - 1; if(endRAO / totalNeedRAO >= times){ // if endRAO is larger than total rao of a frame can support // the endRAO is assigned to last RAO of this frame endRAO = times * totalNeedRAO - 1; startRAO %= totalNeedRAO; endRAO %= totalNeedRAO; } else{ startRAO %= totalNeedRAO; endRAO = startRAO + totalRAOPerSubframe - 1; } //printf("testing--->startRAO: %d, endRAO: %d\n", startRAO, endRAO); //printf("testing--->times: %d\n", times); return; } } else if(associationFrame > 1){ SPDLOG_INFO("association frame is not 1"); // a frame can not map all SSB to a RAO int times = 1; SPDLOG_WARN("start RAO: {0}", startRAO); SPDLOG_WARN("totalNeedRAO: {0}", totalNeedRAO); SPDLOG_WARN("end RAO: {0}", endRAO); SPDLOG_INFO("ssb per rao: {0}" , ssbPerRAO); if(startRAO / totalNeedRAO >= times){ startRAO = -1; endRAO = -1; return; } SPDLOG_TRACE("start rao calculated"); endRAO = startRAO + totalRAOPerSubframe - 1; if(endRAO / totalNeedRAO >= times) endRAO = times * totalNeedRAO - 1; SPDLOG_TRACE("end rao calculated"); } //endRAO = startRAO + totalRAOPerSubframe - 1; } SPDLOG_TRACE("update complete"); } // update association frame // corresponding to TS 38.213 8.1 void AvailiableRAO::updateAssociationFrame(){ // calculate association period for this PRACH configuration associationPeriod = (totalNeedRAO / totalRAOPerFrame); SPDLOG_INFO("totalNeedRAO: {0}, totalRAOPerFrame: {1}, totalRAOPerSubframe: {2}", totalNeedRAO, totalRAOPerFrame, totalRAOPerSubframe); if(totalNeedRAO % totalRAOPerFrame) associationPeriod += 1; // total need frame for all ssb mapping to // rao at least once // associationFrame can only be 1, 2, 4, 8, 16 associationFrame = (associationPeriod * prachConfig->getPrachConfigPeriod() / 10); if(!(associationFrame == 1 || associationFrame == 2 || associationFrame == 4 || associationFrame == 8 || associationFrame == 16)){ int association = 2; while(associationFrame / association != 0){ association *= 2; } associationFrame = association; } SPDLOG_INFO("associationFrame: {0}", associationFrame); } // get number of SSB of a cell // return: number of SSB in a cell int AvailiableRAO::getNumberofSSB(){ return this->nSSB; } // get number of msg1-FDM // return: msg1-FDM corresponding to TS 38.331 int AvailiableRAO::getMsg1FDM(){ return this->msg1FDM; } // get number of contention preambles per rao per cell // return: number of contention preambles int AvailiableRAO::getNumberofPreambles(){ return this->nPreambles; } // get ssb period // return: ssb period, corresponding to SSB rate matching period int AvailiableRAO::getSSBPeriod(){ return this->ssbPeriod; } // get start number of preamble can use for RA based on ssb index // ssbIndex: the index of ssb // return: the start index of preamble int AvailiableRAO::getStartNumberofPreamble(int ssbIndex){ if(this->ssbPerRAO > 1){ int start = (ssbIndex % (int)ssbPerRAO) * (this->nPreambles / this->ssbPerRAO); return start; } else return 0; } // get start number of RAO can use for RA based on ssbIndex // return: the start index of RAO can use int AvailiableRAO::getStartNumberofRAO(int ssbIndex){ return ssbIndex / this->ssbPerRAO; } // get start number of RAO for current subframe // return: start number of RAO for current subframe int AvailiableRAO::getStartRAOofSubframe(){ return startRAO; } // get end number of RAO for current subframe // return: end index of RAO for current subframe int AvailiableRAO::getEndRAOofSubframe(){ return endRAO; } // get total need RAO for mapping all SSB // return: total need RAO int AvailiableRAO::getTotalNeedRAO(){ return totalNeedRAO; } // get total RAO of a subframe // return: total RAO of a subframe int AvailiableRAO::getTotalRAOPerSubframe(){ return totalRAOPerSubframe; } // get ssb per rao // return: ssb per rao, corresponding to TS 38.331 double AvailiableRAO::getSSBPerRAO(){ return this->ssbPerRAO; } // check is this frame index and subframe index is // for this ssb index RA // frameIndex: frame index // subframeIndex: subframe index // return true: if this subframe can perform RA // otherwise false bool AvailiableRAO::isRASubframe(const int frameIndex, const int subframeIndex){ if(frameIndex % prachConfig->getX() != prachConfig->getY()){ //printf("frame index: %d is not for RA\n", frameIndex); return false; } vector<int> raSubframes = prachConfig->getRASubframe(); if(!binary_search(raSubframes.begin(), raSubframes.end(), subframeIndex)){ //printf("subframe index: %d isn't for RA\n", subframeIndex); return false; } return true; } // destructor AvailiableRAO::~AvailiableRAO(){ } <file_sep>/main/src/Beam.cpp #include "Beam.h" // constructor // x: x position of cell center // y: y position of cell center // beamIndex: beam index // lengthBeam: the beam length(strength), corresponding to Cell supportDistance member // spanAngle: each beam's area(in form of angle) in a cell Beam::Beam(Cell *parent, int cellIndex, int beamIndex, int lengthBeam, double spanAngle){ this->parent = parent; //setXY(x, y); setCellIndex(cellIndex); setBeamIndex(beamIndex); setLengthBeam(lengthBeam); setSpanAngle(spanAngle); setStartAngle(beamIndex, spanAngle); } // set beam's index // beamIndex: the index of beam void Beam::setBeamIndex(int beamIndex){ this->beamIndex = beamIndex; } // set length(strength) of this beam // lengthBeam: corresponding to Cell supportDistance member void Beam::setLengthBeam(int lengthBeam){ this->lengthBeam = lengthBeam; } // set span angle // the area cover by this beam, in form of angle // spanAngle: the angle covered by this beam void Beam::setSpanAngle(double spanAngle){ this->spanAngle = spanAngle; } // set this beam's start angle // beam will draw from (start angle) to ((start angle) + (span angle)) // beamIndex: the index of this beam // spanAngle: the angle covered by this beam void Beam::setStartAngle(int beamIndex, double spanAngle){ this->startAngle = (beamIndex) * spanAngle; } // set this beam's start angle // beam will draw from (start angle) to ((start angle) + (span angle)) // startAngle: the start drawing angle of this beam void Beam::setStartAngle(double startAngle){ if(startAngle < 0){ startAngle += 360; } this->startAngle = startAngle; } // set this beam's cell index // cellIndex: cell index void Beam::setCellIndex(int cellIndex){ this->cellIndex = cellIndex; } // detect UE is in this beam's area void Beam::detectUE(UE *ue, double power){ //printf("cell %d beam %d startAngle: %f, spanAngle: %f\n", // cellIndex, // beamIndex, // startAngle, // spanAngle); if(isInArea(ue->getX(), ue->getY(), getX(), getY(), startAngle, spanAngle, lengthBeam / 2)){ SPDLOG_TRACE("UE id {0} is in cell index {1} beam index {2}", ue->getID(), parent->getCellIndex(), getBeamIndex()); ue->setBeam(this->cellIndex, this->beamIndex, power); } } // get this beam's x position // return: this beam's x position, equals to x position of cell center int Beam::getX(){ return parent->getX(); } // get this beam's y position // return: this beam's y position, equals to y position of cell center int Beam::getY(){ return parent->getY(); } // get this beam's index // return: this beam's index int Beam::getBeamIndex(){ return this->beamIndex; } // get this beam's span angle // the beam will cover the area with this span angle // return: this beam's span angle double Beam::getSpanAngle(){ return this->spanAngle; } // get this beam's start angle // the beam will cover the area from (start angle) to ((start angle) + (span angle)) // return: this beam's start angle double Beam::getStartAngle(){ return this->startAngle; } // get this beam's end angle // return: this beam's end angle(startAngle + spaneAngle) int Beam::getEndAngle(){ int endAngle = this->startAngle + this->spanAngle; return (endAngle > 360)?(endAngle - 360):(endAngle); } // get this beam's length(strength) // the beam will cover the area from cell center to beam length(associate with strength) // return: this beam's length int Beam::getLengthBeam(){ return this->lengthBeam; } // get this beam's cell index // return: this beam's cell index int Beam::getCellIndex(){ return this->cellIndex; } // draw beam // painter: QPainter for drawing void Beam::draw(QPainter &painter){ painter.drawPie(getX() - lengthBeam / 2, getY() - lengthBeam / 2, lengthBeam, lengthBeam, startAngle * 16, spanAngle * 16); } // destructor Beam::~Beam(){ SPDLOG_TRACE("beam destructor"); } <file_sep>/main/scripts/plot_result.py import os import sys import csv import collections import numpy as np import matplotlib.pyplot as plt import matplotlib.ticker as ticker import math ############################# # plot the *newest* result from the result folder ############################# line_width = 3.0 marker_size = 7.0 label_font_size = 20 title_font_size = 24 legend_font_size = 16 plot_optimized = False def getSubframePeriod(prachIndex): if type(prachIndex) is not int: prachIndex = int(prachIndex) if prachIndex == 27: return 1 elif prachIndex == 25: return 2 elif prachIndex == 22: return 3 elif prachIndex == 19: return 5 elif prachIndex == 16: return 10 def avgSIBPeriodUELatency(latencies): total = 0 sibPeriod = 160 avg = [] count = 0 for profile in latencies.values(): if profile['arrival'] == sibPeriod: avg.append(total / count) total = 0 count = 0 sibPeriod = sibPeriod + 160 total = total + profile['latency'] count = count + 1 avg.append(total / count) return avg def collectDataUE(filename): latencies = {} with open(filename, newline='') as csvfile: rows = csv.DictReader(csvfile) #next(rows) for row in rows: activeTiming = int(row['Active Frame']) * 10 + int(row['Active Subframe']) departedTiming = int(row['Departed Frame']) * 10 + int(row['Departed Subframe']) latency = departedTiming - activeTiming + 1 latencies[int(row['UE ID'])] = {'arrival':activeTiming, 'latency':latency} latencies = collections.OrderedDict(sorted(latencies.items())) return latencies def collectDataCell(filename): successUEs = [] estimateUEs = [] arrivalUEs = [] participateUEs = [] delta = [] tau = [] timing = [] if plot_optimized: tauOp = [] deltaOp = [] with open(filename, newline='') as csvfile: rows = csv.DictReader(csvfile) for row in rows: timing.append(int(row['Current Frame']) * 10 + int(row['Current Subframe'])) successUEs.append(int(row['Success UEs'])) estimateUEs.append(int(row['Estimate UEs'])) arrivalUEs.append(int(row['Arrival UEs'])) participateUEs.append(int(row['Participate UEs'])) delta.append(float(row['Total Channel Capacity'])) tau.append(int(row['Tau'])) if plot_optimized: deltaOp.append(float(row['Total Channel Capacity Optimized'])) tauOp.append(float(row['Tau Optimized'])) # del estimateUEs[-1] # del delta[-1] del delta[0] del tau[-1] # estimateUEs.insert(0, 0) tau.insert(0, tau[0]) # delta.insert(0, delta[0]) delta.insert(len(delta), delta[-1]) if plot_optimized: return timing, arrivalUEs, participateUEs, successUEs, estimateUEs, delta, tau, deltaOp, tauOp return timing, arrivalUEs, participateUEs, successUEs, estimateUEs, delta, tau def plotDataUE(latencies, upperBound, filenameFig1 = None, subTitle = ""): newXticks = np.linspace(0, len(latencies), 11) fig = plt.figure(1) fig.set_size_inches(9.375, 7.3) ax = plt.subplot(1, 1, 1) #fig.subplots_adjust(top=0.83) plt.plot(range(len(latencies)), [x['latency'] for x in latencies.values()], 'r-') plt.xlabel("UE Index", fontsize=label_font_size) plt.ylabel("Latency (ms)", fontsize=label_font_size) for label in (ax.get_xticklabels() + ax.get_yticklabels()): label.set_fontsize(16) #plt.suptitle("Each UE Latency", fontweight="bold", fontsize=title_font_size) #plt.title(subTitle, fontsize=title_font_size) plt.axis([0, len(latencies), 0, upperBound + 5]) plt.xticks(newXticks) plt.grid(True) manager = plt.get_current_fig_manager() manager.window.wm_geometry("900x700+50+50") if filenameFig1: plt.savefig(filenameFig1) plt.close() del newXticks def plotDataCell(timing, arrivalUEs, participateUEs, successUEs, estimateUEs, delta, deltaOp=None, filenameFig2 = None, subTitle = ""): #xtick = math.ceil(max(timing) / 160) #xtick = [(x * 160) for x in range(xtick + 1)] maxNum = max([max(arrivalUEs), max(participateUEs), max(successUEs), max(estimateUEs), max(delta)]) if plot_optimized and (deltaOp is not None): maxNum = max(maxNum, max(deltaOp)) power = math.floor(math.log(maxNum, 10)) print(power) ylimit = round(maxNum / pow(10, power)) ylimit = (ylimit * 2) * pow(10, power) print(ylimit) fig = plt.figure(2) fig.set_size_inches(9.375, 7.3) ax = plt.subplot(1, 1, 1) line1, = ax.plot(timing, successUEs, 'g-s', label='Success UEs', linewidth=line_width, markersize=marker_size + 7) line2, = ax.plot(timing, estimateUEs, 'c-o', label='Estimate UEs', linewidth=line_width, markersize=marker_size + 3) line3, = ax.plot(timing, arrivalUEs, 'k-^', label='Arrival UEs', linewidth=line_width, markersize=marker_size + 7, fillstyle="none", markeredgewidth=3.0) line4, = ax.plot(timing, participateUEs, 'r-v', label='Participate UEs', linewidth=line_width, markersize=marker_size + 7, fillstyle="none", markeredgewidth=3.0) line5, = ax.plot(timing, delta, 'm-D', label='Total Channel Capacity', linewidth=line_width, markersize=marker_size + 2) if plot_optimized: line6, = ax.plot(timing, deltaOp, 'b-H', label='Optimized Channel Capacity', linewidth=line_width, markersize=marker_size + 10, fillstyle="none", markeredgewidth=3.0) for label in (ax.get_xticklabels() + ax.get_yticklabels()): label.set_fontsize(16) ax.legend(loc="upper left", fontsize=legend_font_size, ncol=2) ax.set_ylim(0, ylimit) #plt.xticks(xtick) #fig.subplots_adjust(top=0.83) #plt.suptitle("UEs Condition & Esitimate UEs", fontsize=title_font_size, fontweight="bold") #plt.suptitle("Beta Distribution Arrival", fontsize=14, fontweight="bold") #ax.set_title(subTitle, fontsize=title_font_size) plt.xlabel("Subframe Index", fontsize=label_font_size) plt.ylabel("Number of UEs", fontsize=label_font_size) plt.grid(True) manager = plt.get_current_fig_manager() manager.window.wm_geometry("900x700+450+50") if filenameFig2: plt.savefig(filenameFig2) plt.close() def plotSIBLatencyAndTau(avgSIBlatencies, tau, filename=None): del tau[0] while len(tau) != len(avgSIBlatencies): del tau[-1] fig = plt.figure(3) fig.set_size_inches(9.375, 7.3) ax1 = plt.subplot(1, 1, 1) t = [x + 1 for x in range(len(tau))] ax1.plot(t, avgSIBlatencies, 'r-o', linewidth=line_width, markersize=marker_size + 3) ax1.set_xlabel('SIB Period Index', fontsize=label_font_size) ax1.set_ylabel('Averge Latency (ms)', color='r', fontsize=label_font_size) ax1.tick_params('y', colors='r') ax2 = ax1.twinx() ax2.plot(t, tau, 'b-^', linewidth=line_width, markersize=marker_size + 6, fillstyle="none", markeredgewidth=3.0) ax2.set_ylabel('RA Attemp Period (ms)', color='b', fontsize=label_font_size) ax2.tick_params('y', colors='b') #fig.subplots_adjust(top=0.8) #plt.suptitle("Each SIB Period UE Average Latency\nvs\nRA Attempt Period", fontsize=title_font_size, fontweight="bold") ax1.grid(True) ytop = 10 * (int(max([max(avgSIBlatencies), max(tau)]) / 10) + 1) ax1.set_ylim(0, ytop) ax2.set_ylim(0, ytop) for label in (ax1.get_xticklabels() + ax1.get_yticklabels()): label.set_fontsize(16) for label in (ax2.get_xticklabels() + ax2.get_yticklabels()): label.set_fontsize(16) #fig.tight_layout() manager = plt.get_current_fig_manager() manager.window.wm_geometry("900x700+1050+50") if filename: plt.savefig(filename) plt.close() if __name__ == '__main__': command = sys.argv if 'plot_op' in command: plot_optimized = True print("plot optimized") #print(plot_optimized) ueFile = 'UE.csv' cellFile = 'Cell.csv' resultSourceFolder = "./result/" dirs = [(resultSourceFolder + d) for d in os.listdir(resultSourceFolder) if os.path.isdir(resultSourceFolder + d)] folderName = max(dirs, key=os.path.getmtime) print(folderName) prachConfig = folderName.split("prach-")[1] prachConfig = prachConfig.split("_")[0] simulationTime = folderName.split("simu-")[1] simulationTime = simulationTime.split("_")[0] arrivalMode = folderName.split("_")[4] arrival = folderName.split("_")[5] arrival = arrival.split("-")[1] if arrivalMode == "uniform": arrivalRate = arrival else: totalUE = arrival #print("prach:" + prachIndex) #print("simu:" + simulationTime) #print("arrival mode:" + arrivalMode) #print("arrival:" + arrival) subTitle = "RA Subframe Period: {0}ms, ".format(getSubframePeriod(prachConfig)) \ + "Simulation Time: {0}s\n".format(str(int(simulationTime))) \ + "Arrival Mode: {0}, ".format(arrivalMode) #subTitle = "Simulation Time: {0}s\n".format(str(int(simulationTime) / 1000)) \ # + "Arrival Mode: {0}, ".format(arrivalMode) if arrivalMode == "uniform": subTitle = subTitle + "Arrival Rate: {0} ".format(arrivalRate) else: subTitle = subTitle + "Total UE: {0} ".format(totalUE) filenameFig1 = folderName + "/" + "UE_latency" filenameFig2 = folderName + "/" + "Estimate_UEs" filenameFig3 = folderName + "/" + "AvgLatency_and_Tau" ueFile = folderName + "/" + ueFile cellFile = folderName + "/" + cellFile print(filenameFig1) print(filenameFig2) ############################ collect data ############################ latencies = collectDataUE(ueFile) avgSIBlatencies = avgSIBPeriodUELatency(latencies) upperBound = max([x['latency'] for x in latencies.values()]) while (upperBound % 5) != 0: upperBound += 1 if plot_optimized: timing, arrivalUEs, participateUEs, successUEs, estimateUEs, delta, tau, deltaOp, tauOp = collectDataCell(cellFile) else: timing, arrivalUEs, participateUEs, successUEs, estimateUEs, delta, tau = collectDataCell(cellFile) print(timing) ############################ collect data ############################ ############################ plot data ############################ plotDataUE(latencies, upperBound, filenameFig1, subTitle) if plot_optimized: plotDataCell(timing, arrivalUEs, participateUEs, successUEs, estimateUEs, delta, deltaOp, filenameFig2, subTitle) else: plotDataCell(timing, arrivalUEs, participateUEs, successUEs, estimateUEs, delta, None, filenameFig2, subTitle) plotSIBLatencyAndTau(avgSIBlatencies, tau, filenameFig3) plt.show() ############################ plot data ############################ del ueFile del cellFile del latencies del upperBound del arrivalUEs del participateUEs del successUEs del estimateUEs del delta del avgSIBlatencies del timing if plot_optimized: del deltaOp del tauOp <file_sep>/project_test/src_test/RAOtestPrachConfig19.cpp #ifndef PRACH_INDEX_19_TEST #define PRACH_INDEX_19_TEST #include "general_definition.h" extern Cell* cell; extern UE* ue; void testPrachIndex19_24(){ int prachConfigIndex = 19; int msg1FDM = 8; double ssbPerRAO = 4; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 1){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; for(int i = 0;i < 8;i++){ subframeExpect->push_back(i); } expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) < 6){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; for(int i = 0;i < 8;i++){ subframeExpect->push_back(i); } expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); //destoryExpects(expected); destory(); } void testPrachIndex19_23(){ int prachConfigIndex = 19; int msg1FDM = 4; double ssbPerRAO = 4; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 1){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; for(int i = 0;i < 4;i++){ subframeExpect->push_back(i); } expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) < 6){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; for(int i = 0;i < 4;i++){ subframeExpect->push_back(i); } expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); //destoryExpects(expected); destory(); } void testPrachIndex19_22(){ int prachConfigIndex = 19; int msg1FDM = 2; double ssbPerRAO = 4; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 1){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(0); subframeExpect->push_back(1); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) < 6){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(0); subframeExpect->push_back(1); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); //destoryExpects(expected); destory(); } void testPrachIndex19_21(){ int prachConfigIndex = 19; int msg1FDM = 1; double ssbPerRAO = 4; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 1){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(0); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) < 6){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(0); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); //destoryExpects(expected); destory(); } void testPrachIndex19_20(){ int prachConfigIndex = 19; int msg1FDM = 8; double ssbPerRAO = 2; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 1){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(0); subframeExpect->push_back(2); subframeExpect->push_back(4); subframeExpect->push_back(6); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) < 6){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(0); subframeExpect->push_back(2); subframeExpect->push_back(4); subframeExpect->push_back(6); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); //destoryExpects(expected); destory(); } void testPrachIndex19_19(){ int prachConfigIndex = 19; int msg1FDM = 4; double ssbPerRAO = 2; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 1){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(0); subframeExpect->push_back(2); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) < 6){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(0); subframeExpect->push_back(2); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); //destoryExpects(expected); destory(); } void testPrachIndex19_18(){ int prachConfigIndex = 19; int msg1FDM = 2; double ssbPerRAO = 2; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 1){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(0); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) < 6){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(0); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); //destoryExpects(expected); destory(); } void testPrachIndex19_17(){ int prachConfigIndex = 19; int msg1FDM = 1; double ssbPerRAO = 2; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 1){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(0); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); //destoryExpects(expected); destory(); } void testPrachIndex19_16(){ int prachConfigIndex = 19; int msg1FDM = 8; double ssbPerRAO = 0.125; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 2; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 6){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(8); subframeExpect->push_back(9); subframeExpect->push_back(10); subframeExpect->push_back(11); subframeExpect->push_back(12); subframeExpect->push_back(13); subframeExpect->push_back(14); subframeExpect->push_back(15); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); //destoryExpects(expected); destory(); } void testPrachIndex19_15(){ int prachConfigIndex = 19; int msg1FDM = 4; double ssbPerRAO = 0.125; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 4; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 11){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(8); subframeExpect->push_back(9); subframeExpect->push_back(10); subframeExpect->push_back(11); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) < 16){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(12); subframeExpect->push_back(13); subframeExpect->push_back(14); subframeExpect->push_back(15); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); //destoryExpects(expected); destory(); } void testPrachIndex19_14(){ int prachConfigIndex = 19; int msg1FDM = 2; double ssbPerRAO = 0.125; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 8; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 21){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(8); subframeExpect->push_back(9); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) < 26){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(10); subframeExpect->push_back(11); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) < 31){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(12); subframeExpect->push_back(13); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) < 36){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(14); subframeExpect->push_back(15); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); //destoryExpects(expected); destory(); } void testPrachIndex19_13(){ int prachConfigIndex = 19; int msg1FDM = 1; double ssbPerRAO = 0.125; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 16; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 41){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(8); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) < 46){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(9); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) < 51){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(10); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) < 56){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(11); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) < 61){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(12); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) < 66){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(13); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) < 71){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(14); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) < 76){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(15); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); //destoryExpects(expected); destory(); } void testPrachIndex19_12(){ int prachConfigIndex = 19; int msg1FDM = 8; double ssbPerRAO = 0.25; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 1){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(4); subframeExpect->push_back(5); subframeExpect->push_back(6); subframeExpect->push_back(7); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); //destoryExpects(expected); destory(); } void testPrachIndex19_11(){ int prachConfigIndex = 19; int msg1FDM = 4; double ssbPerRAO = 0.25; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 2; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 6){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(4); subframeExpect->push_back(5); subframeExpect->push_back(6); subframeExpect->push_back(7); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); //destoryExpects(expected); destory(); } void testPrachIndex19_10(){ int prachConfigIndex = 19; int msg1FDM = 2; double ssbPerRAO = 0.25; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 4; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 11){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(4); subframeExpect->push_back(5); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) < 16){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(6); subframeExpect->push_back(7); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); //destoryExpects(expected); destory(); } void testPrachIndex19_9(){ int prachConfigIndex = 19; int msg1FDM = 1; double ssbPerRAO = 0.25; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 8; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 21){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(4); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) < 26){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(5); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) < 31){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(6); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) < 36){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(7); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); //destoryExpects(expected); destory(); } void testPrachIndex19_8(){ int prachConfigIndex = 19; int msg1FDM = 8; double ssbPerRAO = 0.5; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 1){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(2); subframeExpect->push_back(3); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) < 6){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(2); subframeExpect->push_back(3); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); //destoryExpects(expected); destory(); } void testPrachIndex19_7(){ int prachConfigIndex = 19; int msg1FDM = 4; double ssbPerRAO = 0.5; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 1){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(2); subframeExpect->push_back(3); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); //destoryExpects(expected); destory(); } void testPrachIndex19_6(){ int prachConfigIndex = 19; int msg1FDM = 2; double ssbPerRAO = 0.5; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 2; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 6){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(2); subframeExpect->push_back(3); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); //destoryExpects(expected); destory(); } void testPrachIndex19_5(){ int prachConfigIndex = 19; int msg1FDM = 1; double ssbPerRAO = 0.5; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 4; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 11){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(2); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) < 16){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(3); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); //destoryExpects(expected); destory(); } void testPrachIndex19_4(){ int prachConfigIndex = 19; int msg1FDM = 8; double ssbPerRAO = 1; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 1){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(1); subframeExpect->push_back(5); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) < 6){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(1); subframeExpect->push_back(5); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); //destoryExpects(expected); destory(); } void testPrachIndex19_3(){ int prachConfigIndex = 19; int msg1FDM = 4; double ssbPerRAO = 1; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 1){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(1); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) < 6){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(1); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); //destoryExpects(expected); destory(); } void testPrachIndex19_2(){ int prachConfigIndex = 19; int msg1FDM = 2; double ssbPerRAO = 1; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 1){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(1); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); //destoryExpects(expected); destory(); } void testPrachIndex19_1(){ int prachConfigIndex = 19; int msg1FDM = 1; double ssbPerRAO = 1; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 2; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 6){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(1); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); //destoryExpects(expected); destory(); } void testPrachIndex19(){ testPrachIndex19_1(); testPrachIndex19_2(); testPrachIndex19_3(); testPrachIndex19_4(); testPrachIndex19_5(); testPrachIndex19_6(); testPrachIndex19_7(); testPrachIndex19_8(); testPrachIndex19_9(); testPrachIndex19_10(); testPrachIndex19_11(); testPrachIndex19_12(); testPrachIndex19_13(); testPrachIndex19_14(); testPrachIndex19_15(); testPrachIndex19_16(); testPrachIndex19_17(); testPrachIndex19_18(); testPrachIndex19_19(); testPrachIndex19_20(); testPrachIndex19_21(); testPrachIndex19_22(); testPrachIndex19_23(); testPrachIndex19_24(); } #endif <file_sep>/main/src/PRACHConfigFR1Paired.h #ifndef PRACH_CONFIGURATION_FR1_PAIRED #define PRACH_CONFIGURATION_FR1_PAIRED #include "PRACHConfig.h" class PRACHConfigFR1 : public PRACHConfig{ public: PRACHConfigFR1(int prachConfigIndex); ~PRACHConfigFR1(); void configRA(); }; #endif <file_sep>/main/src/SimulationCanvas.h #ifndef SCANVAS #define SCANVAS #include <QWidget> #include <QMouseEvent> #include <QPainter> #include <QStyleOption> #include "Model.h" #include "IPaintObservor.h" class SimulationCanvas : public QWidget, IPaintObservor{ Q_OBJECT public: SimulationCanvas(QWidget *parent = 0, Model *model = 0); void mouseMoveEvent(QMouseEvent *event); void mousePressEvent(QMouseEvent *event); void mouseReleaseEvent(QMouseEvent *event); void updateCanvas(); protected: void paintEvent(QPaintEvent *event); private: Model *model; }; #endif <file_sep>/main/src/include_log.h #ifndef INCLUDE_LOG #define INCLUDE_LOG #ifndef TESTING #define TESTING 0 #endif #define SPDLOG_ACTIVE_LEVEL SPDLOG_LEVEL_TRACE #include "spdlog/spdlog.h" #include "spdlog/sinks/basic_file_sink.h" #include "spdlog/sinks/stdout_color_sinks.h" #endif <file_sep>/main/run.sh #!/bin/bash echo $project_name qt_project_filename="${project_name}.pro" buildDir=./build qmake -project -o ${buildDir}/${qt_project_filename} sed -i '$a QT += widgets' ${buildDir}/${qt_project_filename} sed -i 's/INCLUDEPATH.*$/INCLUDEPATH += \/home\/daitor\/Qt\/5.12.0\/gcc_64\/include \.\.\/src \.\.\/include /g' ${buildDir}/${qt_project_filename} #sed -i 's/INCLUDEPATH.*$/INCLUDEPATH += \/home\/daitor\/Qt\/5.12.0\/gcc_64\/include \.\/src /g' ${buildDir}/${qt_project_filename} if [ ! -d "./log/" ]; then echo "log directory does not exist" mkdir log fi qmake ${buildDir}/${qt_project_filename} -o ${buildDir} make -C ${buildDir} && ./${buildDir}/${project_name} <file_sep>/project_test/src_test/general_definition.h #ifndef GENERAL_TEST_DEF #define GENERAL_TEST_DEF #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <vector> //#define TESTING 1 #include "../src/includefile.h" //#include "../src/Model.h" #include "../src/Cell.h" #include "../src/MacroCell.h" #include "../src/UE.h" extern Cell *cell = NULL; extern UE *ue = NULL; void initialize(){ cell = new MacroCell(100, 100, 0, 4, celltype::Macro, 27); cell->initializeBeams(); cell->updateBeamsAngle(0, 0); //cell->findCellCoverAreaEquation(); printf("%f\n", cell->getBeamStartAngle()); ue = new UE(110, 90, 0, true); cell->detectUE(ue); } void initialize(int prachConfigIndex, int msg1FDM, double ssbPerRAO){ initialize(); cell->setPrachConfigIndex(prachConfigIndex); cell->setMsg1FDM(msg1FDM); cell->setSSBPerRAO(ssbPerRAO); printf("msg1FDM: %d\n", cell->getMsg1FDM()); printf("ssb-perRAO: %f\n", cell->getSSBPerRAO()); } void destory(){ free(cell); free(ue); } void destoryExpects(vector<vector<int>> expects){ for(decltype(expects.size()) i = expects.size();i >= 0;--i){ delete &expects[i]; } } void failedTest(){ destory(); abort(); } int getRound(int simulationTime, int associationFrame){ int round = simulationTime / (associationFrame * 10); if(simulationTime % (associationFrame * 10) != 0) round += 1; printf("round: %d\n", round); return round; } void validation(vector<vector<int>>& expected, int simulationTime, int prachConfigIndex, int msg1FDM, double ssbPerRAO){ for(int i = 0;i < simulationTime;i++){ printf("===================info===================\n"); cell->broadcastSI(); ue->doRA(); vector<int>& raos = ue->getRAOs(); vector<int> expect = expected[i]; printf("%d\n", i); if(raos.size() != expect.size()){ printf("test case: \n"); printf("prachConfigIndex: %d\nmsg1FDM: %d\nSSBPerRAO: %f\n", prachConfigIndex, msg1FDM, ssbPerRAO); printf("test failed\n"); printf("ue raos size: %lu, expect raos size: %lu\n", raos.size(), expect.size()); failedTest(); } //assert(raos.size() == expect.size()); for(unsigned int j = 0;j < raos.size();j++){ printf("%d, %d\n", raos[j], expect[j]); //assert(raos[j] == expect[j]); if(raos[j] != expect[j]){ printf("test case: \n"); printf("prachConfigIndex: %d\nmsg1FDM: %d\nSSBPerRAO: %f\n", prachConfigIndex, msg1FDM, ssbPerRAO); printf("test failed\n"); printf("ue rao: %d, expect rao: %d\n", raos[j], expect[j]); failedTest(); } } cell->updateSubframe(); printf("===================info===================\n"); } } void printExpects(vector<vector<int>>& expected){ vector<int> temp; for(unsigned int i = 0;i < expected.size();i++){ temp = expected[i]; for(unsigned int j = 0;j < temp.size();j++){ printf("%d\t%d\n", i, temp[j]); } } } #endif <file_sep>/main/src/includefile.h #ifndef BASIC_INCLUDE #define BASIC_INCLUDE #include <stdio.h> #include <vector> #include <algorithm> #include <math.h> using namespace std; #endif <file_sep>/main/scripts/plot_tau_latency.py import os import csv import matplotlib.pyplot as plt import numpy as np import math from plot_result import collectDataUE, getSubframePeriod from evaluateResult import collectCellMsg1FDM, getPreambleLength from math import log ####################### # plot each tau_threshold for each prach-configurationIndex # uniform and beta distribution result ####################### # plot source folder organization # # candidateResult - ./10/ # | each prach configuration with uniform and beta # # ./20/ # | each prach configuration with uniform and beta # # ./40/ # | each prach configuration with uniform and beta # # ./80/ # | each prach configuration with uniform and beta # # ./160/ # | each prach configuration with uniform and beta figureCount = 0 line_width = 3.0 marker_size = 10.0 label_font_size = 20 title_font_size = 24 legend_font_size = 16 def findCandidateFolder(targetPrach, targetArrival, folderName): candidateIndex = [index for index in range(len(folderName)) if "prach-"+targetPrach in folderName[index]] candidateIndex = [candidateIndex[index] for index in range(len(candidateIndex)) if targetArrival in folderName[candidateIndex[index]]] #print(folderName) #print(candidateIndex) #print("target prach: ", targetPrach) #print("target arrival: ", targetArrival) #print("candidate folder: ", [folderName[candidateIndex[index]] for index in range(len(candidateIndex))]) return candidateIndex[0] def findCandidate(targetTau, targetPrach, targetArrival, targetSimulation, datas): candidateIndex = [index for index in range(len(datas)) if datas[index]['tau'] == targetTau] candidateIndex = [candidateIndex[index] for index in range(len(candidateIndex)) if datas[candidateIndex[index]]['prachIndex'] == targetPrach] candidateIndex = [candidateIndex[index] for index in range(len(candidateIndex)) if datas[candidateIndex[index]]['arrivalMode'] == targetArrival] candidateIndex = [candidateIndex[index] for index in range(len(candidateIndex)) if datas[candidateIndex[index]]['simulationTime'] == targetSimulation] #print(candidateIndex) return candidateIndex[0] def collectDataCell(filename): preambleSCS, timing, msg1FDM = collectCellMsg1FDM(filename) delta = [] ssbPerRAO = [] tau = [] with open(filename, newline='') as csvfile: rows = csv.DictReader(csvfile) for row in rows: nBeams = row['Total Beams'] delta.append(float(row['Total Channel Capacity'])) ssbPerRAO.append(float(row['SSB per RAO'])) tau.append(int(row['Tau'])) del delta[-1] del delta[0] del tau[-1] delta.insert(0, delta[0]) delta.insert(len(delta), delta[-1]) tau.insert(0, tau[0]) return nBeams, timing, preambleSCS, msg1FDM, ssbPerRAO, delta, tau def plotLantencyCDF(uedatas, saveFolderName=""): print("Plotting Latency CDF...") global figureCount for arrivalMode in ['uniform', 'beta']: for prach in [16, 19, 22, 25, 27]: for simulation in [1]: fig = plt.figure(figureCount) figureCount = figureCount + 1 fig.set_size_inches(9.375, 7.3) #fig.subplots_adjust(top=0.83) ax = plt.subplot(1, 1, 1) plt.xlabel("Latency (ms)", fontsize=label_font_size) plt.ylabel("CDF",fontsize=label_font_size) #plt.suptitle("UE Latency CDF", fontsize=title_font_size, fontweight="bold") for tau in [10, 20, 40, 80, 160]: candidateIndex = findCandidate(tau, str(prach), arrivalMode, str(simulation), uedatas) data = uedatas[candidateIndex] latency = data['latency'] arrival = data['arrival'] subTitle = "RA Subframe Period: {0}ms Simulation Time: {1}s\n".format(str(getSubframePeriod(prach)), str(simulation)) \ + "Arrival Mode: {0}, ".format(arrivalMode) if arrivalMode == "uniform": subTitle = subTitle + "Arrival Rate: {0}".format(arrival) else: subTitle = subTitle + "Total UE: {0}".format(arrival) #ax.set_title(subTitle, fontsize=title_font_size) latency.insert(0, 0) X = np.linspace(min(latency), max(latency), max(latency) - min(latency)) hist, bin_edges = np.histogram(latency, bins=max(latency) - min(latency), density=True) hist = np.cumsum(hist) plt.plot(X, hist, label=r"$\tau\ Threshold$="+str(tau), linewidth=line_width) ax.legend(loc="lower right", fontsize=legend_font_size) for label in (ax.get_xticklabels() + ax.get_yticklabels()): label.set_fontsize(16) filenameFig = "latency_CDF_prach-{0}_simu-{1}_{2}_arrival-{3}".format(prach, simulation, arrivalMode, arrival) plt.axis([0, max(latency), 0, 1.1]) plt.grid(True) if saveFolderName: plt.savefig(saveFolderName + arrivalMode + "/" + filenameFig) plt.close() del X del hist del bin_edges def plotCellMsg1FDM(celldatas, saveFolderName=""): print("Plotting Msg1FDM...") global figureCount newYTick = [fdm*celldatas[0]['preambleLength']*float(celldatas[0]['preambleSCS'])/1000 for fdm in [1, 2, 4, 8]] for arrivalMode in ['uniform', 'beta']: for prach in [16, 19, 22, 25, 27]: for simulation in [1]: fig = plt.figure(figureCount) figureCount = figureCount + 1 fig.set_size_inches(9.375, 7.3) #fig.subplots_adjust(top=0.83) ax = plt.subplot(1, 1, 1) plt.xlabel("Subframe Index", fontsize=label_font_size) plt.ylabel("Preamble Occupied Bandwidth (MHz)", fontsize=label_font_size) #plt.suptitle(r"RA Used Bandwidth For Each $\tau$ Threshold", fontsize=title_font_size, fontweight="bold") plt.yticks(newYTick) i = 0 attr = ['b-^', 'r-o', 'm-D', 'c-s', 'g-p'] maxTiming = 0 for tau in [10, 20, 40, 80, 160]: candidateIndex = findCandidate(tau, str(prach), arrivalMode, str(simulation), celldatas) data = celldatas[candidateIndex] arrival = data['arrival'] subTitle = "RA Subframe Period: {0}ms".format(str(getSubframePeriod(prach))) \ + " Simulation Time: {0}s\n".format(str(simulation)) \ + "Arrival Mode: {0}, ".format(arrivalMode) if arrivalMode == "uniform": subTitle = subTitle + "Arrival Rate: {0}".format(arrival) else: subTitle = subTitle + "Total UE: {0}".format(arrival) #ax.set_title(subTitle, fontsize=title_font_size) preambleBW = [fdm*data['preambleLength']*float(data['preambleSCS'])/1000 for fdm in data['msg1FDM']] maxTiming = max([maxTiming, max(data['timing'])]) if i == 3: ax.plot(data['timing'], preambleBW, attr[i], label=r'$\tau\ Threshold$='+str(tau), linewidth=line_width, markersize=marker_size + 3, fillstyle="none", markeredgewidth=3.0) elif i == 2: ax.plot(data['timing'], preambleBW, attr[i], label=r'$\tau\ Threshold$='+str(tau), linewidth=line_width, markersize=marker_size + 2, fillstyle="none", markeredgewidth=4.0) elif i == 1: ax.plot(data['timing'], preambleBW, attr[i], label=r'$\tau\ Threshold$='+str(tau), linewidth=line_width, markersize=marker_size + 2) elif i == 0: ax.plot(data['timing'], preambleBW, attr[i], label=r'$\tau\ Threshold$='+str(tau), linewidth=line_width, markersize=marker_size + 9) else: ax.plot(data['timing'], preambleBW, attr[i], label=r'$\tau\ Threshold$='+str(tau), linewidth=line_width, markersize=marker_size) i = i + 1 for label in (ax.get_xticklabels() + ax.get_yticklabels()): label.set_fontsize(16) filenameFig = "RA_Used_BW_prach-{0}_simu-{1}_{2}_arrival-{3}".format(prach, simulation, arrivalMode, arrival) xtick = math.ceil(maxTiming / 160) xtick = [(x * 160) for x in range(xtick + 1)] ax.legend(loc="upper left", fontsize=legend_font_size, ncol=2) ax.set_xlim(0, maxTiming) ax.set_ylim(0, math.ceil((max(newYTick) * 2) / 10) * 10) plt.xticks(xtick) plt.grid(True) if saveFolderName: plt.savefig(saveFolderName + arrivalMode + "/" + filenameFig) plt.close() def plotCellSSBPerRAO(celldatas, saveFolderName=""): print("Plotting SSB per RAO...") global figureCount newYTick = [0.125, 0.25, 0.5, 1, 2, 4, 8, 16] for arrivalMode in ['uniform', 'beta']: for prach in [16, 19, 22, 25, 27]: for simulation in [1]: fig = plt.figure(figureCount) figureCount = figureCount + 1 fig.set_size_inches(9.375, 7.3) #fig.subplots_adjust(top=0.83) ax = plt.subplot(1, 1, 1) plt.xlabel("Subframe Index", fontsize=label_font_size) plt.ylabel(r"SSB Per RAO $S_{RAO}$", fontsize=label_font_size) #plt.suptitle(r"Number of SSB Per RAO $S_{RAO}$ For Each $\tau$ Threshold", fontsize=title_font_size, fontweight="bold") plt.yticks(newYTick) i = 0 attr = ['b-^', 'r-o', 'm-D', 'c-s', 'g-v'] maxTiming = 0 for tau in [10, 20, 40, 80, 160]: candidateIndex = findCandidate(tau, str(prach), arrivalMode, str(simulation), celldatas) data = celldatas[candidateIndex] arrival = data['arrival'] subTitle = "RA SubframePeriod: {0}ms".format(str(getSubframePeriod(prach))) \ + " Simulation Time: {0}s\n".format(str(simulation)) \ + "Arrival Mode: {0}, ".format(arrivalMode) if arrivalMode == "uniform": subTitle = subTitle + "Arrival Rate: {0}".format(arrival) else: subTitle = subTitle + "Total UE: {0}".format(arrival) #ax.set_title(subTitle, fontsize=title_font_size) maxTiming = max([maxTiming, max(data['timing'])]) if i == 4: ax.plot(data['timing'], data['ssbPerRAO'], attr[i], label=r'$\tau\ Threshold$='+str(tau), linewidth=line_width, markersize=marker_size + 9, fillstyle="none", markeredgewidth=3.0) elif i == 2: ax.plot(data['timing'], data['ssbPerRAO'], attr[i], label=r'$\tau\ Threshold$='+str(tau), linewidth=line_width, markersize=marker_size + 3, fillstyle="none", markeredgewidth=3.0) elif i == 1: ax.plot(data['timing'], data['ssbPerRAO'], attr[i], label=r'$\tau\ Threshold$='+str(tau), linewidth=line_width, markersize=marker_size + 5) elif i == 0: ax.plot(data['timing'], data['ssbPerRAO'], attr[i], label=r'$\tau\ Threshold$='+str(tau), linewidth=line_width, markersize=marker_size + 7) else: ax.plot(data['timing'], data['ssbPerRAO'], attr[i], label=r'$\tau\ Threshold$='+str(tau), linewidth=line_width, markersize=marker_size) i = i + 1 for label in (ax.get_xticklabels() + ax.get_yticklabels()): label.set_fontsize(16) filenameFig = "S_RAO_prach-{0}_simu-{1}_{2}_arrival-{3}".format(prach, simulation, arrivalMode, arrival) xtick = math.ceil(maxTiming / 160) xtick = [(x * 160) for x in range(xtick + 1)] ax.legend(loc="upper left", fontsize=legend_font_size) ax.set_xlim(0, maxTiming) ax.set_ylim(newYTick[0], newYTick[-1]) ax.set_yscale('log', basey=2) plt.xticks(xtick) plt.grid(True) if saveFolderName: plt.savefig(saveFolderName + arrivalMode + "/" + filenameFig) plt.close() def plotCellDelta(celldatas, saveFolderName=""): print("Plotting Channel Capacity...") global figureCount for arrivalMode in ['uniform', 'beta']: for prach in [16, 19, 22, 25, 27]: for simulation in [1]: fig = plt.figure(figureCount) figureCount = figureCount + 1 fig.set_size_inches(9.375, 7.3) #fig.subplots_adjust(top=0.83) ax = plt.subplot(1, 1, 1) plt.xlabel("Subframe Index", fontsize=label_font_size) plt.ylabel(r"Channel Capacity $\delta$", fontsize=label_font_size) #plt.suptitle(r"Channel Capacity $\delta$ For Each $\tau$ Threshold", fontsize=title_font_size, fontweight="bold") i = 0 attr = ['b-s', 'r-o', 'm-D', 'c-^', 'g-v'] maxTiming = 0 maxDelta = 0 for tau in [10, 20, 40, 80, 160]: candidateIndex = findCandidate(tau, str(prach), arrivalMode, str(simulation), celldatas) data = celldatas[candidateIndex] arrival = data['arrival'] subTitle = "RA Subframe Period: {0}ms".format(str(getSubframePeriod(prach))) \ + " Simulation Time: {0}s\n".format(str(simulation)) \ + "Arrival Mode: {0}, ".format(arrivalMode) if arrivalMode == "uniform": subTitle = subTitle + "Arrival Rate: {0}".format(arrival) else: subTitle = subTitle + "Total UE: {0}".format(arrival) #ax.set_title(subTitle, fontsize=title_font_size) maxTiming = max([maxTiming, max(data['timing'])]) maxDelta = max([maxDelta, max(data['delta'])]) if i == 4: ax.plot(data['timing'], data['delta'], attr[i], label=r'$\tau\ Threshold$='+str(tau), linewidth=line_width, markersize=marker_size + 9, fillstyle="none", markeredgewidth=3.0) elif i == 0: ax.plot(data['timing'], data['delta'], attr[i], label=r'$\tau\ Threshold$='+str(tau), linewidth=line_width, markersize=marker_size + 7) elif i == 1: ax.plot(data['timing'], data['delta'], attr[i], label=r'$\tau\ Threshold$='+str(tau), linewidth=line_width, markersize=marker_size + 5) elif i == 2: ax.plot(data['timing'], data['delta'], attr[i], label=r'$\tau\ Threshold$='+str(tau), linewidth=line_width, markersize=marker_size + 9, fillstyle="none", markeredgewidth=3.0) elif i == 3: ax.plot(data['timing'], data['delta'], attr[i], label=r'$\tau\ Threshold$='+str(tau), linewidth=line_width, markersize=marker_size + 7) else: ax.plot(data['timing'], data['delta'], attr[i], label=r'$\tau\ Threshold$='+str(tau), linewidth=line_width, markersize=marker_size) i = i + 1 for label in (ax.get_xticklabels() + ax.get_yticklabels()): label.set_fontsize(16) filenameFig = "Delta_prach-{0}_simu-{1}_{2}_arrival-{3}".format(prach, simulation, arrivalMode, arrival) xtick = math.ceil(maxTiming / 160) xtick = [(x * 160) for x in range(xtick + 1)] ax.legend(loc="upper left", fontsize=legend_font_size, ncol=2) ax.set_xlim(0, maxTiming) exponential = math.floor(log(maxDelta, 10)) coef = maxDelta / pow(10, exponential) maxDelta = (coef * 2) * pow(10, exponential) ax.set_ylim(0, maxDelta) plt.xticks(xtick) plt.grid(True) if saveFolderName: plt.savefig(saveFolderName + arrivalMode + "/" + filenameFig) plt.close() def plotCellTau(celldatas, saveFolderName=""): print("Plotting Tau...") global figureCount for arrivalMode in ['uniform', 'beta']: for prach in [16, 19, 22, 25, 27]: for simulation in [1]: fig = plt.figure(figureCount) figureCount = figureCount + 1 fig.set_size_inches(9.375, 7.3) #fig.subplots_adjust(top=0.83) ax = plt.subplot(1, 1, 1) plt.xlabel("Subframe Index", fontsize=label_font_size) plt.ylabel(r"RA Attempt Period $\tau$", fontsize=label_font_size) #plt.suptitle(r"RA Attempt Period $\tau$ For Each $\tau$ Threshold", fontsize=title_font_size, fontweight="bold") i = 0 attr = ['b-s', 'r-o', 'm-D', 'c-^', 'g-v'] maxTiming = 0 maxTau = 0 for tau in [10, 20, 40, 80, 160]: candidateIndex = findCandidate(tau, str(prach), arrivalMode, str(simulation), celldatas) data = celldatas[candidateIndex] arrival = data['arrival'] subTitle = "RA Subframe Period: {0}".format(str(getSubframePeriod(prach))) \ + " Simulation Time: {0}\n".format(str(simulation)) \ + "Arrival Mode: {0}, ".format(arrivalMode) if arrivalMode == "uniform": subTitle = subTitle + "Arrival Rate: {0}".format(arrival) else: subTitle = subTitle + "Total UE: {0}".format(arrival) #ax.set_title(subTitle, fontsize=title_font_size) maxTiming = max([maxTiming, max(data['timing'])]) maxTau = max([maxTau, max(data['RA attempt period'])]) if i == 0: ax.plot(data['timing'], data['RA attempt period'], attr[i], label=r'$\tau\ Threshold$='+str(tau), linewidth=line_width, markersize=marker_size + 7) elif i == 2: ax.plot(data['timing'], data['RA attempt period'], attr[i], label=r'$\tau\ Threshold$='+str(tau), linewidth=line_width, markersize=marker_size + 7, fillstyle="none", markeredgewidth=3.0) elif i == 1: ax.plot(data['timing'], data['RA attempt period'], attr[i], label=r'$\tau\ Threshold$='+str(tau), linewidth=line_width, markersize=marker_size + 5) elif i == 3: ax.plot(data['timing'], data['RA attempt period'], attr[i], label=r'$\tau\ Threshold$='+str(tau), linewidth=line_width, markersize=marker_size + 3) else: ax.plot(data['timing'], data['RA attempt period'], attr[i], label=r'$\tau\ Threshold$='+str(tau), linewidth=line_width, markersize=marker_size) i = i + 1 for label in (ax.get_xticklabels() + ax.get_yticklabels()): label.set_fontsize(16) filenameFig = "RA_attempt_periodprach-{0}_simu-{1}_{2}_arrival-{3}".format(prach, simulation, arrivalMode, arrival) xtick = math.ceil(maxTiming / 160) xtick = [(x * 160) for x in range(xtick + 1)] ax.legend(loc="upper left", fontsize=legend_font_size, ncol=2) ax.set_xlim(0, maxTiming) ax.set_ylim(0, 220) #exponential = math.floor(log(maxTau, 10)) #coef = maxTau / pow(10, exponential) #maxTau = (coef + 1) * pow(10, exponential) #ax.set_ylim(0, maxTau) plt.grid(True) if saveFolderName: plt.savefig(saveFolderName + arrivalMode + "/" + filenameFig) plt.close() print("Collecting Datas...") resultSourceFolder = "./candidateResult/" folderNameUniform = "uniform/" folderNameBeta = "beta/" ueFile = "UE.csv" cellFile = "Cell.csv" if not os.path.exists(resultSourceFolder + folderNameUniform): os.makedirs(resultSourceFolder + folderNameUniform) if not os.path.exists(resultSourceFolder + folderNameBeta): os.makedirs(resultSourceFolder + folderNameBeta) folderTau = [name for name in os.listdir(resultSourceFolder)] folderTau = [name for name in folderTau if "png" not in name] folderTau.remove('beta') folderTau.remove('uniform') folderTau = [int(name) for name in folderTau] folderTau.sort() #print(folderTau) folderName = {} prachIndex = {} simulationTime = {} arrivalMode = {} arrival = {} for i in folderTau: folderName[i] = [name for name in os.listdir(resultSourceFolder + str(i))] prachIndex[i] = [name.split("prach-")[1] for name in folderName[i]] prachIndex[i] = [name.split("_")[0] for name in prachIndex[i]] simulationTime[i] = [name.split("simu-")[1] for name in folderName[i]] simulationTime[i] = [name.split("_")[0] for name in simulationTime[i]] arrivalMode[i] = [name.split("_")[4] for name in folderName[i]] arrival[i] = [name.split("_")[5] for name in folderName[i]] arrival[i] = [name.split("-")[1] for name in arrival[i]] #print(folderName) #print(prachIndex) #print(simulationTime) #print(arrivalMode) #print(arrival) tempPrach = prachIndex[10].copy() tempArrivalMode = arrivalMode[10].copy() uedatas = [] celldatas = [] while(len(tempPrach) > 0): maxIndex = tempPrach.index(max(tempPrach)) for tau in folderName.keys(): candidateIndex = findCandidateFolder(tempPrach[maxIndex], tempArrivalMode[maxIndex], folderName[tau]) # print(resultSourceFolder + str(tau) + "/" + folderName[tau][candidateIndex]) ue_filename = resultSourceFolder + str(tau) + "/" + folderName[tau][candidateIndex] + "/" + ueFile cell_filename = resultSourceFolder + str(tau) + "/" + folderName[tau][candidateIndex] + "/" + cellFile ### get ue data ### latency = [x['latency'] for x in collectDataUE(ue_filename).values()] uedata = {'tau':tau, 'latency':latency, 'prachIndex':prachIndex[tau][candidateIndex], 'simulationTime':simulationTime[tau][candidateIndex], 'arrivalMode':arrivalMode[tau][candidateIndex], 'arrival':arrival[tau][candidateIndex]} uedatas.append(uedata) ### get ue data ### ### get cell data ### nBeams, timing, preambleSCS, msg1FDM, ssbPerRAO, delta, raAttemptPeriod = collectDataCell(cell_filename) celldata = {'tau':tau, 'prachIndex': prachIndex[tau][candidateIndex], 'simulationTime':simulationTime[tau][candidateIndex], 'arrivalMode':arrivalMode[tau][candidateIndex], 'arrival':arrival[tau][candidateIndex], 'nBeams':nBeams, 'timing':timing, 'preambleSCS':preambleSCS, 'preambleLength':getPreambleLength(float(preambleSCS)), 'msg1FDM':msg1FDM, 'ssbPerRAO':ssbPerRAO, 'delta':delta, 'RA attempt period':raAttemptPeriod} celldatas.append(celldata) ### get cell data ### del tempPrach[maxIndex] del tempArrivalMode[maxIndex] plotLantencyCDF(uedatas, resultSourceFolder) plotCellMsg1FDM(celldatas, resultSourceFolder) plotCellSSBPerRAO(celldatas, resultSourceFolder) plotCellDelta(celldatas, resultSourceFolder) plotCellTau(celldatas, resultSourceFolder) print("DONE!") del uedatas del celldatas del folderName del prachIndex del simulationTime del arrivalMode del arrival <file_sep>/main/src/PreambleFormat.h #ifndef PREAMBLE_FORMAT #define PREAMBLE_FORMAT #include "includefile.h" enum Format{ Format_0, Format_1, Format_2, Format_3, Format_A1, Format_A2, Format_A3, Format_B1, Format_B2, Format_B3, Format_B4, Format_C0, Format_C2 }; class PreambleFormat{ private: Format format; }; #endif <file_sep>/main/src/IPRACHConfig.h #ifndef IPRACH_CONFIGURATION #define IPRACH_CONFIGURATION #include "includefile.h" class IPRACHConfig{ public: virtual int getPrachConfigIndex() = 0; virtual int getX() = 0; virtual int getY() = 0; virtual int getPrachConfigPeriod() = 0; virtual int getNumberofPRACHSlotinSubframe() = 0; virtual int getNumberofTimeDomainRAOPerPrachSlot() = 0; virtual int getNumberofTimeDomainRAO() = 0; virtual int getNumberofRASubframe() = 0; virtual vector<int>& getRASubframe() = 0; }; #endif <file_sep>/main/src/MonitorRAFunction.h #ifndef MONITOR_RA_FUNCTION #define MONITOR_RA_FUNCTION #include "AvailiableRAO.h" #include "IPRACHConfig.h" #include "include_log.h" #include <cmath> class MonitorRAFunction{ private: unsigned long successUEs; unsigned long failedUEs; vector<unsigned long> history; vector<unsigned long> historySlot; int tau; int raCount; int nSSB; //double coefThreshold; double ssbPerRAO; double delta; double totalDelta; double estimateUEs; const double sRAO[8] = {0.125, 0.25, 0.5, 1.0, 2.0, 4.0, 8.0, 16.0}; const int fRAO[4] = {1, 2, 4, 8}; const double initSSBPerRAO = 1; const int initMsg1FDM = 1; const int recordTimes = 5; // max record times for estimate use AvailiableRAO *availiableRAO; IPRACHConfig *prachConfig; int getTau(const int RAConfigPeriod, const int totalNeedRAO, const int totalRAOPerSubframe, const int nRASubframe); int getNewMsg1FDM(const double newSSBPerRAO); int getNewMsg1FDMver2(double *newSSBPerRAO); double calculateDelta(const int nPreambles, const double ssbPerRAO); double calculateNewSSBPerRAO(); double calculateNewSSBPerRAO(const double nPreambles, const double nSSB, const double estimateUEs, const double tRAO, const double fRAO, const double totalNeedRAO); unsigned long estimateNextUEsBySIBPeriod(); unsigned long estimateNextUEsBySlot(); public: MonitorRAFunction(AvailiableRAO *availiableRAO, IPRACHConfig *prachConfig); void recordUEsCondition(const int success, const int failed); void updateRAOs(); void restore2Initial(); int getTau(); unsigned long getSuccessUEs(); unsigned long getFailedUEs(); double getEstimateUEs(); double getTotalDelta(); }; #endif <file_sep>/main/src/random_access.h #ifndef RANDOM_ACCESS #define RANDOM_ACCESS #include "includefile.h" struct RAR{ int raoIndex; int preambleIndex; int uplinkResourceIndex; int tc_rnti; }; struct Msg3{ int uplinkResourceIndex; int tc_rnti; unsigned long ueIndex; int power; }; int binarySearchPreamble(const std::vector<RAR*>& subframeRars, const int raoLeft, const int raoRight, const int raoFoundIndex, const int preambleIndex); int binarySearchRAO(const std::vector<RAR*>& subframeRars, int* raoLeft, int* raoRight, const int raoIndex); int binarySeachMsg3(const std::vector<Msg3*>& msg3s, const int tc_rnti); int searchRAR(const vector<RAR*>& subframeRars, const int raoIndex, const int preambleIndex); int searchRAR(const std::vector<RAR*>& subframeRars, RAR &rar); int searchMsg3(const std::vector<Msg3*>& msg3s, int tc_rnti); int searchMsg3(const std::vector<Msg3*>& msg3s, Msg3& msg3); #endif <file_sep>/main/src/PRACHConfig.h #ifndef PRACH_CONFIGURATION #define PRACH_CONFIGURATION #include "IPRACHConfig.h" #include "include_log.h" class PRACHConfig : public IPRACHConfig{ protected: int prachConfigIndex; int nPRACHSlot; int nTimeDomainRAOPerPrachSlot; int prachConfigPeriod; int x; int y; vector<int> raSubframes; public: PRACHConfig(int prachConfigIndex); void setPrachConfigIndex(int prachConfigIndex); void setNumberofPrachSlot(int nPRACHSlot); void setNumberofTimeDomainRAO(int nTimeDomainRAO); int getPrachConfigIndex(); int getX(); int getY(); int getPrachConfigPeriod(); vector<int>& getRASubframe(); int getNumberofPRACHSlotinSubframe(); int getNumberofTimeDomainRAOPerPrachSlot(); int getNumberofTimeDomainRAO(); int getNumberofRASubframe(); virtual void configRA() = 0; virtual ~PRACHConfig(); }; #endif <file_sep>/main/src/EraseRect.cpp #include "EraseRect.h" EraseRect::EraseRect() : x(0), y(0){ } EraseRect::~EraseRect(){ } void EraseRect::setXY(int x, int y){ this->x = x - size / 2; this->y = y - size / 2; } bool EraseRect::isInside(int objectX, int objectY){ if((x <= objectX && y <= objectY) && ((x + size) >= objectX && (y + size) >= objectY)) return true; return false; } void EraseRect::draw(QPainter &painter){ painter.setBrush(QBrush(QColor(255, 255, 255, 255), Qt::SolidPattern)); painter.drawRect(x, y, size, size); } <file_sep>/main/src/Cell.cpp #include "Cell.h" // Constructor // gNB base class // x: gNB x position // y: gNB y position // cellType: gNB CellType, Macro or Femto //FIXME maybe reduntant Cell::Cell(int x, int y, int cellIndex, int nBeams, celltype::CellType cellType, int prachConfigIndex, int nPreambles, int cellBW, int ssbSCS, double preambleSCS) : x(x), y(y), cellIndex(cellIndex), nBeams(nBeams), cellPixelSize(10), subframeIndex(0), frameIndex(0), raResponseWindow(1), nPreambles(nPreambles), cellBW(cellBW), ssbSCS(ssbSCS), preambleSCS(preambleSCS), cellType(cellType){ double ssbperRAO = 1; int msg1FDM = 1; //int nPreambles = 64; SPDLOG_TRACE("cell {0} nPreambles: {1}", this->cellIndex, this->nPreambles); SPDLOG_INFO("cell {0} cell BW: {1}", this->cellIndex, this->cellBW); SPDLOG_INFO("cell{0} preamble SCS: {1}", this->cellIndex, this->preambleSCS); estimateUEs = 0; prachConfig = new PRACHConfigFR1(prachConfigIndex); prachConfig->configRA(); availiableRAO = new AvailiableRAO(nBeams, ssbperRAO, msg1FDM, nPreambles, 160, prachConfig); availiableRAO->updateStartandEndRAOofSubframe(frameIndex, subframeIndex); rars = vector<vector<RAR*>>(10); mRA = new MonitorRAFunction(availiableRAO, prachConfig); successUEs = 0; failedUEs = 0; startBeamIndex = -1; endBeamIndex = -1; updateSSBStartAndEndIndex(); } // Set gNB x position void Cell::setX(int x){ this->x = x; } // Set gNB y position void Cell::setY(int y){ this->y = y; } // set gNB number of support beams // nBeams: number of support beams void Cell::setnBeams(int nBeams){ this->nBeams = nBeams; } // Set gNB cell support distance(associate with cell size) void Cell::setCellSupportDistance(int supportDistance){ this->cellSupportDistance = supportDistance; } // calculate beam start angle based on first mouse click coordinate and // second mouse click coordinate // diffX: the difference of x1 and x2 // diffY: the difference of y1 and y2 void Cell::setBeamStartAngle(int diffX, int diffY){ beamStartAngle = atan2(diffY, diffX) * 180 / M_PI; //printf("%f\n", beamStartAngle); } // set cell index // cellIndex: cell index void Cell::setCellIndex(int cellIndex){ this->cellIndex = cellIndex; } // detect ue is this cell's area // if ue is in this cell, add this ue to this cell's ue vector // ue: the ue to be detected void Cell::detectUE(UE *ue){ //printf("start:%d\tend:%d\n", this->startAngle, this->endAngle); // detect ue is in cell span angle area if(checkUEisExist(ue)) return; double distance = calculateDistance(ue->getX(), ue->getY(), getX(), getY()); SPDLOG_TRACE("cell {0} startAngle: {1}, spanAngle: {2}", cellIndex, startAngle, cellAngle); if(isInArea(ue->getX(), ue->getY(), getX(), getY(), startAngle, cellAngle, cellSupportDistance / 2)){ Beam *beam; for(unsigned int i = 0;i < beams.size();i++){ beam = beams.at(i); beam->detectUE(ue, ((double)(this->cellSupportDistance / 2)) - distance); } ues.push_back(ue); SPDLOG_TRACE("UE {0} is in cell {1} range", ue->getID(), cellIndex); } } // check ue is in this cell // ue: the UE need to be checked bool Cell::checkUEisExist(UE *ue){ UE *temp; for(unsigned int i = 0;i < ues.size();i++){ temp = ues[i]; if(temp->getID() == ue->getID()){ SPDLOG_TRACE("UE {0} already be added to Cell {1}", temp->getID(), cellIndex); return true; } } return false; } // check beam index in current subframe, frame is allowed to // transmit braodcast message // beamIndex: beam index // return: true for allowed bool Cell::isBeamAllowedPBCH(const int beamIndex){ SPDLOG_TRACE("start beam index: {0}", startBeamIndex); SPDLOG_TRACE("end beam index: {0}", endBeamIndex); SPDLOG_TRACE("beam index: {0}", beamIndex); if(startBeamIndex == -1 && endBeamIndex == -1){ SPDLOG_TRACE("current frame {0} subframe {1} is not for PBCH", frameIndex, subframeIndex); return false; } else if(startBeamIndex <= beamIndex && beamIndex < endBeamIndex){ return true; } SPDLOG_TRACE("current frame {0} subframe {1} is not for beam {2} PBCH", frameIndex, subframeIndex, beamIndex); return false; } // update start and end ssb index that is allowed to transmit PBCH void Cell::updateSSBStartAndEndIndex(){ if(frameIndex % 2 == 1 || (frameIndex % 2 == 0 && subframeIndex > 4)){ SPDLOG_TRACE("next frame {0} subframe {1} is not for PBCH", frameIndex, subframeIndex); startBeamIndex = -1; endBeamIndex = -1; } switch(ssbSCS){ case 15: startBeamIndex = subframeIndex * 2; endBeamIndex = (subframeIndex + 1) * 2; if(((nBeams == 4) && (subframeIndex > 1)) || subframeIndex > 3){ startBeamIndex = -1; endBeamIndex = -1; } break; case 30: startBeamIndex = subframeIndex * 4; endBeamIndex = (subframeIndex + 1) * 4; if((nBeams == 4 && subframeIndex > 0) || subframeIndex > 1){ startBeamIndex = -1; endBeamIndex = -1; } break; case 120: startBeamIndex = subframeIndex * 16; endBeamIndex = (subframeIndex + 1) * 16; if(subframeIndex > 1){ endBeamIndex -= 4; } if(subframeIndex > 2){ startBeamIndex -= 4; } if(subframeIndex == 4){ startBeamIndex = 56; endBeamIndex = 63; } break; case 240: startBeamIndex = subframeIndex * 32; endBeamIndex = (subframeIndex + 1) * 32; if(subframeIndex > 1){ startBeamIndex = -1; endBeamIndex = -1; } break; default: SPDLOG_WARN("ssb SCS not support now"); startBeamIndex = -1; endBeamIndex = -1; } } // broadcasting cell's SI void Cell::broadcastSI(){ SPDLOG_TRACE("Broadcast cell index {0} system information", cellIndex); UE *ue; for(unsigned int i = 0;i < ues.size();i++){ ue = ues.at(i); if(isBeamAllowedPBCH(ue->getBeamIndex()) && ue->receiveSI(this)){ i--; } } //ue->receiveSI(this); } // deregister a ue // if a ue have another cell better than this one // ue call this function for removing itself from this cell // since when cell detect a ue is in this cell, // cell will add the UE automatically // as a result, in order to prevent ue receving other cell's // RAR or CR which may cause error // ue need to deregister the cell which it should not listen // ue: the UE need to be deregisted void Cell::deregisterCell(UE *ue){ for(auto it = ues.begin();it != ues.end();it++){ if((*it)->getID() == ue->getID()){ SPDLOG_TRACE("UE: {0} removing from cell: {1}", (*it)->getID(), cellIndex); ues.erase(it); break; } } } // update the subframe // if subframe is add to 10 // mod subframe by 10 and add frame index // also, update availiableRAO's start and end RAO of subframe void Cell::updateSubframe(){ ++subframeIndex; if(subframeIndex == 10){ frameIndex++; subframeIndex %= 10; } if((frameIndex * 10 + subframeIndex) % 160 == 0 && !TESTING){ SPDLOG_INFO("next subframe can modify rao configuration"); SPDLOG_TRACE("next frame: {0}, next subframe: {1}", frameIndex, subframeIndex); successUEs = mRA->getSuccessUEs(); failedUEs = mRA->getFailedUEs(); mRA->updateRAOs(); estimateUEs = mRA->getEstimateUEs(); } availiableRAO->updateStartandEndRAOofSubframe(frameIndex, subframeIndex); updateSSBStartAndEndIndex(); } // reset the subframe and frame nubmer void Cell::resetFrame(){ this->frameIndex = 0; this->subframeIndex = 0; } // set msg1-fdm and update association frame and // start and end RAO of subframe // msg1FDM: the parameter msg1-FDM in TS 38.331 void Cell::setMsg1FDM(int msg1FDM){ availiableRAO->setMsg1FDM(msg1FDM); availiableRAO->updateAssociationFrame(); availiableRAO->updateStartandEndRAOofSubframe(frameIndex, subframeIndex); } // set ssb-perRAO and update association frame and // start and end RAO of subframe // ssbPerRAO: corresponding to TS 38.331 ssb-perRACH-Occasion void Cell::setSSBPerRAO(double ssbPerRAO){ availiableRAO->setSSBPerRAO(ssbPerRAO); availiableRAO->updateAssociationFrame(); availiableRAO->updateStartandEndRAOofSubframe(frameIndex, subframeIndex); } // set prach-ConfigurationIndex and update RA parameters and // update start and end RAO of subframe // prachConfigIndex: corresponding to TS 38.331 prach-ConfigurationIndex void Cell::setPrachConfigIndex(int prachConfigIndex){ prachConfig->setPrachConfigIndex(prachConfigIndex); prachConfig->configRA(); availiableRAO->updateStartandEndRAOofSubframe(frameIndex, subframeIndex); } // set raResponseWindow // raResponseWindow: corresponding to TS 38.331 ra-ResponseWindow void Cell::setRaResponseWindow(const int raResponseWindow){ this->raResponseWindow = raResponseWindow; } // receive preamble // ue will send preamble in a rao // if cell receive a preamble, it store the preamble index and // rao index in (subframe index + rareponsewindow)'s rar // waiting to send in (subframe index + rareponsewindow) // the RARs will store in ascending order firsy by rao index then // preamble index // raoIndex: ue send ra preamble's rao index // preambleIndex: ue send preamble index void Cell::receivePreamble(const int raoIndex, const int preambleIndex){ SPDLOG_TRACE("cell {0} receiving preamble", cellIndex); int respondSubframe = (subframeIndex + raResponseWindow) % 10; vector<RAR*>& subframeRars = rars[respondSubframe]; RAR *rar = new RAR; rar->raoIndex = raoIndex; rar->preambleIndex = preambleIndex; rar->uplinkResourceIndex = subframeRars.size() + 1; rar->tc_rnti = subframeRars.size() + 1; SPDLOG_TRACE("size: {0}", subframeRars.size()); SPDLOG_TRACE("rao index: {0}, preamble index: {1}", rar->raoIndex, rar->preambleIndex); int insertIndex = searchRAR(subframeRars, *rar); SPDLOG_TRACE("insert index: {0}", insertIndex); // if searched index is the end of stored rar // push rar directly in end of subframeRars if(subframeRars.size() == insertIndex) subframeRars.push_back(rar); else if(subframeRars.size() > 0 && subframeRars[insertIndex]->raoIndex == rar->raoIndex && subframeRars[insertIndex]->preambleIndex == rar->preambleIndex){ // the corresponding rar is already exist in stored Rars SPDLOG_TRACE("rao: {0}, preamble: {1} already exist in RAR", rar->raoIndex, rar->preambleIndex); delete rar; } else{ // otherwise, store the new RAR in searched index subframeRars.insert(subframeRars.begin() + insertIndex, rar); } SPDLOG_TRACE("cell {0} receive complete", cellIndex); } // transmit RAR if cell has RAR stored void Cell::transmitRAR(){ if(!hasRAR()) return; SPDLOG_TRACE("Cell: {0} transmitting RARs", cellIndex); vector<RAR*>& subframeRar = rars[subframeIndex]; for(auto i = subframeRar.begin();i != subframeRar.end();i++){ SPDLOG_TRACE("rao: {0}\tpreamble: {1}", (*i)->raoIndex, (*i)->preambleIndex); } UE *ue; SPDLOG_TRACE("rar size: {0}" ,subframeRar.size()); for(decltype(ues.size()) i = 0;i < ues.size();i++){ ue = ues.at(i); if(ue->isBindCell()){ SPDLOG_TRACE("Cell: {0} transmitting RAR to UE :{1}", cellIndex, ue->getID()); ue->receiveRAR(subframeRar, cellIndex); } } // delete each stored and transmitted RAR for(decltype(subframeRar.size()) i = 0;i < subframeRar.size();i++){ delete subframeRar[i]; } subframeRar.clear(); SPDLOG_TRACE("RARs transmit complete"); } // receive Msg3 transmitted by UE // msg3: msg3 forged and transmitted by UE void Cell::receiveMsg3(Msg3& msg3){ int insertIndex = searchMsg3(msg3s, msg3); if(insertIndex == msg3s.size()) msg3s.push_back(&msg3); else if(msg3s.size() > 0 && msg3s[insertIndex]->tc_rnti == msg3.tc_rnti){ SPDLOG_TRACE("tc_rnti: {0}, already exist in RAR", msg3.tc_rnti); if(msg3s[insertIndex]->power < msg3.power){ SPDLOG_TRACE("new msg3 power is bigger than older one"); SPDLOG_TRACE("old msg3 ue index: {0}", msg3s[insertIndex]->ueIndex); SPDLOG_TRACE("old msg3 power: {0}", msg3s[insertIndex]->power); SPDLOG_TRACE("new msg3 ue index: {0}", msg3.ueIndex); SPDLOG_TRACE("new msg3 power: {0}", msg3.power); msg3s[insertIndex]->ueIndex = msg3.ueIndex; msg3s[insertIndex]->power = msg3.power; } } else{ msg3s.insert(msg3s.begin() + insertIndex, &msg3); } } // transmit CR if has stored CR // CR is alternatively the Msg3 transmitted by UE void Cell::transmitCR(){ if(!msg3s.size()) return; SPDLOG_TRACE("transmitting contention resolution"); UE *ue; int countSuccess = 0; int countFailed = 0; for(decltype(ues.size()) i = 0;i < ues.size();i++){ ue = ues.at(i); if(ue->isBindCell() && ue->receiveCR(msg3s, cellIndex)){ if(ue->isRASuccess()){ SPDLOG_TRACE("removing UE id: {0} from cell index: {1}", ue->getID(), cellIndex); ues.erase(ues.begin() + i); i--; countSuccess++; } else{ countFailed++; } } } mRA->recordUEsCondition(countSuccess, countFailed); // delete the stored msg3 for(decltype(msg3s.size()) i = 0;i < msg3s.size();i++){ delete msg3s[i]; } msg3s.clear(); } // restore monitor ra function to initial condition void Cell::restoreMonitorRA2Initial(){ mRA->restore2Initial(); successUEs = 0; failedUEs = 0; estimateUEs = 0; } // get cell support distance int Cell::getCellSupportDistance(){ return this->cellSupportDistance; } // Set gNB cellType void Cell::setCellType(celltype::CellType cellType){ this->cellType = cellType; } // Get gNB x position int Cell::getX(){ return this->x; } // Get gNB y position int Cell::getY(){ return this->y; } // get gNB number of support beams // return number of support beams int Cell::getnBeams(){ return this->nBeams; } // get cell index // return: cell index int Cell::getCellIndex(){ return this->cellIndex; } // get subframe index // return: subframe index int Cell::getSubframeIndex(){ return this->subframeIndex; } // get frame index // return: frame index int Cell::getFrameIndex(){ return this->frameIndex; } // get msg1-FDM // return: msg1-FDM int Cell::getMsg1FDM(){ return availiableRAO->getMsg1FDM(); } // get ra-ResponseWindow // return: ra-ResponseWindow int Cell::getRaResponseWindow(){ return raResponseWindow; } // get prach-ConfigurationIndex // return: prach-ConfigurationIndex int Cell::getPrachConfigIndex(){ return prachConfig->getPrachConfigIndex(); } // get RA attempt period // return: tau int Cell::getTau(){ return mRA->getTau(); } // get cell start angle // return: cell start angle double Cell::getBeamStartAngle(){ return this->beamStartAngle; } // get SSBPerRAO // return: ssb-perRACH-Occasion double Cell::getSSBPerRAO(){ return availiableRAO->getSSBPerRAO(); } // get cell cover angle // return: cell cover angle double Cell::getCellSpanAngle(){ return cellAngle; } // get cell preamble SCS // return cell's preamble SCS double Cell::getPreambleSCS(){ return preambleSCS; } // get current channel capacity // return: current channel capacity double Cell::getTotalChannelCapacity(){ return mRA->getTotalDelta(); } // get success ues count record from monitor ra function // return: success ues count unsigned long Cell::getSuccessUEs(){ if(ues.size() == 0 && (frameIndex * 10 + subframeIndex) % 16 != 0) return mRA->getSuccessUEs(); return successUEs; } // get failed ues count record from monitor ra function // return: failed ues count unsigned long Cell::getFailedUEs(){ if(ues.size() == 0 && (frameIndex * 10 + subframeIndex) % 16 != 0) return mRA->getFailedUEs(); return failedUEs; } // get estimate ues from monitor ra function // return: estimate ues count double Cell::getEstimateUEs(){ return estimateUEs; } // is this cell has stored RAR // return: true if has stored RAR, otherwise is false bool Cell::hasRAR(){ if(rars[subframeIndex].size()) return true; return false; } // Get gNB celltype celltype::CellType Cell::getCellType(){ return this->cellType; } // get IPRACHConfig, typically used by UE // kind of SI // return: IPRACHConfig IPRACHConfig* Cell::getPRACHConfig(){ return prachConfig; } // get IAvailiableRAO, typically used by UE // kind of SI // return: IAvailiableRAO IAvailiableRAO* Cell::getAvailiableRAO(){ return availiableRAO; } // destructor Cell::~Cell(){ SPDLOG_TRACE("cell destructor"); delete mRA; delete prachConfig; delete availiableRAO; } <file_sep>/main/src/AvailiableRAO.h #ifndef AVAILIABLE_RAO #define AVAILIABLE_RAO #include <stdio.h> #include "IAvailiableRAO.h" #include "IPRACHConfig.h" #include "include_log.h" class AvailiableRAO : public IAvailiableRAO{ private: int nSSB; int msg1FDM; int nPreambles; // ssb periodicity for rate matching purpose // correspoding to TS 38.331 ssb-periodicityServingCell int ssbPeriod; int totalRAOPerSubframe; int totalRAOPerFrame; int totalNeedRAO; // for all ssb int associationPeriod; int associationFrame; int startRAO; int endRAO; double ssbPerRAO; IPRACHConfig *prachConfig; // preamble format?// public: AvailiableRAO(int nSSB, double ssbPerRAO, int msg1FDM, int nPreambles, int ssbPeriod, IPRACHConfig *prachConfig); void setNumberofSSB(int nSSB); void setMsg1FDM(int msg1FDM); void setNumberofPreambles(int nPreambles); void setSSBPeriod(int ssbPeriod); void setSSBPerRAO(double ssbPerRAO); void updateStartandEndRAOofSubframe(const int frameIndex, const int subframeIndex); void updateAssociationFrame(); int getNumberofSSB(); int getMsg1FDM(); int getNumberofPreambles(); int getSSBPeriod(); int getStartNumberofPreamble(int ssbIndex); int getStartNumberofRAO(int ssbIndex); int getStartRAOofSubframe(); int getEndRAOofSubframe(); int getTotalNeedRAO(); int getTotalRAOPerSubframe(); double getSSBPerRAO(); bool isRASubframe(const int frameIndex, const int subframeIndex); ~AvailiableRAO(); }; #endif <file_sep>/main/src/Cell.h #ifndef CELL #define CELL #include <QPainter> #include "includefile.h" #include "include_log.h" #include "IDrawable.h" #include "Beam.h" #include "UE.h" #include "CommonMath.h" //#include "PRACHConfig.h" #include "PRACHConfigFR1Paired.h" #include "AvailiableRAO.h" #include "random_access.h" #include "MonitorRAFunction.h" namespace celltype{ enum CellType{ Macro, Femto }; } class Beam; class UE; class Cell : public IDrawable{ public: Cell(int x, int y,int cellIndex, int nBeams, celltype::CellType cellType, int prachConfigIndex, int nPreambles, int cellBW, int ssbSCS, double preambleSCS); virtual void draw(QPainter &painter) = 0; void setCellType(celltype::CellType cellType); void setX(int x); void setY(int y); void setnBeams(int nBeams); void setCellSupportDistance(int supportDistance); void setBeamStartAngle(int diffX, int diffY); void setCellIndex(int cellIndex); void detectUE(UE *ue); void broadcastSI(); void deregisterCell(UE *ue); void updateSubframe(); void resetFrame(); void setMsg1FDM(int msg1FDM); void setSSBPerRAO(double ssbPerRAO); void setPrachConfigIndex(int prachConfigIndex); void setRaResponseWindow(const int raResponseWindw); void receivePreamble(const int raoIndex, const int preambleIndex); void transmitRAR(); void receiveMsg3(Msg3& msg3); void transmitCR(); void restoreMonitorRA2Initial(); virtual void initializeBeams() = 0; virtual void updateBeamsAngle(int diffX, int diffY) = 0; int getX(); int getY(); int getnBeams(); int getCellSupportDistance(); int getCellIndex(); int getSubframeIndex(); int getFrameIndex(); int getMsg1FDM(); int getRaResponseWindow(); int getPrachConfigIndex(); int getTau(); double getBeamStartAngle(); double getSSBPerRAO(); double getCellSpanAngle(); double getPreambleSCS(); double getTotalChannelCapacity(); unsigned long getSuccessUEs(); unsigned long getFailedUEs(); double getEstimateUEs(); bool hasRAR(); celltype::CellType getCellType(); IPRACHConfig *getPRACHConfig(); IAvailiableRAO *getAvailiableRAO(); virtual ~Cell(); protected: int x; int y; int cellIndex; int cellSupportDistance; int nBeams; int cellPixelSize; int subframeIndex; int frameIndex; int raResponseWindow; int nPreambles; int cellBW; int ssbSCS; int startBeamIndex; int endBeamIndex; unsigned long successUEs; unsigned long failedUEs; double estimateUEs; double cellAngle; double startAngle; double endAngle; double beamStartAngle; double preambleSCS; celltype::CellType cellType; vector<Beam*> beams; vector<UE*> ues; vector<vector<RAR*>> rars; vector<Msg3*> msg3s; PRACHConfig *prachConfig; AvailiableRAO *availiableRAO; private: bool checkUEisExist(UE *ue); bool isBeamAllowedPBCH(const int beamIndex); void updateSSBStartAndEndIndex(); MonitorRAFunction *mRA; }; #endif <file_sep>/main/src/IAvailiableRAO.h #ifndef IAVAILIABLE_RAO #define IAVAILIABLE_RAO class IAvailiableRAO{ public: virtual int getNumberofPreambles() = 0; virtual int getStartNumberofPreamble(int ssbIndex) = 0; virtual int getStartNumberofRAO(int ssbIndex) = 0; virtual int getStartRAOofSubframe() = 0; virtual int getEndRAOofSubframe() = 0; virtual int getTotalNeedRAO() = 0; virtual int getTotalRAOPerSubframe() = 0; virtual int getMsg1FDM() = 0; virtual double getSSBPerRAO() = 0; virtual bool isRASubframe(const int frameIndex, const int subframeIndex) = 0; }; #endif <file_sep>/main/src/CommonMath.h #ifndef COMMON_MATH #define COMMON_MATH #include <math.h> #include <stdio.h> bool isInArea(int x, int y, int startAngle, int endAngle, double startB, double startC, double endB, double endC); bool isInArea(const int x1, const int y1, const int x2, const int y2, const double startAngle, const double endAngle, const double distance); double calculateDistance(int x1, int y1, int x2, int y2); int XgetY(int x, double B, double C); int getRnd(int start, int end); #endif <file_sep>/project_test/src_test/RAOtestPrachConfig27.cpp #ifndef PRACH_INDEX_27_TEST #define PRACH_INDEX_27_TEST #include "general_definition.h" extern Cell* cell; extern UE* ue; void testPrachIndex27_17(){ int prachConfigIndex = 27; int msg1FDM = 8; double ssbPerRAO = 1.0 / 4.0; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; int round = getRound(simulationTime, associationFrame); vector<int> *subframeExpect; for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; for(int k = 0;k < 10;k++){ subframeExpect = new vector<int>; subframeExpect->push_back(4); subframeExpect->push_back(5); subframeExpect->push_back(6); subframeExpect->push_back(7); expected.push_back(*subframeExpect); j++; subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } if(j >= simulationTime) break; } printExpects(expected); validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex27_16(){ int prachConfigIndex = 27; int msg1FDM = 8; double ssbPerRAO = 1.0 / 2.0; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; int round = getRound(simulationTime, associationFrame); vector<int> *subframeExpect; for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; for(int k = 0;k < 10;k++){ subframeExpect = new vector<int>; subframeExpect->push_back(2); subframeExpect->push_back(3); expected.push_back(*subframeExpect); j++; } if(j >= simulationTime) break; } printExpects(expected); validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex27_15(){ int prachConfigIndex = 27; int msg1FDM = 4; double ssbPerRAO = 1.0 / 2.0; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; int round = getRound(simulationTime, associationFrame); vector<int> *subframeExpect; for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; for(int k = 0;k < 5;k++){ subframeExpect = new vector<int>; subframeExpect->push_back(2); subframeExpect->push_back(3); expected.push_back(*subframeExpect); j++; subframeExpect = new vector<int>; expected.push_back(*subframeExpect); //printf("%d\t%d\n", j, j %(associationFrame * 10)); j++; } if(j >= simulationTime) break; } printExpects(expected); validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex27_14(){ int prachConfigIndex = 27; int msg1FDM = 2; double ssbPerRAO = 1.0 / 2.0; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; int round = getRound(simulationTime, associationFrame); vector<int> *subframeExpect; for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 1){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); //printf("%d\t%d\n", j, j %(associationFrame * 10)); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(2); subframeExpect->push_back(3); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) < 5){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); //printf("%d\t%d\n", j, j %(associationFrame * 10)); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(2); subframeExpect->push_back(3); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } printExpects(expected); validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex27_13(){ int prachConfigIndex = 27; int msg1FDM = 8; double ssbPerRAO = 4; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; int round = getRound(simulationTime, associationFrame); vector<int> *subframeExpect; for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; for(int k = 0;k < 10;k++){ subframeExpect = new vector<int>; for(int l = 0;l < 8;l++){ subframeExpect->push_back(l); } expected.push_back(*subframeExpect); j++; } if(j >= simulationTime) break; } printExpects(expected); validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex27_12(){ int prachConfigIndex = 27; int msg1FDM = 4; double ssbPerRAO = 4; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; int round = getRound(simulationTime, associationFrame); vector<int> *subframeExpect; for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; for(int k = 0;k < 10;k++){ subframeExpect = new vector<int>; subframeExpect->push_back(0); subframeExpect->push_back(1); subframeExpect->push_back(2); subframeExpect->push_back(3); expected.push_back(*subframeExpect); j++; } if(j >= simulationTime) break; } printExpects(expected); validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex27_11(){ int prachConfigIndex = 27; int msg1FDM = 2; double ssbPerRAO = 4; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; int round = getRound(simulationTime, associationFrame); vector<int> *subframeExpect; for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; for(int k = 0;k < 10;k++){ subframeExpect = new vector<int>; subframeExpect->push_back(0); subframeExpect->push_back(1); expected.push_back(*subframeExpect); j++; } if(j >= simulationTime) break; } printExpects(expected); validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex27_10(){ int prachConfigIndex = 27; int msg1FDM = 1; double ssbPerRAO = 4; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; int round = getRound(simulationTime, associationFrame); vector<int> *subframeExpect; for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; for(int k = 0;k < 10;k++){ subframeExpect = new vector<int>; subframeExpect->push_back(0); expected.push_back(*subframeExpect); j++; } if(j >= simulationTime) break; } printExpects(expected); validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex27_9(){ int prachConfigIndex = 27; int msg1FDM = 1; double ssbPerRAO = 2; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; int round = getRound(simulationTime, associationFrame); vector<int> *subframeExpect; for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; for(int k = 0;k < 5;k++){ subframeExpect = new vector<int>; subframeExpect->push_back(0); expected.push_back(*subframeExpect); j++; subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; } if(j >= simulationTime) break; } printExpects(expected); validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex27_7(){ int prachConfigIndex = 27; int msg1FDM = 1; double ssbPerRAO = 1.0 / 8.0; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 4; vector<vector<int>> expected; int round = getRound(simulationTime, associationFrame); vector<int> *subframeExpect; for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 8){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); //printf("%d\t%d\n", j, j %(associationFrame * 10)); j++; } for(int k = 8;k < 16;k++){ subframeExpect = new vector<int>; subframeExpect->push_back(k); expected.push_back(*subframeExpect); j++; } while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } printExpects(expected); validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex27_6(){ int prachConfigIndex = 27; int msg1FDM = 1; double ssbPerRAO = 1.0 / 4.0; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 2; vector<vector<int>> expected; int round = getRound(simulationTime, associationFrame); vector<int> *subframeExpect; for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 4){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); //printf("%d\t%d\n", j, j %(associationFrame * 10)); j++; } for(int k = 4;k < 8;k++){ subframeExpect = new vector<int>; subframeExpect->push_back(k); expected.push_back(*subframeExpect); j++; } while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } printExpects(expected); validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex27_5(){ int prachConfigIndex = 27; int msg1FDM = 1; double ssbPerRAO = 1.0 / 2.0; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; int round = getRound(simulationTime, associationFrame); vector<int> *subframeExpect; for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 2){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); //printf("%d\t%d\n", j, j %(associationFrame * 10)); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(2); expected.push_back(*subframeExpect); j++; subframeExpect = new vector<int>; subframeExpect->push_back(3); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } printExpects(expected); validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex27_4(){ int prachConfigIndex = 27; int msg1FDM = 8; double ssbPerRAO = 1; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; int round = getRound(simulationTime, associationFrame); vector<int> *subframeExpect; for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; for(int j = 0;j < 10;j++){ subframeExpect = new vector<int>; subframeExpect->push_back(1); subframeExpect->push_back(5); expected.push_back(*subframeExpect); //printf("%d\t%d\n", j, j %(associationFrame * 10)); } if(j >= simulationTime) break; } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex27_3(){ int prachConfigIndex = 27; int msg1FDM = 4; double ssbPerRAO = 1; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; int round = getRound(simulationTime, associationFrame); vector<int> *subframeExpect; for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; for(int j = 0;j < 10;j++){ subframeExpect = new vector<int>; subframeExpect->push_back(1); expected.push_back(*subframeExpect); //printf("%d\t%d\n", j, j %(associationFrame * 10)); } if(j >= simulationTime) break; } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex27_2(){ int prachConfigIndex = 27; int msg1FDM = 2; double ssbPerRAO = 1; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; int round = getRound(simulationTime, associationFrame); vector<int> *subframeExpect; for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; for(int k = 0;k < 5;k++){ subframeExpect = new vector<int>; subframeExpect->push_back(1); expected.push_back(*subframeExpect); j++; subframeExpect = new vector<int>; expected.push_back(*subframeExpect); //printf("%d\t%d\n", j, j %(associationFrame * 10)); j++; } if(j >= simulationTime) break; } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex27_1(){ int prachConfigIndex = 27; int msg1FDM = 1; double ssbPerRAO = 1; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; int round = getRound(simulationTime, associationFrame); vector<int> *subframeExpect; for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; while(j % (associationFrame * 10) < 1){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); //printf("%d\t%d\n", j, j %(associationFrame * 10)); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(1); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) < 5){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); //printf("%d\t%d\n", j, j %(associationFrame * 10)); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(1); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex27(){ testPrachIndex27_1(); testPrachIndex27_2(); testPrachIndex27_3(); testPrachIndex27_4(); testPrachIndex27_5(); testPrachIndex27_6(); testPrachIndex27_7(); testPrachIndex27_9(); testPrachIndex27_10(); testPrachIndex27_11(); testPrachIndex27_12(); testPrachIndex27_13(); testPrachIndex27_14(); testPrachIndex27_15(); testPrachIndex27_16(); testPrachIndex27_17(); } #endif <file_sep>/main/src/Model.h #ifndef MODEL #define MODEL #include "includefile.h" #include "IPaintSubject.h" #include <stdio.h> #include <chrono> #include <thread> #include <iostream> #include <fstream> #include <string> #include <iomanip> #include <ctime> #include <sstream> #include <stdlib.h> #include "Cell.h" #include "MacroCell.h" #include "FemtoCell.h" #include "UE.h" #include "CommonMath.h" #include "include_log.h" #include "EraseRect.h" namespace DrawMode{ enum Mode{ DrawCell, EraseCell }; }; namespace ArrivalMode{ enum Mode{ Uniform, Beta }; }; class Model : public IPaintSubject{ public: Model(); void draw(QPainter &painter); void drawCell(QPainter &painter); void drawUE(QPainter &painter); void setMouseXY(int x, int y); int getMouseX(); int getMouseY(); void setMousePressed(bool isPressed); bool isMousePressed(); int getPressedCount(); unsigned int getFR(); ArrivalMode::Mode getArrivalMode(); void notifyAll(); void registerPaintObservor(IPaintObservor *observor); void traverseUEs(); void transmitDL(); void transmitUL(); void startSimulation(); void setSimulationTime(int simulationTime); void setnBeams(const int nBeams); void setCellType(const celltype::CellType type); void setFR(const unsigned int FR); void setArrivalRate(const unsigned int arrivalRate); void setPrachConfigIndex(std::string s); void setDrawMode(DrawMode::Mode mode); void setNPreambles(const int nPreambles); void setPreambleSCS(const double preambleSCS); void setCellBW(const int cellBW); void setArrivalMode(ArrivalMode::Mode mode); void setTotalUE(const unsigned long totalUE); void setSSBSCS(const int ssbSCS); ~Model(); private: void run(bool isTimesUp, int timestamp); void generateRandomUEs(int timestamp); void recordUELatency(UE *ue); void recordCellsInfo(bool isTimesUp); void initializeOutFiles(); void closeOutFiles(); void plotResult(); void restoreCells2Initial(); void drawing(QPainter &painter); void erasing(QPainter &painter); void detectCellInEraseArea(); int generateBetaUEs(const int timestamp); unsigned long ueIndex; unsigned long participateUEs; unsigned long arrivalUEs; int remainingUEs; int cellIndex; int ueArrivalRate; int mouseX; int mouseY; int prachConfigIndex; vector<Cell*> cells; vector<UE*> UEs; vector<IPaintObservor*> observors; Cell *tempCell; UE *ue; EraseRect eraseRect; celltype::CellType cellType; bool mousePressed; int countPressedReleased; int simulationTime; int simulationCounter; int nBeams; int nPreambles; int cellBW; int ssbSCS; double preambleSCS; std::string outputFolderName; std::string outputFileExtension; std::string outputFileUE; std::string outputFileCell; std::string filenameUE; std::string filenameCell; unsigned int FR; ofstream outFileUE; ofstream outFileCell; std::string curTime; DrawMode::Mode mode; ArrivalMode::Mode arrivalMode; unsigned long totalUE; }; #endif <file_sep>/main/src/IPaintSubject.h #ifndef PAINT_SUBJECT #define PAINT_SUBJECT #include "IPaintObservor.h" class IPaintSubject{ public: virtual void notifyAll() = 0; virtual void registerPaintObservor(IPaintObservor *observor) = 0; }; #endif <file_sep>/main/src/IDrawable.h #ifndef IDRAWABLE #define IDRAWABLE #include <QPainter> class IDrawable{ public: virtual void draw(QPainter& painter) = 0; }; #endif <file_sep>/main/src/mainGUI.cpp #include "mainGUI.h" #include "include_log.h" // Constructor // Initialize Model and UI MainGUI::MainGUI(QWidget *parent): QWidget(parent){ setWindowTitle(QString::fromStdString(sProjectName)); resize(widthWindow, heightWindow); this->model = new Model(); // canvas setting canvas = new SimulationCanvas(this, model); canvas->show(); canvas->setStyleSheet("QWidget{background:white;}"); canvas->setMinimumSize(widthWindow, heightWindow / 2); sp = canvas->sizePolicy(); sp.setHorizontalPolicy(QSizePolicy::MinimumExpanding); sp.setVerticalPolicy(QSizePolicy::Expanding); canvas->setSizePolicy(sp); initialRadioButton(); initialPrachConfig(); initialArrivalRateArea(); initialSimulationTimeArea(); initialDrawingButtonArea(); initialNumberofPreambeArea(); initialPreambleSCSArea(); initialCellBandwithArea(); initialArrivalPattern(); initialTotalUEArea(); initialSSBSCSArea(); initialSystemArea(); initialMainLayout(); connectSignals(); } // Initialize radio button void MainGUI::initialRadioButton(){ // gNBType setting rBtnMacrogNB = new QRadioButton(QString::fromStdString(sMarcogNB), this); rBtnFemtogNB = new QRadioButton(QString::fromStdString(sFemtogNB), this); rBtnMacrogNB->setChecked(true); layoutgNBType = new QHBoxLayout; layoutgNBType->addWidget(rBtnMacrogNB); layoutgNBType->addWidget(rBtnFemtogNB); groupgNBType = new QGroupBox(QString::fromStdString(sgNBType), this); groupgNBType->setLayout(layoutgNBType); // FR setting rBtnFR1 = new QRadioButton(QString::fromStdString(sFR1), this); rBtnFR2 = new QRadioButton(QString::fromStdString(sFR2), this); rBtnFR1->setChecked(true); layoutFR = new QHBoxLayout; layoutFR->addWidget(rBtnFR1); layoutFR->addWidget(rBtnFR2); groupFR = new QGroupBox(QString::fromStdString(sFR), this); groupFR->setLayout(layoutFR); // Number of SSB setting rBtn4Beams = new QRadioButton(QString::fromStdString(sBeam4), this); rBtn8Beams = new QRadioButton(QString::fromStdString(sBeam8), this); rBtn64Beams = new QRadioButton(QString::fromStdString(sBeam64), this); rBtn4Beams->setChecked(true); layoutBeams = new QHBoxLayout; layoutBeams->addWidget(rBtn4Beams); layoutBeams->addWidget(rBtn8Beams); layoutBeams->addWidget(rBtn64Beams); groupBeams = new QGroupBox(QString::fromStdString(sNumberOfBeams), this); groupBeams->setLayout(layoutBeams); } void MainGUI::initialPrachConfig(){ listPrachConfig = new QListWidget(this); int count = 0; listPrachConfig->insertItem(count++, QString::fromStdString(sPrachConfig16)); listPrachConfig->insertItem(count++, QString::fromStdString(sPrachConfig19)); listPrachConfig->insertItem(count++, QString::fromStdString(sPrachConfig22)); listPrachConfig->insertItem(count++, QString::fromStdString(sPrachConfig25)); listPrachConfig->insertItem(count++, QString::fromStdString(sPrachConfig27)); listPrachConfig->insertItem(count++, QString::fromStdString(sPrachConfig101)); listPrachConfig->insertItem(count++, QString::fromStdString(sPrachConfig106)); listPrachConfig->setCurrentRow(0); } // configuration ArrivalRate Area void MainGUI::initialArrivalRateArea(){ // Label setting labelArrivalRate = new QLabel(this); labelUnitArrivalRate = new QLabel(this); labelArrivalRate->setText(QString::fromStdString(sArrivalRate)); labelUnitArrivalRate->setText(QString::fromStdString(sUnitArrivalRate)); // LineEdit setting lEditArrivalRate = new QLineEdit(this); //lEditArrivalRate->setMaximumSize(50, 50); lEditArrivalRate->setValidator(new QIntValidator(lEditArrivalRate)); lEditArrivalRate->setText(QString::number(10)); lEditArrivalRate->setAlignment(Qt::AlignRight); //sp = lEditArrivalRate->sizePolicy(); //sp.setVerticalPolicy(QSizePolicy::Preferred); //sp.setHorizontalPolicy(QSizePolicy::Maximum); //lEditArrivalRate->setSizePolicy(sp); // Arrival rate area setting layoutArrivalRate = new QHBoxLayout; layoutArrivalRate->addWidget(labelArrivalRate); layoutArrivalRate->addWidget(lEditArrivalRate); layoutArrivalRate->addWidget(labelUnitArrivalRate); } // configuration simulation time Area void MainGUI::initialSimulationTimeArea(){ // Label setting labelSimulationTime = new QLabel(this); labelUnitSimulationTime = new QLabel(this); labelSimulationTime->setText(QString::fromStdString(sSimulationTime)); //labelSimulationTime->setMinimumSize(200, 20); labelUnitSimulationTime->setText(QString::fromStdString(sUnitSimulationTime)); // LineEdit setting lEditSimulationTime = new QLineEdit(this); lEditSimulationTime->setValidator(new QIntValidator(lEditSimulationTime)); //lEditSimulationTime->setMaximumSize(50, 50); lEditSimulationTime->setAlignment(Qt::AlignRight); //sp = lEditSimulationTime->sizePolicy(); //sp.setVerticalPolicy(QSizePolicy::Preferred); //sp.setHorizontalPolicy(QSizePolicy::Maximum); //lEditSimulationTime->setSizePolicy(sp); // Simulation time area setting layoutSimulationTime = new QHBoxLayout; layoutSimulationTime->addWidget(labelSimulationTime); layoutSimulationTime->addWidget(lEditSimulationTime); layoutSimulationTime->addWidget(labelUnitSimulationTime); } // configurate draw cell erase cell area void MainGUI::initialDrawingButtonArea(){ btnClear = new QPushButton(this); btnClear->setText(QString::fromStdString(sBtnClear)); btnDrawCell = new QPushButton(this); btnDrawCell->setText(QString::fromStdString(sBtnDrawCell)); btnDrawCell->setEnabled(false); layoutDrawing = new QHBoxLayout; layoutDrawing->addWidget(btnDrawCell); layoutDrawing->addWidget(btnClear); } // initialize number of preamble area void MainGUI::initialNumberofPreambeArea(){ labelNumberofRAPreamble = new QLabel(this); labelNumberofRAPreamble->setText(QString::fromStdString(sNumberofPreamble)); lEditNumberofPreamble = new QLineEdit(this); lEditNumberofPreamble->setValidator(new QIntValidator(lEditNumberofPreamble)); //lEditSimulationTime->setMaximumSize(50, 50); lEditNumberofPreamble->setAlignment(Qt::AlignRight); lEditNumberofPreamble->setText(QString::number(64)); layoutNumberofPreamble = new QHBoxLayout; layoutNumberofPreamble->addWidget(labelNumberofRAPreamble); layoutNumberofPreamble->addWidget(lEditNumberofPreamble); } // initialize area for preamble SCS void MainGUI::initialPreambleSCSArea(){ labelPreambleSCS = new QLabel(this); labelPreambleSCS->setText(QString::fromStdString(sPreambleSCS)); comboPreambleSCS = new QComboBox(this); comboPreambleSCS->setEditable(false); comboPreambleSCS->insertItem(0, QString::number(1.25)); comboPreambleSCS->insertItem(1, QString::number(5)); comboPreambleSCS->insertItem(2, QString::number(15)); comboPreambleSCS->insertItem(3, QString::number(30)); //sp = comboPreambleSCS->sizePolicy(); //sp.setVerticalPolicy(QSizePolicy::Minimum); //comboPreambleSCS->setSizePolicy(sp); layoutPreambleSCS = new QHBoxLayout; //layoutPreambleSCS->setAlignment(Qt::AlignTop); layoutPreambleSCS->addWidget(labelPreambleSCS); layoutPreambleSCS->addWidget(comboPreambleSCS); } // initialize area for cell BW configuration void MainGUI::initialCellBandwithArea(){ labelCellBW = new QLabel(this); labelCellBW->setText(QString::fromStdString(sCellBW)); labelCellBW->setMinimumSize(110, 30); labelCellBW->setMaximumSize(110, 30); sp = labelCellBW->sizePolicy(); sp.setVerticalPolicy(QSizePolicy::Maximum); sp.setHorizontalPolicy(QSizePolicy::Minimum); labelCellBW->setSizePolicy(sp); labelBWUnit = new QLabel(this); labelBWUnit->setText(QString::fromStdString(sBWUnit)); labelBWUnit->setMaximumSize(30, 50); sp = labelBWUnit->sizePolicy(); sp.setVerticalPolicy(QSizePolicy::Preferred); sp.setHorizontalPolicy(QSizePolicy::Maximum); labelBWUnit->setSizePolicy(sp); comboCellBW = new QComboBox(this); comboCellBW->setEditable(false); comboCellBW->insertItem(0, QString::number(5)); comboCellBW->insertItem(1, QString::number(10)); comboCellBW->insertItem(2, QString::number(25)); comboCellBW->insertItem(3, QString::number(50)); comboCellBW->insertItem(4, QString::number(100)); comboCellBW->insertItem(5, QString::number(200)); comboCellBW->insertItem(6, QString::number(400)); layoutCellBW = new QHBoxLayout; layoutCellBW->addWidget(labelCellBW); layoutCellBW->addWidget(comboCellBW); layoutCellBW->addWidget(labelBWUnit); labelCellBW->setVisible(false); labelBWUnit->setVisible(false); comboCellBW->setVisible(false); } // initialize area for arrival pattern void MainGUI::initialArrivalPattern(){ labelArrivalPattern = new QLabel(this); labelArrivalPattern->setText(QString::fromStdString(sArrivalPattern)); comboArrivalPattern = new QComboBox(this); comboArrivalPattern->insertItem(0, "Uniform"); comboArrivalPattern->insertItem(1, "Beta"); comboArrivalPattern->setMinimumSize(130, 20); sp = comboArrivalPattern->sizePolicy(); sp.setHorizontalPolicy(QSizePolicy::Minimum); comboArrivalPattern->setSizePolicy(sp); layoutArrivalPattern = new QHBoxLayout; layoutArrivalPattern->addWidget(labelArrivalPattern); layoutArrivalPattern->addWidget(comboArrivalPattern); } // handle total number of ue area void MainGUI::initialTotalUEArea(){ labelTotalUE = new QLabel(this); labelTotalUE->setText(QString::fromStdString(sTotalUE)); lEditTotalUE = new QLineEdit(this); lEditTotalUE->setValidator(new QIntValidator(lEditTotalUE)); lEditTotalUE->setAlignment(Qt::AlignRight); lEditTotalUE->setText(QString::number(10000)); labelTotalUE->setVisible(false); lEditTotalUE->setVisible(false); layoutTotalUE = new QHBoxLayout; layoutTotalUE->addWidget(labelTotalUE); layoutTotalUE->addWidget(lEditTotalUE); //layoutTotalUE->setVisible(false); } // handle ssb scs area void MainGUI::initialSSBSCSArea(){ labelSSBSCS = new QLabel(this); labelSSBSCS->setText(QString::fromStdString(sSSBSCS)); labelUnitSCS = new QLabel(this); labelUnitSCS->setText(QString::fromStdString(sSCSUnit)); comboSSBSCS = new QComboBox(this); comboSSBSCS->insertItem(0, "15"); comboSSBSCS->insertItem(1, "30"); comboSSBSCS->setMinimumSize(60, 20); sp = comboArrivalPattern->sizePolicy(); sp.setHorizontalPolicy(QSizePolicy::Minimum); comboArrivalPattern->setSizePolicy(sp); layoutSSBSCS = new QHBoxLayout; layoutSSBSCS->addWidget(labelSSBSCS); layoutSSBSCS->addWidget(comboSSBSCS); layoutSSBSCS->addWidget(labelUnitSCS); } // initial area for button start or load, save config area void MainGUI::initialSystemArea(){ // initialize load config button btnLoadConfig = new QPushButton(this); btnLoadConfig->setText(QString::fromStdString(sBtnLoadConfig)); // initialize save config button btnSaveConfig = new QPushButton(this); btnSaveConfig->setText(QString::fromStdString(sBtnSaveConfig)); // initialize start button btnStart = new QPushButton(this); btnStart->setText(QString::fromStdString(sBtnStart)); btnStart->setMaximumSize(50, 50); sp = btnStart->sizePolicy(); sp.setVerticalPolicy(QSizePolicy::Preferred); sp.setHorizontalPolicy(QSizePolicy::Maximum); btnStart->setSizePolicy(sp); // initialize system layout for button start, save, load area layoutSystem = new QHBoxLayout; layoutSystem->addWidget(btnLoadConfig); layoutSystem->addWidget(btnSaveConfig); layoutSystem->addWidget(btnStart); } // Configuration Main Layout void MainGUI::initialMainLayout(){ // Configuration area setting widgetSetting = new QWidget(this); widgetSetting->setMaximumSize(widthWindow, heightWindow / 2); sp = widgetSetting->sizePolicy(); sp.setHorizontalPolicy(QSizePolicy::Maximum); sp.setVerticalPolicy(QSizePolicy::Fixed); widgetSetting->setSizePolicy(sp); layoutSetting = new QGridLayout(widgetSetting); layoutSetting->addWidget(groupFR, 1, 0); layoutSetting->addWidget(groupgNBType, 2, 0); layoutSetting->addWidget(groupBeams, 3, 0); layoutSetting->addLayout(layoutSSBSCS, 4, 0); layoutSetting->addLayout(layoutCellBW, 5, 0); layoutSetting->addLayout(layoutArrivalPattern, 5, 0); layoutSetting->addLayout(layoutArrivalRate, 6, 0); layoutSetting->addLayout(layoutTotalUE, 6, 0); layoutSetting->addLayout(layoutDrawing, 7, 0); layoutSetting->addWidget(listPrachConfig, 1, 1, 3, 1); layoutSetting->addLayout(layoutPreambleSCS, 4, 1); layoutSetting->addLayout(layoutNumberofPreamble, 5, 1); layoutSetting->addLayout(layoutSimulationTime, 6, 1); layoutSetting->addLayout(layoutSystem, 7, 1); // Main Area Setting layoutMain = new QGridLayout(this); layoutMain->addWidget(canvas, 1, 0); layoutMain->addWidget(widgetSetting, 2, 0); } // connect all singals void MainGUI::connectSignals(){ connect(btnStart, SIGNAL(clicked()), this, SLOT(handleButtonStartClick())); connect(rBtn4Beams, SIGNAL(clicked()), this, SLOT(handle4BeamsRadBtnClick())); connect(rBtn8Beams, SIGNAL(clicked()), this, SLOT(handle8BeamsRadBtnClick())); connect(rBtn64Beams, SIGNAL(clicked()), this, SLOT(handle64BeamsRadBtnClick())); connect(rBtnMacrogNB, SIGNAL(clicked()), this, SLOT(handleMacroRadBtnClick())); connect(rBtnFemtogNB, SIGNAL(clicked()), this, SLOT(handleFemtoRadBtnClick())); connect(rBtnFR1, SIGNAL(clicked()), this, SLOT(handleFR1RadBtnClick())); connect(rBtnFR2, SIGNAL(clicked()), this, SLOT(handleFR2RadBtnClick())); connect(listPrachConfig, SIGNAL(currentRowChanged(int)), this, SLOT(handleListPrachIndexChange(int))); connect(btnDrawCell, SIGNAL(clicked()), this, SLOT(handleButtonDrawCellClick())); connect(btnClear, SIGNAL(clicked()), this, SLOT(handleButtonClearClick())); connect(lEditNumberofPreamble, SIGNAL(textChanged(const QString&)), this, SLOT(handleNumberofPreambleChanged(const QString&))); connect(comboPreambleSCS, SIGNAL(currentIndexChanged(const QString&)), this, SLOT(handlePreambleSCSChanged(const QString&))); connect(comboCellBW, SIGNAL(currentIndexChanged(const QString&)), this, SLOT(handleCellBWChanged(const QString&))); connect(comboArrivalPattern, SIGNAL(currentIndexChanged(const QString&)), this, SLOT(handleArrivalPatternChanged(const QString&))); connect(comboSSBSCS, SIGNAL(currentIndexChanged(const QString&)), this, SLOT(handleSSBSCSChanged(const QString&))); } // handle start button click event void MainGUI::handleButtonStartClick(){ SPDLOG_TRACE("start button click"); model->setSimulationTime(lEditSimulationTime->text().toInt()); if(model->getArrivalMode() == ArrivalMode::Uniform) model->setArrivalRate(lEditArrivalRate->text().toInt()); else model->setTotalUE(lEditTotalUE->text().toInt()); model->startSimulation(); } // handle radio button 4 beams click event void MainGUI::handle4BeamsRadBtnClick(){ SPDLOG_TRACE("4 beams\n"); model->setnBeams(beams4); } // handle radio button 8 beams click event void MainGUI::handle8BeamsRadBtnClick(){ SPDLOG_TRACE("8 beams\n"); model->setnBeams(beams8); } // handle radio button 64 beams click event void MainGUI::handle64BeamsRadBtnClick(){ SPDLOG_TRACE("64 beams\n"); model->setnBeams(beams64); } // handle radio button marco click event void MainGUI::handleMacroRadBtnClick(){ SPDLOG_TRACE("Macro gNB selected\n"); model->setCellType(celltype::Macro); } // handle radio button femto click event void MainGUI::handleFemtoRadBtnClick(){ SPDLOG_TRACE("Femto gNB selected\n"); model->setCellType(celltype::Femto); } // handle FR1 radio button click event void MainGUI::handleFR1RadBtnClick(){ SPDLOG_TRACE("FR1 selected\n"); if(model->getFR() == 1){ comboPreambleSCS->removeItem(1); comboPreambleSCS->removeItem(0); comboPreambleSCS->insertItem(0, QString::number(1.25)); comboPreambleSCS->insertItem(1, QString::number(5)); comboPreambleSCS->insertItem(2, QString::number(15)); comboPreambleSCS->insertItem(3, QString::number(30)); comboPreambleSCS->setCurrentIndex(0); comboSSBSCS->removeItem(1); comboSSBSCS->removeItem(0); comboSSBSCS->insertItem(0, QString::number(15)); comboSSBSCS->insertItem(1, QString::number(30)); comboSSBSCS->setCurrentIndex(0); } model->setFR(iFR1); } // handle FR2 radio button click event void MainGUI::handleFR2RadBtnClick(){ SPDLOG_TRACE("FR2 selected\n"); if(model->getFR() == 0){ comboPreambleSCS->removeItem(3); comboPreambleSCS->removeItem(2); comboPreambleSCS->removeItem(1); comboPreambleSCS->removeItem(0); comboPreambleSCS->insertItem(0, QString::number(60)); comboPreambleSCS->insertItem(1, QString::number(120)); comboPreambleSCS->setCurrentIndex(0); comboSSBSCS->removeItem(1); comboSSBSCS->removeItem(0); comboSSBSCS->insertItem(0, QString::number(120)); comboSSBSCS->insertItem(1, QString::number(240)); comboSSBSCS->setCurrentIndex(0); } model->setFR(iFR2); } // handle prach configuration index list widget select row change event void MainGUI::handleListPrachIndexChange(int selectedRow){ model->setPrachConfigIndex(listPrachConfig->item(selectedRow)->text().toStdString()); } // handle button draw cell click void MainGUI::handleButtonDrawCellClick(){ model->setDrawMode(DrawMode::DrawCell); btnClear->setEnabled(true); btnDrawCell->setEnabled(false); } // handle button clear click void MainGUI::handleButtonClearClick(){ model->setDrawMode(DrawMode::EraseCell); btnDrawCell->setEnabled(true); btnClear->setEnabled(false); } // handle lineedit number of preamble changed void MainGUI::handleNumberofPreambleChanged(const QString& text){ model->setNPreambles(text.toInt()); } // handle preamble scs changed void MainGUI::handlePreambleSCSChanged(const QString& text){ model->setPreambleSCS(text.toDouble()); } // handle cell BW changed void MainGUI::handleCellBWChanged(const QString& text){ model->setCellBW(text.toInt()); } // handle arrival pattern changed void MainGUI::handleArrivalPatternChanged(const QString& text){ //SPDLOG_INFO("{0}", text.fromStdString()); if(!text.toStdString().compare("Uniform")){ model->setArrivalMode(ArrivalMode::Uniform); labelArrivalRate->setVisible(true); labelUnitArrivalRate->setVisible(true); lEditArrivalRate->setVisible(true); labelTotalUE->setVisible(false); lEditTotalUE->setVisible(false); } else{ model->setArrivalMode(ArrivalMode::Beta); labelArrivalRate->setVisible(false); labelUnitArrivalRate->setVisible(false); lEditArrivalRate->setVisible(false); labelTotalUE->setVisible(true); lEditTotalUE->setVisible(true); } } // handle ssb scs changed void MainGUI::handleSSBSCSChanged(const QString& text){ model->setSSBSCS(text.toInt()); } // destructor MainGUI::~MainGUI(){ delete model; delete layoutMain; delete layoutArrivalRate; delete layoutSimulationTime; delete layoutSSBSCS; delete layoutTotalUE; delete layoutCellBW; delete layoutArrivalPattern; delete layoutPreambleSCS; delete layoutNumberofPreamble; delete layoutDrawing; delete layoutSystem; delete layoutSetting; delete layoutgNBType; delete layoutFR; delete layoutBeams; delete labelArrivalRate; delete labelSimulationTime; delete labelUnitArrivalRate; delete labelUnitSimulationTime; delete labelNumberofRAPreamble; delete labelPreambleSCS; delete labelCellBW; delete labelBWUnit; delete labelArrivalPattern; delete labelTotalUE; delete labelSSBSCS; delete labelUnitSCS; delete comboPreambleSCS; delete comboCellBW; delete comboArrivalPattern; delete comboSSBSCS; delete btnStart; delete btnSaveConfig; delete btnLoadConfig; delete btnClear; delete btnDrawCell; delete rBtnMacrogNB; delete rBtnFemtogNB; delete rBtnFR1; delete rBtnFR2; delete rBtn4Beams; delete rBtn8Beams; delete rBtn64Beams; delete listPrachConfig; delete groupgNBType; delete groupFR; delete groupBeams; delete lEditArrivalRate; delete lEditSimulationTime; delete lEditNumberofPreamble; delete lEditTotalUE; delete widgetSetting; delete canvas; } <file_sep>/project_test/src_test/RAOtest.cpp #include <stdio.h> #include <stdlib.h> #include <assert.h> #include "general_definition.h" #include "RAOtestPrachConfig16.cpp" #include "RAOtestPrachConfig19.cpp" #include "RAOtestPrachConfig22.cpp" #include "RAOtestPrachConfig25.cpp" #include "RAOtestPrachConfig27.cpp" #include "RAOtestPrachConfig101.cpp" #include "RAOtestPrachConfig106.cpp" int main(){ testPrachIndex16(); testPrachIndex27(); testPrachIndex101(); testPrachIndex106(); testPrachIndex19(); testPrachIndex22(); testPrachIndex25(); printf("test correct\n"); return 0; } <file_sep>/project_test/src_test/RAOtestPrachConfig106.cpp #ifndef PRACH_INDEX_106_TEST #define PRACH_INDEX_106_TEST #include "general_definition.h" extern Cell *cell; extern UE *ue; void testPrachIndex106_23(){ int prachConfigIndex = 106; int msg1FDM = 8; double ssbPerRAO = 4; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; for(int l = 0;l < 10;l++){ subframeExpect = new vector<int>; for(int k = 0;k < 96;k++){ subframeExpect->push_back(k); } expected.push_back(*subframeExpect); j++; } while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex106_22(){ int prachConfigIndex = 106; int msg1FDM = 2; double ssbPerRAO = 4; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; for(int l = 0;l < 10;l++){ subframeExpect = new vector<int>; for(int k = 0;k < 24;k++){ subframeExpect->push_back(k); } expected.push_back(*subframeExpect); j++; } while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex106_21(){ int prachConfigIndex = 106; int msg1FDM = 1; double ssbPerRAO = 4; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; for(int l = 0;l < 10;l++){ subframeExpect = new vector<int>; for(int k = 0;k < 12;k++){ subframeExpect->push_back(k); } expected.push_back(*subframeExpect); j++; } while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex106_20(){ int prachConfigIndex = 106; int msg1FDM = 8; double ssbPerRAO = 2; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; for(int l = 0;l < 10;l++){ subframeExpect = new vector<int>; for(int k = 0;k < 48;k++){ subframeExpect->push_back(k * 2); } expected.push_back(*subframeExpect); j++; } while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex106_19(){ int prachConfigIndex = 106; int msg1FDM = 4; double ssbPerRAO = 2; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; for(int l = 0;l < 10;l++){ subframeExpect = new vector<int>; for(int k = 0;k < 24;k++){ subframeExpect->push_back(k * 2); } expected.push_back(*subframeExpect); j++; } while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex106_18(){ int prachConfigIndex = 106; int msg1FDM = 2; double ssbPerRAO = 2; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; for(int l = 0;l < 10;l++){ subframeExpect = new vector<int>; for(int k = 0;k < 12;k++){ subframeExpect->push_back(k * 2); } expected.push_back(*subframeExpect); j++; } while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex106_17(){ int prachConfigIndex = 106; int msg1FDM = 1; double ssbPerRAO = 2; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; for(int l = 0;l < 10;l++){ subframeExpect = new vector<int>; for(int k = 0;k < 6;k++){ subframeExpect->push_back(k * 2); } expected.push_back(*subframeExpect); j++; } while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex106_16(){ int prachConfigIndex = 106; int msg1FDM = 8; double ssbPerRAO = 1.0 / 8.0; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; for(int l = 0;l < 10;l++){ subframeExpect = new vector<int>; for(int k = 8;k < 16;k++){ subframeExpect->push_back(k); } for(int k = 40;k < 48;k++){ subframeExpect->push_back(k); } for(int k = 72;k < 80;k++){ subframeExpect->push_back(k); } expected.push_back(*subframeExpect); j++; } while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex106_15(){ int prachConfigIndex = 106; int msg1FDM = 4; double ssbPerRAO = 1.0 / 8.0; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; for(int l = 0;l < 5;l++){ subframeExpect = new vector<int>; for(int k = 8;k < 16;k++){ subframeExpect->push_back(k); } for(int k = 40;k < 48;k++){ subframeExpect->push_back(k); } expected.push_back(*subframeExpect); j++; subframeExpect = new vector<int>; for(int k = 40;k < 48;k++){ subframeExpect->push_back(k); } expected.push_back(*subframeExpect); j++; } while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex106_14(){ int prachConfigIndex = 106; int msg1FDM = 2; double ssbPerRAO = 1.0 / 8.0; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; for(int l = 0;l < 2;l++){ subframeExpect = new vector<int>; for(int k = 8;k < 16;k++){ subframeExpect->push_back(k); } expected.push_back(*subframeExpect); j++; subframeExpect = new vector<int>; for(int k = 40;k < 48;k++){ subframeExpect->push_back(k); } expected.push_back(*subframeExpect); j++; subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; subframeExpect = new vector<int>; for(int k = 8;k < 16;k++){ subframeExpect->push_back(k); } expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; for(int k = 8;k < 16;k++){ subframeExpect->push_back(k); } expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex106_13(){ int prachConfigIndex = 106; int msg1FDM = 1; double ssbPerRAO = 1.0 / 8.0; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; subframeExpect = new vector<int>; for(int k = 8;k < 12;k++){ subframeExpect->push_back(k); } expected.push_back(*subframeExpect); j++; subframeExpect = new vector<int>; for(int k = 12;k < 16;k++){ subframeExpect->push_back(k); } expected.push_back(*subframeExpect); j++; subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; subframeExpect = new vector<int>; for(int k = 8;k < 16;k++){ subframeExpect->push_back(k); } expected.push_back(*subframeExpect); j++; subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; subframeExpect = new vector<int>; for(int k = 8;k < 16;k++){ subframeExpect->push_back(k); } expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex106_12(){ int prachConfigIndex = 106; int msg1FDM = 8; double ssbPerRAO = 1.0 / 4.0; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; for(int l = 0;l < 10;l++){ subframeExpect = new vector<int>; for(int k = 0;k < 6;k++){ subframeExpect->push_back(4 + k * 16); subframeExpect->push_back(5 + k * 16); subframeExpect->push_back(6 + k * 16); subframeExpect->push_back(7 + k * 16); } expected.push_back(*subframeExpect); j++; } while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex106_11(){ int prachConfigIndex = 106; int msg1FDM = 4; double ssbPerRAO = 1.0 / 4.0; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; for(int l = 0;l < 10;l++){ subframeExpect = new vector<int>; for(int k = 0;k < 3;k++){ subframeExpect->push_back(4 + k * 16); subframeExpect->push_back(5 + k * 16); subframeExpect->push_back(6 + k * 16); subframeExpect->push_back(7 + k * 16); } expected.push_back(*subframeExpect); j++; } while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex106_10(){ int prachConfigIndex = 106; int msg1FDM = 2; double ssbPerRAO = 1.0 / 4.0; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; for(int l = 0;l < 5;l++){ subframeExpect = new vector<int>; subframeExpect->push_back(4); subframeExpect->push_back(5); subframeExpect->push_back(6); subframeExpect->push_back(7); subframeExpect->push_back(20); subframeExpect->push_back(21); subframeExpect->push_back(22); subframeExpect->push_back(23); expected.push_back(*subframeExpect); j++; subframeExpect = new vector<int>; subframeExpect->push_back(20); subframeExpect->push_back(21); subframeExpect->push_back(22); subframeExpect->push_back(23); expected.push_back(*subframeExpect); j++; } while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex106_9(){ int prachConfigIndex = 106; int msg1FDM = 1; double ssbPerRAO = 1.0 / 4.0; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; for(int l = 0;l < 2;l++){ subframeExpect = new vector<int>; subframeExpect->push_back(4); subframeExpect->push_back(5); subframeExpect->push_back(6); subframeExpect->push_back(7); expected.push_back(*subframeExpect); j++; subframeExpect = new vector<int>; subframeExpect->push_back(20); subframeExpect->push_back(21); subframeExpect->push_back(22); subframeExpect->push_back(23); expected.push_back(*subframeExpect); j++; subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; subframeExpect = new vector<int>; subframeExpect->push_back(4); subframeExpect->push_back(5); subframeExpect->push_back(6); subframeExpect->push_back(7); expected.push_back(*subframeExpect); j++; } subframeExpect = new vector<int>; subframeExpect->push_back(4); subframeExpect->push_back(5); subframeExpect->push_back(6); subframeExpect->push_back(7); expected.push_back(*subframeExpect); j++; while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex106_8(){ int prachConfigIndex = 106; int msg1FDM = 8; double ssbPerRAO = 1.0 / 2.0; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; for(int k = 0;k < 10;k++){ subframeExpect = new vector<int>; for(int l = 0;l < 12;l++){ subframeExpect->push_back(2 + l * 8); subframeExpect->push_back(3 + l * 8); } expected.push_back(*subframeExpect); j++; } while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex106_7(){ int prachConfigIndex = 106; int msg1FDM = 4; double ssbPerRAO = 1.0 / 2.0; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; for(int k = 0;k < 10;k++){ subframeExpect = new vector<int>; for(int l = 0;l < 6;l++){ subframeExpect->push_back(2 + l * 8); subframeExpect->push_back(3 + l * 8); } expected.push_back(*subframeExpect); j++; } while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex106_6(){ int prachConfigIndex = 106; int msg1FDM = 2; double ssbPerRAO = 1.0 / 2.0; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; for(int k = 0;k < 10;k++){ subframeExpect = new vector<int>; subframeExpect->push_back(2); subframeExpect->push_back(3); subframeExpect->push_back(10); subframeExpect->push_back(11); subframeExpect->push_back(18); subframeExpect->push_back(19); expected.push_back(*subframeExpect); j++; } while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex106_5(){ int prachConfigIndex = 106; int msg1FDM = 1; double ssbPerRAO = 1.0 / 2.0; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; for(int k = 0;k < 10;k++){ subframeExpect = new vector<int>; subframeExpect->push_back(2); subframeExpect->push_back(3); subframeExpect->push_back(10); subframeExpect->push_back(11); expected.push_back(*subframeExpect); j++; subframeExpect = new vector<int>; subframeExpect->push_back(10); subframeExpect->push_back(11); expected.push_back(*subframeExpect); j++; } while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex106_4(){ int prachConfigIndex = 106; int msg1FDM = 8; double ssbPerRAO = 1; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; for(int l = 0;l < 10;l++){ subframeExpect = new vector<int>; for(int k = 0;k < 24;k++){ subframeExpect->push_back(1 + k * 4); } expected.push_back(*subframeExpect); j++; } while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex106_3(){ int prachConfigIndex = 106; int msg1FDM = 4; double ssbPerRAO = 1; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; for(int l = 0;l < 10;l++){ subframeExpect = new vector<int>; for(int k = 0;k < 12;k++){ subframeExpect->push_back(1 + k * 4); } expected.push_back(*subframeExpect); j++; } while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex106_2(){ int prachConfigIndex = 106; int msg1FDM = 2; double ssbPerRAO = 1; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; for(int l = 0;l < 10;l++){ subframeExpect = new vector<int>; for(int k = 0;k < 6;k++){ subframeExpect->push_back(1 + k * 4); } expected.push_back(*subframeExpect); j++; } while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex106_1(){ int prachConfigIndex = 106; int msg1FDM = 1; double ssbPerRAO = 1; initialize(prachConfigIndex, msg1FDM, ssbPerRAO); int simulationTime = 100; int associationFrame = 1; vector<vector<int>> expected; vector<int> *subframeExpect; int round = getRound(simulationTime, associationFrame); for(int i = 0;i < round;i++){ int j = i * associationFrame * 10; for(int l = 0;l < 10;l++){ subframeExpect = new vector<int>; for(int k = 0;k < 3;k++){ subframeExpect->push_back(1 + k * 4); } expected.push_back(*subframeExpect); j++; } while(j % (associationFrame * 10) != 0){ subframeExpect = new vector<int>; expected.push_back(*subframeExpect); j++; if(j >= simulationTime) break; } } validation(expected, simulationTime, prachConfigIndex, msg1FDM, ssbPerRAO); destory(); } void testPrachIndex106(){ testPrachIndex106_1(); testPrachIndex106_2(); testPrachIndex106_3(); testPrachIndex106_4(); testPrachIndex106_5(); testPrachIndex106_6(); testPrachIndex106_7(); testPrachIndex106_8(); testPrachIndex106_9(); testPrachIndex106_10(); testPrachIndex106_11(); testPrachIndex106_12(); testPrachIndex106_13(); testPrachIndex106_14(); testPrachIndex106_15(); testPrachIndex106_16(); testPrachIndex106_17(); testPrachIndex106_18(); testPrachIndex106_19(); testPrachIndex106_20(); testPrachIndex106_21(); testPrachIndex106_22(); testPrachIndex106_23(); } #endif <file_sep>/main/src/IPaintObservor.h #ifndef PAINT_OBSERVOR #define PAINT_OBSERVOR class IPaintObservor{ public: virtual void updateCanvas() = 0; }; #endif <file_sep>/main/src/FemtoCell.cpp #include "FemtoCell.h" // Constructor // initialize macro cell // x: gNB x position // y: gNB y position // cellType: gNB CellType, Macro or Femto //FIXME maybe reduntant FemtoCell::FemtoCell(int x, int y, int cellIndex, int nBeams, celltype::CellType cellType, int prachConfigIndex, int nPreambles, int cellBW, int ssbSCS, double preambleSCS):Cell(x, y, cellIndex, nBeams, cellType, prachConfigIndex, nPreambles, cellBW, ssbSCS, preambleSCS){ this->cellAngle = 360; //FIXME this->cellSupportDistance = 100; } // Draw Femto Cell // painter: QPainter use for painting void FemtoCell::draw(QPainter &painter){ painter.setBrush(QBrush(QColor(0, 0, 0, 255), Qt::SolidPattern)); painter.drawEllipse(x - cellPixelSize / 2, y - cellPixelSize / 2, cellPixelSize, cellPixelSize); painter.setBrush(QBrush(QColor(128, 128, 255, 32), Qt::SolidPattern)); Beam *beam; for(unsigned int i = 0;i < beams.size();i++){ beam = beams.at(i); beam->draw(painter); } } // initialize gNB's beams // nBeams: number of beams void FemtoCell::initializeBeams(){ double spanAngle = (double)cellAngle / (double)nBeams; for(int i = 0;i < nBeams;i++){ Beam *beam = new Beam(this, cellIndex, i, cellSupportDistance, spanAngle); beams.push_back(beam); } } // calculate beam start angle based on first mouse click coordinate and // second mouse click coordinate // diffX: the difference of x1 and x2 // diffY: the difference of y1 and y2 void FemtoCell::updateBeamsAngle(int diffX, int diffY){ Cell::setBeamStartAngle(diffX, diffY); Beam *beam; double spanAngle = cellAngle / getnBeams(); for(unsigned int i = 0;i < beams.size();i++){ beam = beams.at(i); beam->setStartAngle(beamStartAngle + i * spanAngle); } } // destructor FemtoCell::~FemtoCell(){ SPDLOG_TRACE("Femto cell destructor"); for(auto it = beams.begin();it != beams.end();it++){ delete (*it); } } <file_sep>/main/src/Beam.h #ifndef BEAM #define BEAM #include "includefile.h" #include "include_log.h" #include <QPainter> #include "Cell.h" #include "UE.h" #include <math.h> #include "CommonMath.h" class Cell; class Beam : public IDrawable{ private: int beamIndex; double spanAngle; int lengthBeam; int cellIndex; double startAngle; Cell *parent; public: Beam(Cell *parent, int cellIndex, int beamIndex, int lengthBeam, double spanAngle); void draw(QPainter &painter); void setBeamIndex(int beamIndex); void setSpanAngle(double spanAngle); void setStartAngle(int beamIndex, double spanAngle); void setStartAngle(double startAngle); void setLengthBeam(int lengthBeam); void setCellIndex(int cellIndex); void detectUE(UE *ue, double power); int getX(); int getY(); int getBeamIndex(); double getSpanAngle(); double getStartAngle(); int getEndAngle(); int getLengthBeam(); int getCellIndex(); ~Beam(); }; #endif <file_sep>/main/src/CommonMath.cpp #include "CommonMath.h" #include <random> std::random_device rd; std::mt19937 gen(rd()); // detect point x and y is in two line's area // two line from startAngle to endAngle // two line with x + By + C = 0 // x: point x, relative point // y: point y, relative point // startAngle: angle of first line // endAngle: angle of second line // startB: first line's coefficient B // startC: first line's coefficient C // endB: second line's coefficient B // endC: second line's coefficient C bool isInArea(int x, int y, int startAngle, int endAngle, double startB, double startC, double endB, double endC){ //printf("x: %d\ty: %d\n", x, y); if(startAngle >= 0 && startAngle < 180 && endAngle > 0 && endAngle <= 180){ //printf("1\n"); if(x + y * startB + startC <= 0 && x + y * endB + endC >= 0) return true; } else if(startAngle > 0 && startAngle <= 180 && endAngle > 180 && endAngle < 360){ //printf("2\n"); if(x + y * startB + startC <= 0 && x + y * endB + endC <= 0) return true; } else if(startAngle > 180 && startAngle < 360 && endAngle > 180 && endAngle <= 360){ //printf("3\n"); if(x + y * startB + startC >= 0 && x + y * endB + endC <= 0) return true; } else if(startAngle > 180 && startAngle <= 360 && endAngle > 0 && endAngle < 180){ //printf("4\n"); if(x + y * startB + startC >= 0 && x + y * endB + endC >= 0) return true; } return false; } // test first point is in second point cover area // the area is covered from start angle to // (start angle + span angle) and 0 to distance // x1: first point of x // y1: first point of y // x2: second point of x // y2: second point of y // startAngle: the cover area of second point start angle // spanAngle: the cover area of second point cover angle // distance: the cover area of second point cover length bool isInArea(const int x1, const int y1, const int x2, const int y2, const double startAngle, const double spanAngle, const double distance){ const double endAngle = spanAngle + startAngle; const double angle = atan2(y2 - y1, x1 - x2) * 180 / M_PI; //printf("start Angle: %f, endAngle: %f\n", startAngle, endAngle); //printf("dif angle: %f\n", angle); if((startAngle <= angle && angle <= endAngle) || (startAngle <= (angle + 360) && (angle + 360) <= endAngle)){ const double difDistance = calculateDistance(x1, y1, x2, y2); if(distance >= difDistance) return true; } return false; } // calculate distance between two x, y point // x1: first point x // y1: first point y // x2: second point x // y2: second point y // return: the distance bewteen two point double calculateDistance(int x1, int y1, int x2, int y2){ return sqrt(pow((x2 - x1), 2) + pow((y2 - y1), 2)); } // use point x get y from linear equation x + By + C = 0 // x: point x, relative point // B: linear equation coefficient B // C: linear equation coefficient C int XgetY(int x, double B, double C){ return ((-1.0) * ((double)x + C)) / B; } // get a random number between start and end interval // start: the lower bound of random number // end: the upper bound of random number int getRnd(int start, int end){ std::uniform_int_distribution<int> distribution(start, end); return distribution(gen); } <file_sep>/main/src/UE.cpp #include "UE.h" using namespace std; // constructor // x: point x of ue // y: point y of ue // id: ue ID UE::UE(int x, int y, unsigned long id) : UE(x, y, id, false){ } // constructor // x: point x of ue // y: point y of ue // id: ue ID // isTest: if this class is used by testing, this value is true, // otherwise false UE::UE(int x, int y, unsigned long id, bool isTest){ setXY(x, y); this->id = id; beamIndex = -1; cellIndex = -1; beamStrength = -1; powerRamp = 0; UEPixelSize = 6; candidateCell = NULL; startRAO = 0; endRAO = 0; raStartRAO = -1; raEndRAO = -1; selectRAOIndex = -1; selectPreambleIndex = -1; uplinkResourceIndex = -1; tc_rnti = -1; preambleTransmitted = false; rarReceived = false; msg3Transmitted = false; raSuccess = false; this->isTest = isTest; collided = false; raFrame = -1; raSubframe = -1; msg3Frame = -1; msg3Subframe = -1; } // set ue's point x and y // x: point x of ue // y: point y of ue void UE::setXY(int x, int y){ this->x = x; this->y = y; } // set cell index, beam index, beam strength // if new beam strength is higher than old beam strength // update information to new beam // cellIndex: cell index related to the beam // beamIndex: beam index // beamstrength: beam strength, power void UE::setBeam(int cellIndex, int beamIndex, int beamStrength){ if(beamStrength > this->beamStrength){ // new beam is better SPDLOG_TRACE("new beam is better than original one"); this->cellIndex = cellIndex; this->beamIndex = beamIndex; this->beamStrength = beamStrength; return; } // old beam is better SPDLOG_TRACE("old beam is better"); } // receive SI // if received SI's cell is better than original cell, // deregister the original cell and change candidate cell // to the received SI's cell // if original cell is better, // deregister the received SI's cell since when detect UE procedure // will store UE context in cell int UE::receiveSI(Cell *cell){ if(cell->getCellIndex() == this->cellIndex){ // TODO: set ssb-perrach-OccasionAndCBRA-preambles // TODO: set CRE(future work) SPDLOG_TRACE("UE {0} receive cell index {1}, beam index {2} system information", id, cell->getCellIndex(), beamIndex); if(candidateCell && candidateCell->getCellIndex() != cellIndex){ candidateCell->deregisterCell(this); } // storing cell's configuration this->candidateCell = cell; prachConfig = cell->getPRACHConfig(); availiableRAO = cell->getAvailiableRAO(); startRAO = beamIndex / availiableRAO->getSSBPerRAO(); int nRAO = 1 / availiableRAO->getSSBPerRAO(); if(nRAO > 0) nRAO -= 1; endRAO = startRAO + nRAO; return 0; } SPDLOG_TRACE("UE: {0} Other cell is better, doesn't need to receive cell index {1} SI", id, cell->getCellIndex()); SPDLOG_TRACE("UE: {0} deregister from cell: {1}", id, cell->getCellIndex()); cell->deregisterCell(this); return 1; } // do the RA procedure // if is testing, UE won't send preamble void UE::doRA(){ SPDLOG_TRACE("UE {0} doing RA", id); if(isTest || !preambleTransmitted){ checkRA(); if(raStartRAO != -1 && raEndRAO != -1){ SPDLOG_TRACE("current subframe is for UE {0} RA", id); SPDLOG_TRACE("UE {0}: ra start RAO: {1}\tra end RAO: {2}", id, raStartRAO, raEndRAO); // store raos index with subframeRAOStart to subframeRAOEnd storeRAOsforRA(availiableRAO->getStartRAOofSubframe(), availiableRAO->getEndRAOofSubframe()); SPDLOG_TRACE("number of rao: %d", raos.size()); SPDLOG_TRACE("rao index: "); for(unsigned int i = 0;i < raos.size();i++) SPDLOG_TRACE("{:4d}", raos[i]); if(!isTest) transmitMsg1(); else SPDLOG_TRACE("is testing"); } else SPDLOG_TRACE("current subframe is not for UE {0} RA", id); } else if (preambleTransmitted && rarReceived && !msg3Transmitted){ // if preamble is transmitted and rar received transmitMsg3(); } else if(preambleTransmitted && rarReceived && msg3Transmitted && raSuccess) SPDLOG_TRACE("UE {0} RA already success, wait for remove from simulation", id); else{ SPDLOG_ERROR("preamble transmitted: {0}, msg3 transmitted: {1}, ra success: {2}", preambleTransmitted, msg3Transmitted, raSuccess); SPDLOG_ERROR("something wrong!!!"); } } // receive RAR // rars: cell transmits rar // cellIndex: cell index void UE::receiveRAR(const vector<RAR*>& rars, const int cellIndex){ SPDLOG_TRACE("rar cell index: {0}, select cell index: {1}", cellIndex, candidateCell->getCellIndex()); if(cellIndex != candidateCell->getCellIndex() || (!preambleTransmitted || rarReceived || msg3Transmitted)) return; SPDLOG_TRACE("UE {0} receiving RAR", id); int index = searchRAR(rars, raos[selectRAOIndex], selectPreambleIndex); SPDLOG_TRACE("rar index: {0}", index); SPDLOG_TRACE("select rao index: {0}, searched rao index: {1}", raos[selectRAOIndex], rars[index]->raoIndex); SPDLOG_TRACE("select preamble index: {0}, searched preamble index: {1}", selectPreambleIndex, rars[index]->preambleIndex); uplinkResourceIndex = rars[index]->uplinkResourceIndex; tc_rnti = rars[index]->tc_rnti; rarReceived = true; msg3Frame = candidateCell->getFrameIndex(); msg3Subframe = candidateCell->getSubframeIndex() + 1; if(msg3Subframe >= 10){ msg3Frame++; msg3Subframe = 0; } SPDLOG_TRACE("receive complete"); } // set active frame index and subframe index // frameIndex: active frame index // subframeIndex: active subframe index void UE::setActiveTime(const int frameIndex, const int subframeIndex){ activeFrame = frameIndex; activeSubframe = subframeIndex; } // check current timing can do RA or not // if RA can be performed, update raStartRAO and raEndRAO // otherwise, raStartRAO and raEndRAO is -1 void UE::checkRA(){ SPDLOG_TRACE("checking ra availiable"); int frameIndex = candidateCell->getFrameIndex(); int subframeIndex = candidateCell->getSubframeIndex(); SPDLOG_TRACE("frame: {0}, subframe: {1}", frameIndex, subframeIndex); raos.clear(); if(availiableRAO->isRASubframe(frameIndex, subframeIndex)){ SPDLOG_TRACE("UE {0}: frame index: {1}, subframe Index: {2} is for RA", id, frameIndex, subframeIndex); updateRAOforRA(); } else{ SPDLOG_TRACE("UE {0}: frame index: {1}, subframe index: {2} not for RA", id, frameIndex, subframeIndex); raStartRAO = -1; raEndRAO = -1; } } // call by checkRA // update RAOs for RA // is current timing contain RAOs for UE to perform RA // update raos // this procedure will do twice if subframeStartRAO is larger than // ue startRAO void UE::updateRAOforRA(){ const int subframeStartRAO = availiableRAO->getStartRAOofSubframe(); const int subframeEndRAO = availiableRAO->getEndRAOofSubframe(); const int totalNeedRAO = availiableRAO->getTotalNeedRAO(); SPDLOG_TRACE("UE {0}: ssb per rao: {1}, msg1FDM: {2}, nBeams: {3}, start RAO: {4}, end RAO: {5}", id, availiableRAO->getSSBPerRAO(), availiableRAO->getMsg1FDM(), candidateCell->getnBeams(), startRAO, endRAO); SPDLOG_TRACE("subframe start RAO: {0}, subframe end RAO: {1}", availiableRAO->getStartRAOofSubframe(), availiableRAO->getEndRAOofSubframe()); updateRAOforRA(startRAO, endRAO, subframeStartRAO, subframeEndRAO, totalNeedRAO); //TODO: still testing if(raStartRAO == -1 && raEndRAO == -1){ updateRAOforRA(startRAO + totalNeedRAO, endRAO + totalNeedRAO, subframeStartRAO, subframeEndRAO, totalNeedRAO); } } // call by updateRAOforRA // the second time to update // check if subframeStartRAO is larger than ue's start RAO once time // startRAO: start rao // endRAO: end rao // subframeStartRAO: subframe start rao // subframeEndRAO: subframe end rao // totalNeedRAO: totalNeedRAO for all ssb // // will call by the condition like this // // |----totalNeedRAO----|----totalNeedRAO----|-----------------------------| // startRAO--------endRAO--subframeStartRAO-------------------subframeEndRAO void UE::updateRAOforRA(const int startRAO, const int endRAO, const int subframeStartRAO, const int subframeEndRAO, const int totalNeedRAO){ raStartRAO = startRAO; raEndRAO = endRAO; if((subframeStartRAO <= startRAO && startRAO <= subframeEndRAO) || (subframeStartRAO <= endRAO && endRAO <= subframeEndRAO)){ if(endRAO >= subframeEndRAO) raEndRAO = subframeEndRAO; if(startRAO <= subframeStartRAO) raStartRAO = subframeStartRAO; } else if(startRAO <= subframeStartRAO && endRAO >= subframeEndRAO){ raStartRAO = subframeStartRAO; raEndRAO = subframeEndRAO; } else{ raStartRAO = -1; raEndRAO = -1; } } // store raos for RA // raStartRAO and raEndRAO only stored the range // raos stores the each of RAO can perform RA // subframeStartRAO: subframe start RAO // subframeEndRAO: subframe end RAO void UE::storeRAOsforRA(const int subframeStartRAO, const int subframeEndRAO){ int nRAO = 1 / availiableRAO->getSSBPerRAO(); const int totalNeedRAO = availiableRAO->getTotalNeedRAO(); const int totalRAOPerSubframe = availiableRAO->getTotalRAOPerSubframe(); SPDLOG_TRACE("raStartRAO: {0}, raEndRAO: {1}", raStartRAO, raEndRAO); for(int i = 0;i < raEndRAO - raStartRAO + 1;i++){ raos.push_back(raStartRAO + i); } // if subframe contains the number of RAOs larger than totalNeedRAO // means that all ssb can map to this subframe more than one time if(totalRAOPerSubframe > totalNeedRAO){ while(raEndRAO + totalNeedRAO <= subframeEndRAO){ raStartRAO += totalNeedRAO; raEndRAO += totalNeedRAO; for(int i = 0;i < raEndRAO - raStartRAO + 1;i++) raos.push_back(raStartRAO + i); } if(raStartRAO + totalNeedRAO <= subframeEndRAO){ raStartRAO += totalNeedRAO; if(raStartRAO + nRAO < subframeEndRAO){ raEndRAO = raStartRAO + nRAO; } else if(raStartRAO + nRAO > subframeEndRAO){ raEndRAO = subframeEndRAO; } for(int i = 0;i < raEndRAO - raStartRAO + 1;i++) raos.push_back(raStartRAO + i); } } } // transmit msg1 aka preamble // ue random select a preamble from availiable resource of current SSB // and select a random RAO from availiable resource of current SSB void UE::transmitMsg1(){ const int startPreamble = availiableRAO->getStartNumberofPreamble(beamIndex); const int nPreambles = availiableRAO->getNumberofPreambles(); raFrame = candidateCell->getFrameIndex(); raSubframe = candidateCell->getSubframeIndex(); raSSBPerRAO = candidateCell->getSSBPerRAO(); raMsg1FDM = candidateCell->getMsg1FDM(); SPDLOG_TRACE("start preambe number: {0}, number of preamble: {1}", startPreamble, nPreambles); selectRAOIndex = getRnd(0, raos.size() - 1); selectPreambleIndex = getRnd(startPreamble, startPreamble + nPreambles - 1); SPDLOG_TRACE("UE {0} select rao: {1}, select preamble: {2}", id, raos[selectRAOIndex], selectPreambleIndex); candidateCell->receivePreamble(raos[selectRAOIndex], selectPreambleIndex); preambleTransmitted = true; } // transmit Msg3 void UE::transmitMsg3(){ const int frame = candidateCell->getFrameIndex(); const int subframe = candidateCell->getSubframeIndex(); if(frame != msg3Frame || subframe != msg3Subframe){ SPDLOG_TRACE("current frame {0} subframe {1} can not transmit msg3", frame, subframe); return; } Msg3 *msg3 = new Msg3; msg3->uplinkResourceIndex = uplinkResourceIndex; msg3->tc_rnti = tc_rnti; msg3->ueIndex = id; msg3->power = beamStrength + powerRamp; candidateCell->receiveMsg3(*msg3); msg3Transmitted = true; } // get ue's point x // return: point x of ue int UE::getX(){ return this->x; } // get ue's point y // return: point y of ue int UE::getY(){ return this->y; } // get ue's id // return: ue's id unsigned long UE::getID(){ return this->id; } // get ue's best beam index // return: ue's best beam index int UE::getBeamIndex(){ return this->beamIndex; } // get ue active frame index // return: ue active frame index int UE::getActiveFrame(){ return activeFrame; } // get ue active subframe index // return: ue active subframe index int UE::getActiveSubframe(){ return activeSubframe; } // get ue departed frame index // return: ue departed frame index int UE::getDepartedFrame(){ return departedFrame; } // get frame that ue perform RA // return: ue perform RA frame int UE::getRAFrame(){ return raFrame; } // get subframe that ue perform RA // return: ue perform RA subframe int UE::getRASubframe(){ return raSubframe; } // get msg1-FDM when ue perform RA // return: msg1-FDM when ue perform RA int UE::getRAMsg1FDM(){ return raMsg1FDM; } // get ue selected preamble index // return: ue selected preamble index int UE::getSelectPreambleIndex(){ return selectPreambleIndex; } // get ue selected rao index // return: ue selected rao index int UE::getSelectRAOIndex(){ return raos[selectRAOIndex]; } // get ssb-perRAO when ue perform RA // return: ssb-perRAO when ue perform RA double UE::getRASSBPerRAO(){ return raSSBPerRAO; } // get ue departed subframe index // return: ue departed subframe index int UE::getDepartedSubframe(){ return departedSubframe; } // get ue's best cell index // return: ue's best cell index int UE::getCellIndex(){ return this->cellIndex; } // get beam strength // return: best beam's strength int UE::getBeamStrength(){ return this->beamStrength; } // receive CR // if received CR and contained ue ID the same as itself // RA is success // otherwise // RA failed, and perform RA from preamble transmission again // CRs: CR transmitted by cell // cellIndex: cell index bool UE::receiveCR(const vector<Msg3*>& CRs, const int cellIndex){ if(cellIndex != candidateCell->getCellIndex() || !msg3Transmitted) return false; int index = searchMsg3(CRs, tc_rnti); SPDLOG_TRACE("contention resolution index: {0}", index); SPDLOG_TRACE("UE TC-RNTI: {0], searched TC-RNTI: {1}", tc_rnti, CRs[index]->tc_rnti); SPDLOG_TRACE("UE id: {0}, searched UE id: {1}", id, CRs[index]->ueIndex); if(tc_rnti == CRs[index]->tc_rnti && id == CRs[index]->ueIndex){ SPDLOG_TRACE("UE {0} RA success!!!", id); departedFrame = candidateCell->getFrameIndex(); departedSubframe = candidateCell->getSubframeIndex(); raSuccess = true; } else{ SPDLOG_TRACE("UE {0} RA failed", id); raSuccess = false; preambleTransmitted = false; rarReceived = false; msg3Transmitted = false; collided = true; raFrame = -1; raSubframe = -1; msg3Frame = -1; msg3Subframe = -1; powerRamp += 5; } return true; } // test whether ue has binded to a cell bool UE::isBindCell(){ if(candidateCell) return true; return false; } // test whether ue has transmitted a preamble bool UE::isPreambleTransmit(){ return preambleTransmitted; } // test whether ue has received a RAR bool UE::isRarReceived(){ return rarReceived; } // test whether ue msg3 is already transmitted bool UE::isMsg3Transmitted(){ return msg3Transmitted; } // test whether ue RA already success bool UE::isRASuccess(){ return raSuccess; } // test whether ue has been collided with other ue bool UE::isCollided(){ return collided; } // draw ue // painter: QPainter void UE::draw(QPainter &painter){ if(collided) painter.setBrush(QBrush(QColor(200, 0, 128, 255), Qt::SolidPattern)); else painter.setBrush(QBrush(QColor(200, 128, 255, 255), Qt::SolidPattern)); painter.drawEllipse(x - UEPixelSize / 2, y - UEPixelSize / 2, UEPixelSize, UEPixelSize); } // get stored RAOs // typicallly testing use this method // other cell may NOT using this method vector<int>& UE::getRAOs(){ return raos; } // destructor UE::~UE(){ SPDLOG_TRACE("ue deleted"); } <file_sep>/main/src/mainGUI.h #ifndef WIDGET_H #define WIDGET_H #include <QWidget> #include <QPushButton> #include <QLabel> #include <QHBoxLayout> #include <QVBoxLayout> #include <QGridLayout> #include <QLineEdit> #include <QComboBox> #include <QRadioButton> #include <QGroupBox> #include <QString> #include <QSizePolicy> #include <QIntValidator> #include <QListWidget> #include <string> #include "Model.h" #include "Cell.h" #include "SimulationCanvas.h" class MainGUI : public QWidget { Q_OBJECT public: MainGUI(QWidget *parent = 0); ~MainGUI(); private: void initialRadioButton(); void initialPrachConfig(); void initialArrivalRateArea(); void initialSimulationTimeArea(); void initialDrawingButtonArea(); void initialNumberofPreambeArea(); void initialPreambleSCSArea(); void initialCellBandwithArea(); void initialArrivalPattern(); void initialTotalUEArea(); void initialSSBSCSArea(); void initialSystemArea(); // for start save area void initialMainLayout(); void connectSignals(); QLabel *labelArrivalRate; QLabel *labelSimulationTime; QLabel *labelUnitArrivalRate; QLabel *labelUnitSimulationTime; QLabel *labelNumberofRAPreamble; QLabel *labelPreambleSCS; QLabel *labelCellBW; QLabel *labelBWUnit; QLabel *labelArrivalPattern; QLabel *labelTotalUE; QLabel *labelSSBSCS; QLabel *labelUnitSCS; QPushButton *btnStart; QPushButton *btnSaveConfig; QPushButton *btnLoadConfig; QPushButton *btnClear; QPushButton *btnNumberofPreamble; QPushButton *btnDrawCell; QRadioButton *rBtnMacrogNB; QRadioButton *rBtnFemtogNB; QRadioButton *rBtnFR1; QRadioButton *rBtnFR2; QRadioButton *rBtn4Beams; QRadioButton *rBtn8Beams; QRadioButton *rBtn64Beams; QListWidget *listPrachConfig; QGroupBox *groupgNBType; QGroupBox *groupFR; QGroupBox *groupBeams; QLineEdit *lEditArrivalRate; QLineEdit *lEditSimulationTime; QLineEdit *lEditNumberofPreamble; QLineEdit *lEditTotalUE; QComboBox *comboPreambleSCS; QComboBox *comboCellBW; QComboBox *comboArrivalPattern; QComboBox *comboSSBSCS; QGridLayout *layoutSetting; QGridLayout *layoutMain; QHBoxLayout *layoutgNBType; QHBoxLayout *layoutFR; QHBoxLayout *layoutBeams; QHBoxLayout *layoutArrivalRate; QHBoxLayout *layoutSimulationTime; QHBoxLayout *layoutSystem; // for button start, save... QHBoxLayout *layoutDrawing; QHBoxLayout *layoutNumberofPreamble; QHBoxLayout *layoutPreambleSCS; QHBoxLayout *layoutCellBW; QHBoxLayout *layoutArrivalPattern; QHBoxLayout *layoutTotalUE; QHBoxLayout *layoutSSBSCS; QWidget *widgetSetting; SimulationCanvas *canvas; //fixed this QSizePolicy sp; Model *model; std::string sProjectName = "project"; std::string sgNBType = "gNB Type"; std::string sNumberOfBeams = "Number of SSB "; std::string sArrivalRate = "UE Arrival Rate: "; std::string sFR = "FR"; std::string sSimulationTime = "Simulation Time: "; std::string sMarcogNB = "Marco gNB"; std::string sFemtogNB = "Femto gNB"; std::string sFR1 = "FR1"; std::string sFR2 = "FR2"; std::string sBeam4 = "4"; std::string sBeam8 = "8"; std::string sBeam64 = "64"; std::string sPrachConfig16 = "Index:16; Format0; FR1; x:1,y:0; RA subframe: 1; time domain RAO:1"; std::string sPrachConfig19 = "Index:19; Format0; FR1; x:1,y:0; RA subframe: 1, 6; time domain RAO:1"; std::string sPrachConfig22 = "Index:22; Format0; FR1; x:1,y:0; RA subframe: 1, 4, 7; time domain RAO:1"; std::string sPrachConfig25 = "Index:25; Format0; FR1; x:1,y:0; RA subframe: 0, 2, 4, 6, 8; time domain RAO:1"; std::string sPrachConfig27 = "Index:27; Format0; FR1; x:1,y:0; RA subframe:0..9; time domain RAO: 1"; std::string sPrachConfig101 = "Index:101; FormatA1; FR1; x:1,y:0; RA subframe: 1; time domain RAO: 12"; std::string sPrachConfig106 = "Index:106; FormatA1; FR1; x:1,y:0; RA subframe:0..9; time domaint RAO: 12"; std::string sUnitms = "ms"; std::string sUnitArrivalRate = "per ms"; std::string sUnitSimulationTime = "second(s)"; std::string sBtnStart = "Start"; std::string sBtnSaveConfig = "Save Config"; std::string sBtnLoadConfig = "Load Config"; std::string sBtnClear = "Erase Cell"; std::string sBtnDrawCell = "Draw Cell"; std::string sBtnSetNumberofPreamble = "Set"; std::string sNumberofPreamble = "Number of CBRA Preamble:"; std::string sPreambleSCS = "Preamble Subcarrier Spacing:"; std::string sCellBW = "Cell Bandwidth:"; std::string sBWUnit = "MHz"; std::string sArrivalPattern = "Arrival Pattern:"; std::string sTotalUE = "Total Number of UE:"; std::string sSSBSCS = "SSB Subcarrier Spacing:"; std::string sSCSUnit = "kHz"; int widthWindow = 540; int heightWindow = 700; //unsigned int FR1 = 0; //unsigned int FR2 = 1; unsigned int beams4 = 4; unsigned int beams8 = 8; unsigned int beams64 = 64; unsigned int iFR1 = 0; unsigned int iFR2 = 1; private slots: void handleButtonStartClick(); void handle4BeamsRadBtnClick(); void handle8BeamsRadBtnClick(); void handle64BeamsRadBtnClick(); void handleMacroRadBtnClick(); void handleFemtoRadBtnClick(); void handleFR1RadBtnClick(); void handleFR2RadBtnClick(); void handleListPrachIndexChange(int selectedRow); void handleButtonDrawCellClick(); void handleButtonClearClick(); void handleNumberofPreambleChanged(const QString& text); void handlePreambleSCSChanged(const QString& text); void handleCellBWChanged(const QString& text); void handleArrivalPatternChanged(const QString& text); void handleSSBSCSChanged(const QString& text); }; #endif <file_sep>/main/src/PRACHConfigFR1Paired.cpp #include "PRACHConfigFR1Paired.h" // constructor // prachConfigIndex: corresponding to TS 38.331 prach-ConfigurationIndex PRACHConfigFR1::PRACHConfigFR1(int prachConfigIndex) : PRACHConfig(prachConfigIndex){ } // config ra parameters void PRACHConfigFR1::configRA(){ switch(prachConfigIndex){ case 16: nPRACHSlot = 1; nTimeDomainRAOPerPrachSlot = 1; raSubframes.clear(); raSubframes.push_back(1); prachConfigPeriod = 10; x = 1; y = 0; break; case 19: nPRACHSlot = 1; nTimeDomainRAOPerPrachSlot = 1; raSubframes.clear(); raSubframes.push_back(1); raSubframes.push_back(6); prachConfigPeriod = 10; x = 1; y = 0; break; case 22: nPRACHSlot = 1; nTimeDomainRAOPerPrachSlot = 1; raSubframes.clear(); raSubframes.push_back(1); raSubframes.push_back(4); raSubframes.push_back(7); prachConfigPeriod = 10; x = 1; y = 0; break; case 25: nPRACHSlot = 1; nTimeDomainRAOPerPrachSlot = 1; raSubframes.clear(); for(int i = 0;i < 5;++i){ raSubframes.push_back(2 * i); } prachConfigPeriod = 10; x = 1; y = 0; break; case 27: nPRACHSlot = 1; nTimeDomainRAOPerPrachSlot = 1; raSubframes.clear(); for(int i = 0;i < 10;i++) raSubframes.push_back(i); prachConfigPeriod = 10; x = 1; y = 0; break; case 101: nPRACHSlot = 2; nTimeDomainRAOPerPrachSlot = 6; raSubframes.clear(); raSubframes.push_back(1); prachConfigPeriod = 10; x = 1; y = 0; break; case 106: nPRACHSlot = 2; nTimeDomainRAOPerPrachSlot = 6; raSubframes.clear(); for(int i = 0;i < 10;i++) raSubframes.push_back(i); prachConfigPeriod = 10; x = 1; y = 0; break; default: SPDLOG_CRITICAL("prach configuration %d not support\n", prachConfigIndex); exit(1); } } // destructor PRACHConfigFR1::~PRACHConfigFR1(){ } <file_sep>/main/src/Model.cpp #include "Model.h" // Initialize Model::Model(){ mouseX = 0; mouseY = 0; ueIndex = 0; cellIndex = 0; ueArrivalRate = 10; tempCell = NULL; mousePressed = false; cellType = celltype::Macro; countPressedReleased = 0; tempCell = NULL; simulationTime = 0; simulationCounter = 0; nBeams = 4; FR = 0; prachConfigIndex = 16; outputFolderName = "./result/"; outputFileExtension = ".csv"; outputFileUE = "UE"; outputFileCell = "Cell"; mode = DrawMode::DrawCell; arrivalMode = ArrivalMode::Uniform; nPreambles = 64; preambleSCS = 1.25; totalUE = 0; ssbSCS = 15; participateUEs = 0; arrivalUEs = 0; } // Set mouse XY position void Model::setMouseXY(int x, int y){ mouseX = x; mouseY = y; if(mode == DrawMode::DrawCell){ if(isMousePressed() && countPressedReleased == 1){ // do when mouse first pressed tempCell->setX(mouseX); tempCell->setY(mouseY); } else if(countPressedReleased > 1){ // do things when mouse click second time tempCell->updateBeamsAngle(x - tempCell->getX(), tempCell->getY() - y); //tempCell->updateBeamsAngle(x - tempCell->getX(), // y - tempCell->getY()); } if(countPressedReleased >= 1) notifyAll(); } else{ eraseRect.setXY(mouseX, mouseY); notifyAll(); } } // Get mouse X position int Model::getMouseX(){ return mouseX; } // Get mouse y position int Model::getMouseY(){ return mouseY; } // Set mouse is pressed or not void Model::setMousePressed(bool isPressed){ mousePressed = isPressed; countPressedReleased++; if(mousePressed){ if(countPressedReleased == 1 && mode == DrawMode::DrawCell){ if(cellType == celltype::Macro) tempCell = new MacroCell(mouseX, mouseY, cellIndex++, nBeams, cellType, prachConfigIndex, nPreambles, cellBW, 15, preambleSCS); else tempCell = new FemtoCell(mouseX, mouseY, cellIndex++, nBeams, cellType, prachConfigIndex, nPreambles, cellBW, 15, preambleSCS); tempCell->initializeBeams(); } else if(countPressedReleased == 3){ // TODO // do mouse pressed second time } if(mode == DrawMode::EraseCell){ detectCellInEraseArea(); } } else if(!mousePressed && countPressedReleased == 4 && mode == DrawMode::DrawCell){ // mouse release second time tempCell->updateBeamsAngle(this->mouseX - tempCell->getX(), tempCell->getY() - this->mouseY); //tempCell->findCellCoverAreaEquation(); countPressedReleased = 0; cells.push_back(tempCell); tempCell = NULL; notifyAll(); } if(mode == DrawMode::EraseCell) countPressedReleased = 0; } // Get mouse is pressed or not bool Model::isMousePressed(){ return mousePressed; } // Draw Cells and UEs void Model::draw(QPainter &painter){ drawing(painter); if(mode == DrawMode::EraseCell){ erasing(painter); } } // get number of mouse pressed count int Model::getPressedCount(){ return countPressedReleased; } // get FR mode // 0: FR1 // 1: FR2 unsigned int Model::getFR(){ return FR; } // get arrival mode // return: arrival mode ArrivalMode::Mode Model::getArrivalMode(){ return arrivalMode; } // notify all IPaintObservor void Model::notifyAll(){ for(unsigned int i = 0;i < observors.size();i++){ IPaintObservor *o = observors.at(i); o->updateCanvas(); } } // register a IPaintObservor void Model::registerPaintObservor(IPaintObservor *observor){ observors.push_back(observor); } // traverse all UEs and detect them is in cell or not void Model::traverseUEs(){ UE *ue; Cell *cell; for(unsigned int i = 0;i < UEs.size();i++){ //printf("%lu\n", i); ue = UEs.at(i); //printf("ues size: %lu\n", UEs.size()); if(ue->isRASuccess()){ recordUELatency(ue); UEs.erase(UEs.begin() + i); delete ue; --i; if(remainingUEs) --remainingUEs; continue; } //printf("ues size: %lu\n", UEs.size()); for(unsigned int j = 0;j < cells.size();j++){ cell = cells.at(j); cell->detectUE(ue); } } } // transmit cells downlink // first broadcast all cells' system information // for ue to deregister from the cell that SINR is not the best one // since when traverse all UEs, cell will first store all detected UE // then when ue receive SI, it will deregister from the cell // that it does not select // second, cell will then transmit RAR and CR later void Model::transmitDL(){ Cell *cell; for(auto it = cells.begin();it != cells.end();it++){ (*it)->broadcastSI(); } for(unsigned int i = 0;i < cells.size();i++){ cell = cells.at(i); // cell->broadcastSI(); cell->transmitRAR(); cell->transmitCR(); } } // transmit all UEs' uplink aka performing RA void Model::transmitUL(){ UE *ue; for(unsigned int i = 0;i < UEs.size();i++){ ue = UEs.at(i); if(ue->isBindCell()){ //printf("UE %lu doing doRA\n", ue->getID()); ue->doRA(); //printf("UE %lu complete doRA\n", ue->getID()); } } } // start the simulation // if simulation time or no cell is in the canvas // it won't start the simulation // otherwise, frame, subframe number, ueIndex counter, // remaining UEs will be reset // then, run the simulation for simulationTime in ms // finally, if there are UEs remain after simulationTime, // simulation will then proceed until all UEs success void Model::startSimulation(){ if(!TESTING){ initializeOutFiles(); if(!outFileUE || !outFileCell){ SPDLOG_CRITICAL("ue output file create failed!\n"); exit(1); } } //////////////////////// testing //////////////////////// //simulationTime = 16; //////////////////////// testing //////////////////////// ueIndex = 0; remainingUEs = 0; bool isTimesUp = false; if(simulationTime == 0 || cells.size() == 0){ SPDLOG_WARN("no cell in simulation or simualtion time is 0"); return; } for(unsigned int i = 0;i < cells.size();i++){ cells.at(i)->resetFrame(); } for(int i = 0;i < simulationTime;i++){ run(isTimesUp, i); } isTimesUp = true; if(UEs.size() > 0 && !TESTING){ for(auto it = UEs.begin();it != UEs.end();it++){ //if((*it)->isBindCell()){ remainingUEs++; //} } int fade = 0; while(remainingUEs){ run(isTimesUp, 0); SPDLOG_TRACE("remaining UEs: {0}", remainingUEs); if(fade < 5) fade++; if(fade == 5){ remainingUEs = 0; for(auto it = UEs.begin();it != UEs.end();it++){ //if((*it)->isBindCell()){ remainingUEs++; //} } } } } SPDLOG_INFO("simulation: {0} complete", simulationCounter++); if(!TESTING){ recordCellsInfo(isTimesUp); restoreCells2Initial(); plotResult(); closeOutFiles(); participateUEs = 0; arrivalUEs = 0; } } // set the simulation time // simulationTime: the simulation time for simulation // it will be stored in ms void Model::setSimulationTime(int simulationTime){ // model store simulation time in msec this->simulationTime = simulationTime * 1000; SPDLOG_TRACE("{0}", this->simulationTime); } // set number of beams // nBeams: number of beams void Model::setnBeams(const int nBeams){ this->nBeams = nBeams; } // set cell type // type: cell type void Model::setCellType(const celltype::CellType type){ cellType = type; } // set UE arrival rate // arrivalRate: ue arrival rate void Model::setArrivalRate(const unsigned int arrivalRate){ SPDLOG_TRACE("arrival rate: {0}", arrivalRate); ueArrivalRate = arrivalRate; } // set prach configuration index // s: input from GUI's combobox item text void Model::setPrachConfigIndex(string s){ //cout << s << endl; int spaceIndex = s.find(";"); int colonIndex = s.find(":"); string sPrachConfigIndex = s.substr(colonIndex + 1, spaceIndex - colonIndex - 1); prachConfigIndex = stoi(sPrachConfigIndex); SPDLOG_TRACE("prach configuration index: {0}", prachConfigIndex); //cout << prachConfigIndex << endl; } // set drawing mode // mode: draw cell mode or erase cell mode void Model::setDrawMode(DrawMode::Mode mode){ this->mode = mode; SPDLOG_TRACE("mode: {0}", this->mode); } // set number of preambles // nPreambles: number of preambles void Model::setNPreambles(const int nPreambles){ this->nPreambles = nPreambles; SPDLOG_TRACE("nPreambles: {0}", this->nPreambles); } // set preamble SCS // preambleSCS: preamble SCS void Model::setPreambleSCS(const double preambleSCS){ this->preambleSCS = preambleSCS; SPDLOG_TRACE("praemble SCS: {0}", this->preambleSCS); } // set cell BW // cellBW: cell BW void Model::setCellBW(const int cellBW){ this->cellBW = cellBW; SPDLOG_TRACE("cell BW: {0}", this->cellBW); } // set arrival mode // mode: arrival mode void Model::setArrivalMode(ArrivalMode::Mode mode){ arrivalMode = mode; SPDLOG_TRACE("arrival mode: {0}", arrivalMode); } // set total arrival ue // totalUE: total arrival ue void Model::setTotalUE(const unsigned long totalUE){ this->totalUE = totalUE; SPDLOG_TRACE("total ue: {0}", this->totalUE); } // set ssb scs // ssbSCS: ssb scs void Model::setSSBSCS(const int ssbSCS){ this->ssbSCS = ssbSCS; SPDLOG_INFO("ssb scs: {0}", this->ssbSCS); } // set FR // FR: FR void Model::setFR(const unsigned int FR){ this->FR = FR; } // run the simulation // first, traverse each UEs stored in model to detect // whether UE is in the cell // second, transmit cell's DL // third, transmit UE's UL // isTimesUp: when simulationTime is 0, set this value to true // for proceeding remaining UEs RA void Model::run(bool isTimesUp, int timestamp){ SPDLOG_INFO("=================info================="); recordCellsInfo(isTimesUp); if(!isTimesUp) generateRandomUEs(timestamp); SPDLOG_INFO("frame: {0}, subframe: {1}", cells.at(0)->getFrameIndex(), cells.at(0)->getSubframeIndex()); traverseUEs(); notifyAll(); transmitDL(); SPDLOG_TRACE("downlink transmit complete"); transmitUL(); SPDLOG_TRACE("uplink transmit complete"); for(unsigned int j = 0;j < cells.size();j++){ cells.at(j)->updateSubframe(); } SPDLOG_INFO("=================info================="); std::this_thread::sleep_for(std::chrono::milliseconds(100)); } // generate random number UEs based on ueArrivalRate // first random select a cell // second random select an angle // third random select a distance from the cell centor // notice that random generated angle has a 5 degree tolerance // and random generated distance has a 10 tolerance // for decreasing the probability of cell cannot detect ue // then calculate random x, y point based on distance and angle void Model::generateRandomUEs(int timestamp){ Cell *cell; SPDLOG_TRACE("generating ues\n"); int nUE; if(arrivalMode == ArrivalMode::Uniform) nUE = ueArrivalRate; else nUE = generateBetaUEs(timestamp); participateUEs += nUE; arrivalUEs += nUE; SPDLOG_INFO("generating number of ue: {0}", nUE); for(int i = 0;i < nUE;i++){ int rndCellIndex = getRnd(0, cells.size() - 1); cell = cells[rndCellIndex]; double cellStartAngle = cell->getBeamStartAngle(); double cellSpanAngle = cell->getCellSpanAngle(); int rndAngle = getRnd(cellStartAngle + 5, cellStartAngle + cellSpanAngle - 5); //printf("%d\n", cell->getCellSupportDistance()); int rndDistance = getRnd(10, cell->getCellSupportDistance() / 2); int rndX = rndDistance * cos(rndAngle * M_PI / 180.0); int rndY = rndDistance * sin(rndAngle * M_PI / 180.0); UE *ue = new UE(cell->getX() + rndX, cell->getY() - rndY, ueIndex++); ue->setActiveTime(cell->getFrameIndex(), cell->getSubframeIndex()); UEs.push_back(ue); } } // generate ues based on beta distribution // timestamp: current time // return: number of ue int Model::generateBetaUEs(const int timestamp){ int alpha = 3; int beta = 4; int output = round(totalUE * pow(timestamp, alpha - 1) * pow((simulationTime - timestamp), beta - 1) / pow(simulationTime, alpha + beta - 1) * 60); return output; } // record ue active and departed frame and subframe index to a file void Model::recordUELatency(UE *ue){ int cellIndexUE = ue->getCellIndex(); auto it = cells.begin(); for(it;it != cells.end();it++) if((*it)->getCellIndex() == cellIndexUE) break; outFileUE << ue->getID() << "," << ue->getCellIndex() << "," << (*it)->getnBeams() << "," << ue->getBeamIndex() << "," << ue->getRASSBPerRAO() << "," << ue->getRAMsg1FDM() << "," << ue->getActiveFrame() << "," << ue->getActiveSubframe() << "," << ue->getRAFrame() << "," << ue->getRASubframe() << "," << ue->getDepartedFrame() << "," << ue->getDepartedSubframe() << "," << ue->getSelectRAOIndex() << "," << ue->getSelectPreambleIndex() << "," << ue->isCollided() << endl; } // record each cells information every 160ms void Model::recordCellsInfo(bool isTimesUp){ auto it = cells.begin(); const int frame = (*it)->getFrameIndex(); const int subframe = (*it)->getSubframeIndex(); if((frame * 10 + subframe) % 160 != 0 && (!isTimesUp || UEs.size() != 0)) return; for(;it != cells.end();it++){ outFileCell << (*it)->getCellIndex() << "," << (*it)->getPreambleSCS() << "," << (*it)->getnBeams() << "," << (*it)->getFrameIndex() << "," << (*it)->getSubframeIndex() << "," << (*it)->getSSBPerRAO() << "," << (*it)->getMsg1FDM() << "," << (*it)->getPrachConfigIndex() << "," << (*it)->getTau() << "," << (*it)->getTotalChannelCapacity() << "," << arrivalUEs << "," << (*it)->getSuccessUEs() << "," << (*it)->getEstimateUEs() << "," << (*it)->getFailedUEs() << "," << participateUEs << endl; participateUEs -= (*it)->getSuccessUEs(); arrivalUEs = 0; } } // initialize output files void Model::initializeOutFiles(){ time_t t = time(nullptr); tm tm = *localtime(&t); stringstream ss; ss << put_time(&tm, "%Y%m%d_%H%M%S"); curTime = ss.str(); outputFolderName = outputFolderName + curTime + "_prach-" + to_string(cells[0]->getPrachConfigIndex()) + "_simu-" + to_string(simulationTime / 1000); if(arrivalMode == ArrivalMode::Uniform){ outputFolderName = outputFolderName + "_uniform" + "_arrival-" + to_string(ueArrivalRate); } else{ outputFolderName = outputFolderName + "_beta" + "_totalUE-" + to_string(totalUE); } outputFolderName += "/"; string command = "mkdir " + outputFolderName; system(command.c_str()); filenameUE = outputFolderName + outputFileUE + outputFileExtension; filenameCell = outputFolderName + outputFileCell + outputFileExtension; outFileUE = ofstream(filenameUE); outFileUE << "\"UE ID\",\"Cell ID\",\"Total Beams\",\"Beam Index\",\"SSB per RAO\",\"msg1-FDM\",\"Active Frame\",\"Active Subframe\",\"RA Frame\",\"RA Subframe\",\"Departed Frame\",\"Departed Subframe\",\"Selected RAO Undex\",\"Selected Preamble\",\"Collided\"" << endl; outFileCell = ofstream(filenameCell); outFileCell << "\"Cell ID\",\"Preamble SCS\",\"Total Beams\",\"Current Frame\",\"Current Subframe\",\"SSB per RAO\",\"msg1-FDM\",\"prach-ConfigurationIndex\",\"Tau\",\"Total Channel Capacity\",\"Arrival UEs\",\"Success UEs\",\"Estimate UEs\",\"Failed UEs\",\"Participate UEs\"" << endl; } // close output files void Model::closeOutFiles(){ outFileUE.close(); outFileCell.close(); outputFolderName = "./result/"; } // plot result done recently void Model::plotResult(){ string command = "python3 ./scripts/plot_result.py"; system(command.c_str()); } // restore the cell's ssb per rao and msg1-fdm to initial status void Model::restoreCells2Initial(){ for(auto it = cells.begin();it != cells.end();it++){ (*it)->restoreMonitorRA2Initial(); } } // draw cell/ue // painter: QPainter void Model::drawing(QPainter &painter){ Cell *cell; UE *ue; for(unsigned int i = 0;i < cells.size();i++){ cell = cells.at(i); cell->draw(painter); } if(countPressedReleased >= 1 && countPressedReleased < 4 && mode == DrawMode::DrawCell){ tempCell->draw(painter); } //painter.setBrush(QBrush(QColor(200, 128, 255, 255), Qt::SolidPattern)); for(decltype(UEs.size()) i = 0;i < UEs.size();i++){ ue = UEs[i]; ue->draw(painter); } } // erase cell // painter: QPainter void Model::erasing(QPainter &painter){ eraseRect.draw(painter); } // detect cell is in erase area // if cell is in erase area, delete void Model::detectCellInEraseArea(){ for(decltype(cells.size()) i = 0;i < cells.size();++i){ SPDLOG_INFO("i: {0}", i); SPDLOG_INFO("cell size: {0}", cells.size()); if(eraseRect.isInside(cells[i]->getX(), cells[i]->getY())){ SPDLOG_INFO("cell {0} is in erase area", cells[i]->getCellIndex()); Cell *cell = cells[i]; cells.erase(cells.begin() + i); delete cell; --i; } } } // destructor Model::~Model(){ SPDLOG_TRACE("model destructor"); for(auto it = cells.begin();it != cells.end();it++){ delete (*it); } } <file_sep>/main/src/EraseRect.h #ifndef ERASE_RECT #define ERASE_RECT #include <QPainter> #include "IDrawable.h" #include "include_log.h" class EraseRect : IDrawable{ private: int x; int y; const int size = 50; public: EraseRect(); ~EraseRect(); void setXY(int x, int y); bool isInside(int objectX, int objectY); void draw(QPainter &painter); }; #endif <file_sep>/main/src/MacroCell.h #ifndef MACROCELL #define MACROCELL #include "Cell.h" #include "CommonMath.h" class MacroCell : public Cell{ public: MacroCell(int x, int y, int cellIndex, int nBeams, celltype::CellType cellType, int prachConfigIndex, int nPreambles, int cellBW, int ssbSCS, double preambleSCS); void draw(QPainter &painter); void initializeBeams(); void setBeamStartAngle(int diffX, int diffY); void updateBeamsAngle(int diffX, int diffY); ~MacroCell(); }; #endif
d3f38f9cf5d532994e24985accb0b8c1a71ea045
[ "C", "Python", "C++", "Shell" ]
53
Python
tim90721/Project
251b095bdb85cc2d4a290af650dc18e6c43c8f4f
60850cfc1f18c72087e7fc67d46924a7fe1f2bb2
refs/heads/master
<file_sep>package AmazonPages; import CommonBase.AppDriver; public class TodaysDeal extends AppDriver{ public TodaysDeal() throws Throwable { super(); // TODO Auto-generated constructor stub } } <file_sep>URL = http://www.amazon.in Search_Text = //input[@id='twotabsearchtextbox'] Go_Btn = //input[@value='Go'] Amazon_Pay = //a[text()='Amazon Pay']<file_sep>package StepDefinition; import org.openqa.selenium.support.PageFactory; import AmazonPages.BrowsingHistory; import cucumber.api.java.en.And; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; public class BrowsingHistorySteps extends BrowsingHistory{ public BrowsingHistorySteps() throws Throwable { super(); // TODO Auto-generated constructor stub } @Given ("^I want to open a \"(.*)\" browser$") public void want_to_open_browser(String browser) throws Throwable{ openBrowser(browser); } @And ("^I want to launch the application$") public void want_to_launch () throws Throwable{ navigateURL(ObjectXpath.getProperty("URL")); } @And ("^I want to enter a value to \"(.*)\" as \"(.*)\"$") public void want_enter_textvalue (String xpath, String textValue) throws Throwable{ enterText(xpath, textValue); } @And ("^I want to click \"(.*)\"$") public void want_click (String label) throws Throwable{ //getIDCick(label); //clickButton(label); BrowsingHistory bH = PageFactory.initElements(driver, BrowsingHistory.class); bH.Amazon_Pay.click(); } @Then ("^I want to highlight elements$") public void want_highlight_element () throws Throwable{ listOfElements(); } } <file_sep># gitSession git training
80964341fc396d11371558f7cae4e9bc6bb9ce83
[ "Markdown", "Java", "INI" ]
4
Java
sharmipriya/gitSession
983c322317dcd6c7b5c6675c36b8984ff928c20e
aacd71d00188ce6be63b448a7bcc6807ec54b269
refs/heads/main
<repo_name>mgiota/myFlix-client-1<file_sep>/src/components/main-view/main-view.jsx import React from 'react'; import Axios from 'axios'; import { MovieCard } from '../movieCard/movieCard'; import { MovieView } from '../movieView/movieView'; export class MainView extends React.Component { constructor() { super(); this.state = { movies: [ { _id: 1, Title: 'Inception', Description: 'desc1...', ImagePath: '...'}, { _id: 2, Title: 'The Shawshank Redemption', Description: 'desc2...', ImagePath: '...'}, { _id: 3, Title: 'Gladiator', Description: 'desc3...', ImagePath: '...'} ], selectedMovie: null } } setSelectedMovie(newSelectedMovie) { this.setState({ selectedMovie: newSelectedMovie }); } render() { const { movies, selectedMovie } = this.state; if(movies.length === 0) return <div className="main-view">The list is empty</div>; // If there is no selected movie, return the home page if (selectedMovie) return ( <div className="main-view"> <MovieView movie={selectedMovie} onBackClick={ newSelectedMovie => {this.setSelectedMovie(newSelectedMovie)}}/> </div> ) return ( <div className="main-view"> { movies.map( movie => <MovieCard key={movie._id} movie={movie} onMovieClick={ movie => {this.setSelectedMovie(movie)} }/> ) } </div> ); } }<file_sep>/src/components/registration/registration.jsx import React, { useState } from 'react'; import Proptypes from 'prop-types'; import Form from 'react-bootstrap/Form'; import Button from 'react-bootstrap/Button'; export function RegistrationView(props) { const [username, setUsername] = useState(''); const [password, setPassword] = useState(''); const [email, setEmail] = useState(''); const [birthdate, setBirthdate] = useState(''); const handleSubmit = (e) => { e.preventDefault(); console.log(username, password, email, birthdate); props.onRegister(username); } return ( <Form> <Form.Group controlId='registerUsername'> <Form.Label>Username:</Form.Label> <Form.Control type='text' onChange={e => setUsername(e.target.value)} /> </Form.Group> <Form.Group controlId='registerPassword'> <Form.Label>Password:</Form.Label> <Form.Control type='password' onChange={e => setPassword(e.target.value)} /> </Form.Group> <Form.Group controlId='registerEmail'> <Form.Label>Email:</Form.Label> <Form.Control type='text' onChange={e => setEmail(e.target.value)} /> </Form.Group> <Form.Group controlId='registerBirthdate'> <Form.Label>Birthdate:</Form.Label> <Form.Control type='text' onChange={e => setBirthdate(e.target.value)} /> </Form.Group> <Button variant='primary' type='submit' onClick={handleSubmit}> Submit </Button> <Button variant='primary' onClick={props.toggleRegister}> Existing User </Button> </Form> ) // return ( // <form> // <label> // Username: // <input type="text" value={username} onChange={e => setUsername(e.target.value)}/> // </label> // <label> // Password: // <input type="text" value={password} onChange={e => setPassword(e.target.value)}/> // </label> // <label> // Email: // <input type="text" value={email} onChange={e => setEmail(e.target.value)}/> // </label> // <label> // Birthdate: // <input type="text" value={birthdate} onChange={e => setBirthdate(e.target.value)}/> // </label> // <button type='button' onClick={handleSubmit}>Submit</button> // </form> // ) } RegistrationView.Proptypes = { onRegister: Proptypes.func.isRequired };<file_sep>/src/index.jsx import React from 'react'; import ReactDOM from 'react-dom'; import { MainView } from './component/main-view/main-view'; import './index.scss'; class MyFlixApplication extends React.Component { render() { return ( <MainView /> ); } } const container = document.getElementsByClassName('app-container')[0]; ReactDOM.render(React.createElement(MyFlixApplication), container);
a8fd4d07ea984a46de7e3f29c7fd0b2c3301c507
[ "JavaScript" ]
3
JavaScript
mgiota/myFlix-client-1
62388fc7bcfa4b8b52986cf57649e27a9597d67a
bb3764c0af42b3ece1301574e19c3ad7a4b8e9f8
refs/heads/master
<repo_name>pandaapo/rpc-client<file_sep>/src/main/java/com/panda/rpc/App.java package com.panda.rpc; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; /** * Hello world! * */ public class App { public static void main( String[] args ) { ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class); RpcProxyClient rpcProxyClient = context.getBean(RpcProxyClient.class); IHelloService iHelloService = rpcProxyClient.clientProxy(IHelloService.class, "localhost",8080, "v2.0"); iHelloService.sayHello(1629); } }
993217986ffd8c5f5a41cad76f190a9338a3d5c7
[ "Java" ]
1
Java
pandaapo/rpc-client
e07202e7cc13f7ce707cf3e5d15f6be1f2842167
f20199e33d7afe9f9fc8821f05e4f55be9cc834e
refs/heads/main
<file_sep>const state = { posts: [ { id: 3, title: "Blog 3", body: "This is Blog 3" }, { id: 2, title: "Blog 2", body: "This is Blog 2" }, { id: 1, title: "Blog 1", body: "This is Blog 1" } ], postId: 0 } const getters = {} const actions = {} const mutations = {} export default { state, getters, actions, mutations }<file_sep>module.exports = { jwtSecret: process.env.JWT_SECRET || '3839ce90-2044-4208-9163-8296998dc9e9' };
42bfa368babe4ee4c4044b6216d6bc8aea91a2d9
[ "JavaScript" ]
2
JavaScript
jsparks0089/blog
0e24593c1823c2501ed5864a47f9c39cf1030c96
168e939f93b3e6f4565a8330f6d80c5d534c1a07
refs/heads/master
<repo_name>oldmill1/twitauth<file_sep>/public/js/app.js (function($) { var users = $("#users li"); var links = users.find( "a" ); var user_ids = new Array(); var main = $("#main"); users.each( function() { var id = $(this).attr("id"); if ( id != undefined ) { user_ids.push(id); } }); var app = { print_tweet: function(status, screen_name, status_id) { buttons = "<div id='actions' class='well'><a href='' id='"+status_id+"' class='retweet btn btn-primary'>ReTweet</button></div>"; text = "<li class='tweet-view'><h2>" + status + "</h2><p>" + screen_name + "</p>"+buttons+"</li>"; main.find("ul").prepend(text); }, }; // app links.click( function(event) { event.preventDefault(); $(".alert").hide(); main.prepend("<img class='working' src='/twitauth/public/img/load.gif' />"); id = $(this).parent().attr("id"); console.log(id ); var data = { 'id': id, 'action': 'userdata' }; $.post( '/twitauth/app.php', data, function( response ) { // todo: check if status exists before going deeper $(".working").hide(); console.dir( response ); var status = response[0].status.text; var status_id = response[0].status.id_str; var screen_name = response[0].screen_name; app.print_tweet( status, screen_name, status_id ); }, 'json' ); }); /* $("a").on("click", function(event){ alert($(this).text()); });*/ $("a.retweet").live("click", function(e){ var data = { 'id': $(this).attr('id'), 'action': 'retweet', }; $.post( '/twitauth/app.php', data, function ( response ) { console.log('tweeted!'); console.dir(response); }, 'json' ); $(this).addClass("retweeted"); $(this).text("Retweeted!"); e.preventDefault(); }); })( jQuery ); <file_sep>/depreciated.php <?php /* * Similiar to get followers, instead gets data for just 1 follower * * @param $id string */ function get_data( $id ) { global $tmhOAuth; $code = $tmhOAuth->request( 'POST', $tmhOAuth->url('1/users/lookup.json', ''), array( 'user_id' => $id ) ); if ( $code == 200 ) { $data = json_decode($tmhOAuth->response['response']); return $data; } else { outputError($tmhOAuth); } } /** * Get extended information for the users who's IDs are passed * * @param $ids array A list of IDs * @return $data array Similiar to what's stored in $user, but for followers of $user */ function get_followers( $ids ) { global $tmhOAuth; if ( $_SESSION['followers'] != null ) { return $_SESSION['followers']; } else { $user_ids = implode(",", $ids); $code = $tmhOAuth->request( 'POST', $tmhOAuth->url('1/users/lookup.json', ''), array( 'user_id' => $user_ids ) ); if ( $code == 200 ) { $data = json_decode($tmhOAuth->response['response'], true); $_SESSION['followers'] = $data; return $data; } else { outputError($tmhOAuth); } } } <file_sep>/app.php <?php require 'tmhOAuth.php'; require 'tmhUtilities.php'; $username = ""; $tmhOAuth = new tmhOAuth(array( 'consumer_key' => 'uq1haQ4HWEBiu4ZXQ7Qw', 'consumer_secret' => '<KEY>', )); $here = tmhUtilities::php_self(); session_start(); if ( gettype($_SESSION['user']) == "object" ) { $user = $_SESSION['user']; } if ( gettype($_SESSION['ids']) == "array" ) { $ids = $_SESSION['ids']; } function outputError($tmhOAuth) { echo 'Error: ' . $tmhOAuth->response['response'] . PHP_EOL; tmhUtilities::pr($tmhOAuth); } // reset request? if ( isset($_REQUEST['wipe'])) { session_destroy(); header("Location: {$here}"); } // got an access token? elseif ( isset($_SESSION['access_token']) ) { $tmhOAuth->config['user_token'] = $_SESSION['access_token']['oauth_token']; $tmhOAuth->config['user_secret'] = $_SESSION['access_token']['oauth_token_secret']; if ( $_SESSION['user'] == null ) : $code = $tmhOAuth->request('GET', $tmhOAuth->url('1/account/verify_credentials')); if ($code == 200) { $user = json_decode($tmhOAuth->response['response']); $username = $user->screen_name; $_SESSION['user'] = $user; } else { outputError($tmhOAuth); } endif; } // being called back by Twitter, with request token ("oauth token") in hand elseif ( isset($_REQUEST['oauth_verifier']) ) { $tmhOAuth->config['user_token'] = $_SESSION['oauth']['oauth_token']; $tmhOAuth->config['user_secret'] = $_SESSION['oauth']['oauth_token_secret']; // request for an access token, we've got the user's permission already $code = $tmhOAuth->request('POST', $tmhOAuth->url('oauth/access_token', ''), array( 'oauth_verifier' => $_REQUEST['oauth_verifier'] )); if ( $code == 200 ) { $_SESSION['access_token'] = $tmhOAuth->extract_params($tmhOAuth->response['response']); unset($_SESSION['oauth']); header("Location: {$here}"); } else { outputError($tmhOAuth); } } // get a request token from Twitter, get back an "oauth token" on 200 elseif ( isset( $_REQUEST['authenticate'] ) || isset( $_REQUEST['authorize']) ) { $callback = isset($_REQUEST['oob']) ? 'oob' : $here; $params = array( 'oauth_callback' => $callback ); $code = $tmhOAuth->request('POST', $tmhOAuth->url('oauth/request_token', ''), $params); if ( $code == 200 ) { $_SESSION['oauth'] = $tmhOAuth->extract_params($tmhOAuth->response['response']); $authurl = $tmhOAuth->url("oauth/authenticate", ""). "?oauth_token={$_SESSION['oauth']['oauth_token']}"; header( "Location: " . $authurl ); } else { outputError($tmhOAuth); } } /** * Wrapper for user/lookup. Lookup users via user ids. * Goes well with friends/ids. (I.e., get all the ids of your friends then get user data about them.) * Doesn't matter if you give it multiple ids (array) or just a single id (int). * * @param array/int Either a comma-seperated array or just a single id. * @return $data array Information regarding the user or users * */ function get_userdata_for( $lookup ) { global $tmhOAuth; if ( is_array( $lookup ) ) { if ( $_SESSION['followers'] != null ) { return $_SESSION['followers']; } else { $user_ids = implode(",", $lookup ); } } else { $user_ids = $lookup; } $code = $tmhOAuth->request( 'POST', $tmhOAuth->url('1/users/lookup.json', ''), array( 'user_id' => $user_ids ) ); if ( $code == 200 ) { $data = json_decode($tmhOAuth->response['response'], true); if ( $_SESSION['followers'] == null ) { $_SESSION['followers'] = $data; } return $data; } else { outputError($tmhOAuth); } } /** * Returns an array of user IDs; * The ID's are users that are following the $user passed in * * @param $user object The user to get followers for * @return $ids array Containg IDs of Twitter users */ function get_followers_ids( $user ) { global $tmhOAuth; if ( $_SESSION['ids'] == null ) : $ids = array(); $code = $tmhOAuth->request( 'GET', $tmhOAuth->url('1/followers/ids.json', ''), array( 'user_id' => $user->id ) ); if ( $code == 200 ) { $data = json_decode($tmhOAuth->response['response'], true); $ids = array_merge( $ids, $data['ids']); $_SESSION['ids'] = $ids; var_dump($_SESSION['ids']); return $ids; } else { outputError($tmhOAuth); } endif; } /* * POST/AJAX API */ if ( !empty( $_POST ) && !is_null( $_POST ) ) { extract( $_POST ); //imports $id; if ( $_POST['action'] == 'userdata' ) { $data = get_userdata_for($id); exit(json_encode($data)); } elseif ( $_POST['action'] == 'retweet' ) { $retweet = retweet( $id ); exit(json_encode($retweet)); } } /** * Retweets a tweet. * * @param $tweet tweet_id * @return $data the retweeted tweet * * todo: add custom text before (or after) the original tweet */ function retweet( $tweet_id ) { global $tmhOAuth; $request_url = $tmhOAuth->url("1/statuses/retweet/$tweet_id"); $params = array( // retweet params ); $code = $tmhOAuth->request( 'POST', $request_url, $params ); if ( $code != 200 ) { // we have a problem... outputError($tmhOAuth); } elseif ( $code == 200 ) { // succesfully retweeted $data = $tmhOAuth->response['response']; exit(json_encode($data)); } } <file_sep>/index.php <?php include 'app.php'; ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>twitauth <?php echo $username; ?></title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content=""> <meta name="author" content=""> <!-- Le styles --> <link href="public/css/bootstrap.css" rel="stylesheet"> <link href="public/css/style.css" rel="stylesheet"> <link href="public/css/bootstrap-responsive.css" rel="stylesheet"> <!-- Le HTML5 shim, for IE6-8 support of HTML5 elements --> <!--[if lt IE 9]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <!-- Le fav and touch icons --> <link rel="shortcut icon" href="public/ico/favicon.ico"> <link rel="apple-touch-icon-precomposed" sizes="144x144" href="public/ico/apple-touch-icon-144-precomposed.png"> <link rel="apple-touch-icon-precomposed" sizes="114x114" href="public/ico/apple-touch-icon-114-precomposed.png"> <link rel="apple-touch-icon-precomposed" sizes="72x72" href="public/ico/apple-touch-icon-72-precomposed.png"> <link rel="apple-touch-icon-precomposed" href="public/ico/apple-touch-icon-57-precomposed.png"> </head> <body> <div class="container"> <h1 class="page-header">twitauth</h1> <?php if ( ! isset( $user ) ) : ?> <p>Welcome to twitauth. To get started, <a href="?authenticate">begin here</a>.</p> <p>You may wish to <a href="?wipe">start over</a> if you're having trouble.</p> <?php else : ?> <p><img src="<?php echo $user->profile_image_url; ?>" /></p> <p>Welcome <strong><?php echo $user->screen_name; ?></strong>. <a href="?wipe">Sign Out</a></p> <br /> <div class="row"> <div class="span3"> <div class="well"> <ul id="users" class="nav nav-list"> <?php $ids = get_followers_ids( $user ); $followers = get_userdata_for( $_SESSION['ids'] ); echo "<li class='nav-header'>My Followers (".count($followers).")</li>"; foreach ( $followers as $follower ) : ?> <li id="<?php echo $follower['id']; ?>"> <a href="http://www.twitter.com/<?php echo $follower['screen_name']; ?>"><?php echo $follower['screen_name']; ?></a> </li> <?php endforeach; ?> </ul> </div> </div> <div class="span9" id="main"> <p class='alert alert-info'>Please click a username on the left to get more info.</p> <ul> <li class="tweet-view"> <a href=""></a> </li> </ul> </div> </div> <?php endif; ?> </div> <!-- /container --> <!-- Le javascript ================================================== --> <!-- Placed at the end of the document so the pages load faster --> <script src="public/js/jquery.js"></script> <script src="public/js/app.js"></script> </body> </html>
3564c0879598763c2b63e6f2fe875097b36d6f20
[ "JavaScript", "PHP" ]
4
JavaScript
oldmill1/twitauth
19c75abf4a1d18c0976c2d9d543364d62515d029
d32771cb74b6673ab232e5a3190d9d1196557441
refs/heads/master
<repo_name>mtheusbrito/desenvolvimento<file_sep>/Projeto/app/src/main/java/com/example/matheus/projeto/ListaRegras.java package com.example.matheus.projeto; import android.content.DialogInterface; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import java.util.List; import adapter.RegraAdapter; import dao.RegraDAO; import model.Regra; import utils.Mensagem; public class ListaRegras extends AppCompatActivity implements AdapterView.OnItemClickListener, DialogInterface.OnClickListener { List<Regra> regraList; private ListView lista; private RegraAdapter regraAdapter; private RegraDAO regraDAO; private android.app.AlertDialog alertDialog; private android.app.AlertDialog alertconfirmacao; private int idposition; //QBF8J-9RVTC-XVLBL @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_lista_regras); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); alertDialog = Mensagem.criarAlertDialogRegras(this); alertconfirmacao = Mensagem.criarDialogConfirmacao(this); regraDAO = new RegraDAO(this); regraList = regraDAO.listaRegras(); regraAdapter = new RegraAdapter(this, regraList); lista = (ListView) findViewById(R.id.list_regra); lista.setAdapter(regraAdapter); lista.setOnItemClickListener(this); } @Override public void onClick(DialogInterface dialogInterface, int i) { Integer id = regraList.get(idposition).get_id(); switch (i) { case 0: break; case 1: alertconfirmacao.show(); break; case DialogInterface.BUTTON_POSITIVE: regraList.remove(idposition); regraDAO.removeRegra(id); lista.invalidateViews(); break; case DialogInterface.BUTTON_NEGATIVE: alertDialog.dismiss(); break; } } @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { idposition = i; alertDialog.show(); } } <file_sep>/Projeto/app/src/main/java/com/example/matheus/projeto/AddRegra.java package com.example.matheus.projeto; import android.os.Bundle; import android.support.design.widget.TextInputLayout; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.text.Editable; import android.text.TextWatcher; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.WindowManager; import android.widget.EditText; import dao.RegraDAO; import model.Regra; import utils.Mensagem; public class AddRegra extends AppCompatActivity { private EditText editDescricao, editValor; private RegraDAO regraDAO; private Regra regra; private TextInputLayout inputLayoutDescricao, inputLayoutValor; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_regra); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); regraDAO = new RegraDAO(this); editDescricao = (EditText) findViewById(R.id.edtdescricao); editValor = (EditText) findViewById(R.id.edtValor); inputLayoutDescricao = (TextInputLayout) findViewById(R.id.inputLayoutDescricao); inputLayoutValor = (TextInputLayout) findViewById(R.id.inputLayoutValor); editDescricao.addTextChangedListener(new MyTextWatcher(editDescricao)); editValor.addTextChangedListener(new MyTextWatcher(editValor)); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_default, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem menuItem) { int id = menuItem.getItemId(); switch (id) { case R.id.action_salvar: this.cadastrar(); break; } return super.onOptionsItemSelected(menuItem); } @Override protected void onDestroy() { regraDAO.fechar(); super.onDestroy(); } private boolean verificaCampoDescricao() { if (editDescricao.getText().toString().trim().isEmpty()) { inputLayoutDescricao.setError(getString(R.string.campo_obrigatorio)); requesFocus(editDescricao); return false; } else { inputLayoutDescricao.setErrorEnabled(false); } return true; } private boolean verificaCampoValor() { if (editValor.getText().toString().trim().isEmpty()) { inputLayoutValor.setError(getString(R.string.campo_obrigatorio)); requesFocus(editValor); return false; } else { inputLayoutValor.setErrorEnabled(false); } return true; } private void requesFocus(View view) { if (view.requestFocus()) { getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); } } private void cadastrar() { if (!verificaCampoDescricao()) { return; } if (!verificaCampoValor()) { return; } String descricao = editDescricao.getText().toString(); String valor = editValor.getText().toString(); regra = new Regra(); regra.setDescricao(descricao); regra.setValor(valor); regraDAO.salvar(regra); Mensagem.Msg(this, getString(R.string.cadastrado)); finish(); } public class MyTextWatcher implements TextWatcher { private View view; private MyTextWatcher(View view) { this.view = view; } public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { } public void afterTextChanged(Editable editable) { switch (view.getId()) { case R.id.edtdescricao: verificaCampoDescricao(); break; case R.id.edtValor: verificaCampoValor(); break; } } } } <file_sep>/Projeto/app/src/main/java/com/example/matheus/projeto/MenuActivity.java package com.example.matheus.projeto; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.CollapsingToolbarLayout; import android.support.design.widget.CoordinatorLayout; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.AdapterView; import android.widget.GridView; import adapter.MenuAdapter; public class MenuActivity extends AppCompatActivity { Toolbar toolbar; CollapsingToolbarLayout collapsingToolbarLayoutAndroid; CoordinatorLayout rootLayoutAndroid; GridView gridView; public static String[] items = { "Adicionar Filho", "Adicionar Regra", "Administrar", "Lista de Regras" }; public static int[] image = { R.mipmap.ic_02, R.mipmap.ic_03, R.mipmap.ic_04, R.mipmap.ic_05, }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.gridview_menu); toolbar = (Toolbar)findViewById(R.id.toolbar) ; gridView = (GridView) findViewById(R.id.grid_view_menu); gridView.setAdapter(new MenuAdapter(this,items,image)); iniciarInstancias(); gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { switch (i) { case 0: Intent intent = new Intent(getApplicationContext(), AddFilho.class); startActivity(intent); break; case 1: Intent intent1 = new Intent(getApplicationContext(), AddRegra.class); startActivity(intent1); break; case 2: Intent intent2 = new Intent(getApplicationContext(), ListaFilhos.class); startActivity(intent2); break; case 3: Intent intent3 = new Intent(getApplicationContext(), ListaRegras.class); startActivity(intent3); break; } } }); } private void iniciarInstancias() { rootLayoutAndroid = (CoordinatorLayout)findViewById(R.id.android_coordinator_layout); collapsingToolbarLayoutAndroid = (CollapsingToolbarLayout)findViewById(R.id.android_collapsingtoolbarLayout); collapsingToolbarLayoutAndroid.setTitle("Mesada"); } }<file_sep>/Projeto/app/src/main/java/com/example/matheus/projeto/ListaFilhos.java package com.example.matheus.projeto; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import java.util.List; import adapter.FilhoAdapter; import dao.FilhoDAO; import model.Filho; import utils.Mensagem; public class ListaFilhos extends AppCompatActivity implements AdapterView.OnItemClickListener, DialogInterface.OnClickListener { private ListView lista; private List<Filho> filhoList; private FilhoAdapter filhoAdapter; private FilhoDAO filhoDAO; private android.app.AlertDialog alertDialog; private android.app.AlertDialog alertConfirmacao; private int idposition; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_lista_filhos); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); alertDialog = Mensagem.criarAlertDialog(this); alertConfirmacao = Mensagem.criarDialogConfirmacao(this); filhoDAO = new FilhoDAO(this); filhoList = filhoDAO.listaFilhos(); filhoAdapter = new FilhoAdapter(this, filhoList); lista = (ListView) findViewById(R.id.list_filho); lista.setAdapter(filhoAdapter); lista.setOnItemClickListener(this); } @Override public void onClick(DialogInterface dialogInterface, int which) { Integer id = filhoList.get(idposition).get_id(); switch (which) { case 0: Intent intent = new Intent(this, Adm.class); intent.putExtra("FILHO_ID", id); startActivity(intent); break; case 1: alertConfirmacao.show(); break; case DialogInterface.BUTTON_POSITIVE: filhoList.remove(idposition); filhoDAO.removeFilho(id); lista.invalidateViews(); break; case DialogInterface.BUTTON_NEGATIVE: alertConfirmacao.dismiss(); break; case 2: Intent it = new Intent(this, BonusActivity.class); it.putExtra("FILHO_ID", id); startActivity(it); break; } } @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) { idposition = position; alertDialog.show(); } }
ff27535432165d4a0df49a759517a3463eb8f9db
[ "Java" ]
4
Java
mtheusbrito/desenvolvimento
f6ed161c3a303c158f88c05dcc8edc18d1a2ebbc
f070a3728b1edf6bfb61575899aa3ce14ba5bf99
refs/heads/main
<file_sep># ergasies_feb21 Το αρχείο ergasiespython.txt είναι το text ASCII file που γίνεται import στις εργασίες 9,12,13 <file_sep>import string import collections f = open('ergasiespython.txt', 'r') #open file data = f.read() #save file's data in data print(data) list1=[] for i in range(len(data)): x=ord(data[i]) if x%2 == 1 : #create list with the odd ascii numbers list1.append(x) print(list1) #print the list with the odd ascii numbers def count_letters(text_file): alphabet = string.ascii_letters + string.digits + string.punctuation #letters,digits,special characters alphabet_set = set(alphabet) counts = collections.Counter(c for c in text_file if c in alphabet_set) list = [] #This list will contain the letters and their probability for letter in alphabet: #Calculating probability total = sum(counts.values()) prob = counts[letter] / total if counts[letter] != 0: #Discard the letters with zero probability list.append(letter) list.append("%.2f" % round(prob, 2)) #Rounding and using only two decimal places return list counts = count_letters(data) #print (counts) #The original list containing all letters and probabilities for i in counts: a = ''.join(list(i)) #Seperate the data and their probabilities in 2 lines if len(a)==1: #Only get the line with the data's character print(a + ':') else: #Only get the line with the probabilities b= list(i)[-2: ] #Get the last 2 digits of the probability c=(''.join(b)) #print(c + "%") #Printing and converting the probability to the 100% scale star='*' print(star * int(c)) #Print as many stars as the probability value. For example: 8% = 8 stars #f.close() <file_sep>""" Επειδή η πλειοψηφία των κατοπτρικών χαρακτήρων έχουν τιμή(int) 130 και πάνω, αντιστοιχούν στον extended ASCII code, δηλαδή στα διάφορα σύμβολα, οπότε είναι λογικό στο τελικό αποτέλεσμα να βρίσκονται τα σύμβολα αυτά ή ακόμη και κουτάκια που στην ουσία παραμπέμπουν και αυτά στα ίδια σύμβολα. """ f = open('ergasiespython.txt', 'r') #open file data = f.read() #save file's data in data #print(data) list1=[] for i in range(len(data)): x = 255 - ord(data[i]) #pername sto x ton katoptriko tou ascii tou kathe stoixeiou tou txt list1.append(x) #dimiourgia listas me ta katoptrika ascii print(list1) list1=list1[::-1] #allazw twra tin seira twn dedomenwn apo kanoniki se anapodi for i in list1: #gia na ta ektipwsw kateutheian me antestrammeni seira meta print("".join(chr(i)),end='') #metatropi tou ascii se text kai ektiposi telikou zitoumenou <file_sep>import random term = int(input("Give the sequence's term you'd like: ")) # The Fibonacci sequence n0, n1 = 0, 1 # first two terms # 1os oros:0, 2os:1, 3os:1, 4os:2, 5os:3 kai ta loipa... count = 2 if term == 1: print("Term", term, "equals to:", n0) print('Your p:', n0, ',', 'is not prime!') elif term == 2 or term==3: print("Term", term, "equals to:", n1) print('Your p:', n1, ',', 'is not prime!') elif term <= 0: print('Please enter a value greater than 0!') else: while count < term: p = n0 + n1 n0 = n1 n1 = p count += 1 print('Term', term, 'equals to:', p) x = 0 for i in range(20): a = (random.randint(1, 2000)) #random number from 1 to 2.000, you can change the range #print(a) #if ((a ** p)-a) % p == 0: if (a**p) % p == a%p: x += 1 #print(x) if x == 20: print('Your p:', p, ',', 'is prime!') else: print('Your p:', p, ',', 'is not prime!') <file_sep>f = open('ergasiespython.txt', 'r') #open file data = f.read() #save file's data in data alphabet = '~`!@#$%^&*()_+-=[]{};:"",./<>?\|123456789' #creating an alphabet in order to replace them later for i in data: if i in alphabet or i=="'" or i=="" : #if u find a symbol from our alphabet replace it with space data=data.replace(i," ") print(data) list1=data.split(" ") #creating a list with the words of the txt and the spaces of the aplhabet #print(list1) while ('' in list1): #we want to be left only with the words of the txt for stoixeio in list1: #double loop to search all the lenght of the list if stoixeio=='' : #so we search if there are spaces on the list to remove them list1.pop(list1.index(stoixeio)) #remove the spaces from the list #print(list1) for i in range (0, len(list1)-1): #double loop to go through all the lenght of every word for j in range(i, len(list1)): #and the next word if (len(list1[i]) + len(list1[j])) == 20: #if word1 and word2 have character length=20 print the pair print('Character length=20:',"'", list1[i],"'", 'and',"'", list1[j],"'", '!Pair found!')
47073f8eb05b42a15cb37999b59f1901715ff196
[ "Markdown", "Python" ]
5
Markdown
Vasiliki011/ergasies_feb21
fc9dc8652826820bd51c500598d12f0bb1f4cc00
5b1cac09cae21a5ed22b97b2330c696a872e5eb0
refs/heads/master
<file_sep>chrome.browserAction.onClicked.addListener(function (tab) { window.alert( `An Achewood companion. - Left Arrow / J: previous comic - Right Arrow / K: next comic - A: view alt text - R: random comic` ); }); chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) { console.log(tabId, changeInfo, tab); if (changeInfo.status === "complete" && tab.active) { chrome.tabs.executeScript(null, { file: "app.js" }); } }); <file_sep>let url = window.location.origin; window.addEventListener("keydown", function (e) { if (e.key === "ArrowLeft" || e.key.match(/^j$/i)) { const previousComic = document .querySelector(".left a") .getAttribute("href"); window.location = `${url}/${previousComic}`; } else if (e.key === "ArrowRight" || e.key.match(/^k$/i)) { const nextComic = document.querySelector(".right a").getAttribute("href"); window.location = `${url}/${nextComic}`; } else if (e.key.match(/^a$/i)) { const altText = document .querySelector("#comic_body img.comic") .getAttribute("title"); window.alert(altText); } else if (e.key.match(/^r$/i)) { window.location = "http://www.ohnorobot.com/random.php?comic=636"; } }); <file_sep># GOLDEN TABLOID This is an extension to make reading [Achewood][achewood] easier. Available now for [Chrome][chrome] and [Firefox][firefox]. ## Features - Navigate forward/backward with your left and right arrow keys (mice begone) - Press `A` to view the alt text for a comic - Press `R` to view a random comic Pull requests are welcome, always, forever. [achewood]: http://www.achewood.com/ [chrome]: https://chrome.google.com/webstore/detail/golden-tabloid/dpmaginmjlogipoijfhmbjoihmgckkjh?hl=en-US&gl=US [firefox]: https://addons.mozilla.org/en-US/firefox/addon/golden-tabloid/ ## Changelog ### v0.0.5 – April 29th 2020 - Fixed the random comic function. Pressing `R` now loads a random comic as expected. - Ran prettier to clean up some formatting, but it's still nothing fancy.
e31dadff76eaa098033e6e4d92e69698134bb2c7
[ "JavaScript", "Markdown" ]
3
JavaScript
whymog/golden-tabloid
89955394d72de036e17078f6282bed3e48617bc4
d06c47b8b04630dbf8dfc74121094fb544180afc
refs/heads/master
<repo_name>sbsrouteur/weewx-opensensemap<file_sep>/install.py # installer for OpenSensMap Rest uploader # Copyright 2021- # Distributed under the terms of the MIT License from weecfg.extension import ExtensionInstaller def loader(): return OpenSenseMapInstaller() class OpenSenseMapInstaller(ExtensionInstaller): def __init__(self): super(OpenSenseMapInstaller, self).__init__( version="0.1", name='OpenSenseMap', description='Upload weather data to OpenSenseMap.', author="sbsrouteur", author_email="<EMAIL>", restful_services='user.opensensemap.OpenSenseMap', config={ 'StdRESTful': { 'OpenSenseMap': { 'SensorId': 'INSERT_SENSORBOX_ID_HERE', 'AuthKey': 'INSERT_AUTH_KEY_HERE', 'UsUnits':'False', 'enable':'True', 'Sensors':{ 'outTemp':{ 'SensorId':'ENTER_OUT_TEMP_SENSOR_ID' }, 'outHumidity':{ 'SensorId':'ENTER_OUT_Humidity_SENSOR_ID' } } }}}, files=[('bin/user', ['bin/user/opensensemap.py'])] ) <file_sep>/README.md # weewx-opensensemap weewx extension that sends data to OpenSenseMap Copyright 2021- sbsRouteur Distributed under the terms of the MIT License Installation instructions: 1) download `wget -O weewx-opensensemap.zip https://github.com/sbsrouteur/weewx-opensensemap/releases/download/V0.3/weewx-opensensemap-0.3.zip` 2) run the installer: `wee_extension --install weewx-opensensemap.zip` 3) modify weewx.conf: ``` [StdRESTful] [[OpenSenseMap]] SensorId=INSERT_SENSORBOX_ID_HERE, AuthKey=INSERT_AUTH_KEY_HERE, UsUnits=False, [[Sensors]] [[outTemp]] SensorId=ENTER_OUT_TEMP_SENSOR_ID Unit=degree_C #Optional Unit override Format=%0.3f #Optional Format override [[outHumidity]] SensorId=ENTER_OUT_Humidity_SENSOR_ID ``` 1) restart weewx ``` sudo /etc/init.d/weewx stop sudo /etc/init.d/weewx start ``` <file_sep>/bin/user/opensensemap.py # Copyright 2021- sbsRouteur """ This is a weewx extension that uploads data to OpenSenseMap. https://opensensemap.org Minimal Configuration: [StdRESTful] [[OpenSenseMap]] SensorBoxID = OpenSenseMap_ID AuthKey = OpenSenseMap_AuthSecret USUnits = False [[Sensors]] [[outTemp]] SensorId = SENSOR_ID Unit = °C .... """ try: # Python 3 import queue except ImportError: # Python 2 import Queue as queue import json import calendar import re import sys import time import six from six.moves import urllib try: # Python 3 from urllib.parse import urlencode except ImportError: # Python 2 from urllib import urlencode import weewx import weewx.restx import weewx.units from weeutil.weeutil import startOfDayUTC from weeutil.weeutil import to_bool VERSION = "0.3" if weewx.__version__ < "3": raise weewx.UnsupportedFeature("weewx 3 is required, found %s" % weewx.__version__) try: # Test for new-style weewx logging by trying to import weeutil.logger import weeutil.logger import logging log = logging.getLogger(__name__) def logdbg(msg): log.debug(msg) def loginf(msg): log.info(msg) def logerr(msg): log.error(msg) except ImportError: # Old-style weewx logging import syslog def logmsg(level, msg): syslog.syslog(level, 'OpenSenseMap: %s' % msg) def logdbg(msg): logmsg(syslog.LOG_DEBUG, msg) def loginf(msg): logmsg(syslog.LOG_INFO, msg) def logerr(msg): logmsg(syslog.LOG_ERR, msg) class OpenSenseMap(weewx.restx.StdRESTful): def __init__(self, engine, config_dict): """This service recognizes standard restful options plus the following: SensorBoxId: OpenSenseMap Box identifier AuthKey : Box Auth Secret Key password: <PASSWORD> Sensor : Dictionnary of Sensors Key : WeewxValueName SensorID : SensorID for API """ super(OpenSenseMap, self).__init__(engine, config_dict) site_dict = weewx.restx.get_site_dict(config_dict, 'OpenSenseMap', 'SensorId', 'AuthKey','UsUnits') if site_dict is None: return Sensors=config_dict['StdRESTful']['OpenSenseMap']['Sensors'] if Sensors is None: raise ("Missing sensors collection option") site_dict['manager_dict'] = weewx.manager.get_manager_dict( config_dict['DataBindings'], config_dict['Databases'], 'wx_binding') self.archive_queue = queue.Queue() self.archive_thread = OpenSenseMapThread(self.archive_queue,Sensors, **site_dict) self.archive_thread.start() self.bind(weewx.NEW_ARCHIVE_RECORD, self.new_archive_record) self.LogginID = site_dict['SensorId'][0:2]+"xxxxxxxx"+site_dict['SensorId'][-4:] loginf("OpenSenseMap v%s: Data for station %s will be posted"% (VERSION,self.LogginID)) print("OpenSenseMap v%s: Data for station %s will be posted"% (VERSION,self.LogginID)) def new_archive_record(self, event): self.archive_queue.put(event.record) class OpenSenseMapThread(weewx.restx.RESTThread): _SERVER_URL = 'https://ingress.opensensemap.org' """_DATA_MAP = {'tempf': ('outTemp', '%.1f'), # F 'humidity': ('outHumidity', '%.0f'), # percent 'winddir': ('windDir', '%.0f'), # degree [0-360] 'windspeedmph': ('windSpeed', '%.1f'), # mph 'windgustmph': ('windGust', '%.1f'), # mph 'baromin': ('barometer', '%.3f'), # inHg 'rainin': ('hourRain', '%.2f'), # in 'dailyRainin': ('dayRain', '%.2f'), # in 'monthlyrainin': ('monthRain', '%.2f'), # in 'tempfhi': ('outTempMax', '%.1f'), # F (for the day) 'tempflo': ('outTempMin', '%.1f'), # F (for the day) 'Yearlyrainin': ('yearRain', '%.2f'), # in 'dewptf': ('dewpoint', '%.1f'), # F 'solarradiation': ('radiation', '%.1f'), # MJ/m^2 'UV': ('UV', '%.0f'), # index 'soiltempf': ('soilTemp1', '%.1f'), # F 'soiltempf2': ('soilTemp2', '%.1f'), # F 'soiltempf3': ('soilTemp3', '%.1f'), # F 'soiltempf4': ('soilTemp4', '%.1f'), # F 'soilmoisture': ('soilMoist1', '%.1f'), # % 'soilmoisture2': ('soilMoist2', '%.1f'), # % 'soilmoisture3': ('soilMoist3', '%.1f'), # % 'soilmoisture4': ('soilMoist4', '%.1f'), # % 'leafwetness': ('leafWet1', '%.1f'), # % 'leafwetness': ('leafWet1', '%.1f'), # % 'tempf2': ('extraTemp1', '%.1f'), # F 'tempf3': ('extraTemp2', '%.1f'), # F 'tempf4': ('extraTemp3', '%.1f'), # F 'humidity2': ('extraHumid1', '%.0f'), # % 'humidity3': ('extraHumid2', '%.0f'), # % } """ def __init__(self, q, Sensors, SensorId, AuthKey, UsUnits, manager_dict, server_url=_SERVER_URL, skip_upload=False, post_interval=None, max_backlog=sys.maxsize, stale=None, log_success=True, log_failure=True, timeout=60, max_tries=3, retry_wait=5): super(OpenSenseMapThread, self).__init__(q, protocol_name='OpenSenseMap', manager_dict=manager_dict, post_interval=post_interval, max_backlog=max_backlog, stale=stale, log_success=log_success, log_failure=log_failure, max_tries=max_tries, timeout=timeout, retry_wait=retry_wait, skip_upload=skip_upload) self.SensorId = SensorId self.AuthKey = AuthKey self.server_url = server_url self.Sensors = Sensors self.UseUSUnits = to_bool(UsUnits) def get_record(self, record, dbm): rec = super(OpenSenseMapThread, self).get_record(record, dbm) # put everything into the right units if not self.UseUSUnits : rec = weewx.units.to_METRIC(rec) return rec def check_response(self, response): for line in response: if not line.decode().startswith('"Measurements saved in box"'): raise weewx.restx.FailedPost("Server response: %s" % line.decode()) else: return def format_url(self, record): logdbg("record: %s" % record) url = self.server_url + '/boxes/'+ self.SensorId + '/data' if weewx.debug >= 2: loginf('url: %s' % re.sub(r"s\/.*\/", "s/XXXXXXXXXXXXXX/", url)) return url def get_post_body(self, record): # @UnusedVariable """Return any POST payload. The returned value should be a 2-way tuple. First element is the Python object to be included as the payload. Second element is the MIME type it is in (such as "application/json"). Return a simple 'None' if there is no POST payload. This is the default. """ Values={} f = weewx.units.Formatter() for SensorName in self.Sensors: Sensor=self.Sensors[SensorName] if SensorName in record and not record[SensorName] is None: ug = weewx.units._getUnitGroup(SensorName) if self.UseUSUnits: un=weewx.units.USUnits[ug] else: un=weewx.units.MetricUnits[ug] if 'Unit' in Sensor: RecordValue=weewx.units.convert((record[SensorName],un),Sensor['Unit'])[0] else: RecordValue=record[SensorName] if 'Format' in Sensor: FormattedValue=Sensor['Format']%(RecordValue) else: FormattedValue=f.get_format_string(un)%(RecordValue) Values[Sensor['SensorId']]=FormattedValue RetVal = json.dumps(Values, ensure_ascii=False) print('OpenSenseMap : Body Encoded as **%s**'% (RetVal)) return RetVal, 'application/json' def handle_exception(self, e, count): """Check exception from HTTP post. This simply logs the exception.""" loginf("%s: Failed upload attempt %d: %s" % (self.protocol_name, count, e)) def get_request(self, url): """Get a request object. This can be overridden to add any special headers.""" _request = urllib.request.Request(url) _request.add_header("User-Agent", "weewx/%s" % weewx.__version__) _request.add_header("Authorization", self.AuthKey) return _request # Do direct testing of this extension like this: # PYTHONPATH=WEEWX_BINDIR python WEEWX_BINDIR/user/OpenSenseMap.py if __name__ == "__main__": import optparse import weewx.manager weewx.debug = 2 try: # WeeWX V4 logging weeutil.logger.setup('OpenSenseMap', {}) except NameError: # WeeWX V3 logging syslog.openlog('OpenSenseMap', syslog.LOG_PID | syslog.LOG_CONS) syslog.setlogmask(syslog.LOG_UPTO(syslog.LOG_DEBUG)) usage = """%prog --id=StationID --AuthKey=AuthKey [--version] [--help]""" parser = optparse.OptionParser(usage=usage) parser.add_option('--version', dest='version', action='store_true', help='display driver version') parser.add_option('--id', metavar='OpenSenseMap_ID', help='Your SensorBox ID') parser.add_option('--AuthKey', metavar='OpenSenseMap_AuthSecret', help='Auth Key to upload') #parser.add_option('--pw', dest='pw', metavar='PASSWORD', help='your password') (options, args) = parser.parse_args() manager_dict = { 'manager': 'weewx.manager.DaySummaryManager', 'table_name': 'archive', 'schema': None, 'database_dict': { 'SQLITE_ROOT': '/home/weewx/archive', 'database_name': 'weewx.sdb', 'driver': 'weedb.sqlite' } } if options.version: print("meteotemplate uploader version %s" % VERSION) exit(0) if options.id == None: print("Wrong params run : "+ usage ) exit(0) else: print("uploading to station %s" % options.id) Sensors={'windSpeed':{'SensorId':'603b5c4d2c4a41001b8db744','Unit':"km_per_hour",'Format':'%.2f'},} q = queue.Queue() t = OpenSenseMapThread(q,Sensors,options.id,options.AuthKey,False, manager_dict) t.start() q.put({'dateTime': int(time.time() + 0.5), 'usUnits': weewx.US, 'outTemp': 51.26, 'inTemp': 75.8, 'outHumidity': 72, 'windSpeed': 8, 'windDir':331}) q.put(None) t.join(20)
4e6fdf8202b61825464fe14064d161bc996bc0e9
[ "Markdown", "Python" ]
3
Python
sbsrouteur/weewx-opensensemap
996b9a53bf782b015dfdec43051831855833b602
1329e05150e84259e7b685ee85d647587bc8878a
refs/heads/master
<file_sep>/* Encrypts the text with the Caesar algorithm */ /* Build: gcc ../../vendor/cs50.c caesar.c -o caesar */ /* Usage example: caesar 13 plaintext: hello ciphertext: uryyb */ #include <stdio.h> #include "../../vendor/cs50.h" #include <string.h> #include <stdlib.h> void print_cipher_character(int letter_code, int key, int max_letter_code); int main(int argc, string argv[]) { if (argc != 2) { printf("Wrong arguments number"); return 1; } for (int i = 0, length = strlen(argv[1]); i < length; i++) { int letter_code = argv[1][i]; if (letter_code < 48 || letter_code > 57) { printf("Usage: ./caesar key"); return 1; } } int key = atoi(argv[1]); string plaintext = get_string("plaintext: "); printf("ciphertext: "); for (int i = 0, length = strlen(plaintext); i < length; i++) { int letter_code = (int)plaintext[i]; if ((letter_code >= 65 && letter_code <= 90)) { print_cipher_character(letter_code, key, 90); } else if ((letter_code >= 97 && letter_code <= 122)) { print_cipher_character(letter_code, key, 122); } else { printf("%c", plaintext[i]); } } return 0; } void print_cipher_character(int letter_code, int key, int max_letter_code) { int cipher_index = letter_code + key % 26; if (cipher_index > max_letter_code) { cipher_index -= 26; } printf("%c", (char)cipher_index); }<file_sep># CS50 Mashup A small web application that combines Google Maps API, Google News API and database with geo data. Map tags displaying current local news according to geodata. Autocomplete implemented with Twitter Typeahead.js. ### Screenshots: <img src="/pset8/readme/screen1.jpg" alt="Screenshot 1" width="400"/> <img src="/pset8/readme/screen2.jpg" alt="Screenshot 2" width="400"/><file_sep><?php require("../includes/config.php"); $id = get_user_id(); if ($_SERVER["REQUEST_METHOD"] == "GET") { render("buy_form.php", ["title" => "Buy"]); } else if ($_SERVER["REQUEST_METHOD"] == "POST") { if (empty($_POST["symbol"])) { apologize("Symbol can't be empty."); } if (empty($_POST["shares"])) { apologize("Shares can't be empty."); } if (!preg_match("/^\d+$/", $_POST["shares"])) { apologize("Shares must be positive integer."); } $cash_query = CS50::query("SELECT cash FROM users WHERE id = ?", $id); if (count($cash_query) != 1) { apologize("User not finded."); } $stock = lookup($_POST["symbol"]); if (!$stock) { apologize("Symbol not finded."); } $cost = $stock["price"] * $_POST["shares"]; $cash = $cash_query[0]["cash"] - $cost; if ($cash < 0) { apologize("You don't have enought money."); } CS50::query( "UPDATE users SET cash = ? WHERE id = ?", $cash, $id ); CS50::query( "INSERT INTO portfolios (user_id, symbol, shares) VALUES(?, ?, ?) ON DUPLICATE KEY UPDATE shares = shares + VALUES(shares)", $id, strtoupper($_POST["symbol"]), $_POST["shares"] ); CS50::query( "INSERT INTO history (user_id, action, symbol, shares, price, time) VALUES(?, ?, ?, ?, ?, CURRENT_TIMESTAMP())", $id, "buy", strtoupper($_POST["symbol"]), $_POST["shares"], $stock["price"] ); $report = [ "shares" => $_POST["shares"], "symbol" => $_POST["symbol"], "cost" => $cost, "cash" => $cash ]; render( "buy_report.php", [ "title" => "Buy report", "report" => $report ] ); } <file_sep><div class="container"> <table class ="tab"> <tr class="tab-title"> <td>action</td> <td>symbol</td> <td>shares</td> <td>price</td> <td>date</td> <td>time</td> </tr> <?php foreach ($positions as $position): ?> <tr> <td><?= htmlspecialchars($position["action"]) ?></td> <td><?= htmlspecialchars($position["symbol"]) ?></td> <td><?= htmlspecialchars($position["shares"]) ?></td> <td><?= htmlspecialchars($position["price"]) ?></td> <td><?= htmlspecialchars($position["date"]) ?></td> <td><?= htmlspecialchars($position["time"]) ?></td> </tr> <?php endforeach ?> </table> </div> <file_sep>/* Encrypts the text with a key */ /* Usage example: substitution VCHPRZGJNTLSKFBDQWAXEUYMOI plaintext: Hello ciphertext: Jrssb */ /* Build: gcc ../../vendor/cs50.c substitution.c -o substitution */ #include "../../vendor/cs50.h" #include <stdio.h> #include <ctype.h> #include <string.h> int main(int argc, string argv[]) { if (argc != 2) { printf("Wrong arguments number"); return 1; } string key = argv[1]; int key_length = strlen(argv[1]); if (key_length != 26) { printf("key must contain 26 characters"); return 1; } for (int i = 0; i < key_length; i++) { if (!isalpha(key[i])) { printf("Your input is not alphabetical.\n"); return 1; } for (int j = 0; j < key_length; j++) { if (tolower(key[i]) == tolower(key[j]) && i != j) { printf("Your key must containing each letter exactly once.\n"); return 1; } } } string plaintext = get_string("plaintext: "); printf("ciphertext: "); for (int i = 0, text_length = strlen(plaintext); i < text_length; i++) { if (isalpha(plaintext[i])) { int key_index = (tolower(plaintext[i]) - 97); if (islower(plaintext[i])) { printf("%c", (char)tolower((int)key[key_index])); } else { printf("%c", (char)toupper((int)key[key_index])); } } else { printf("%c", plaintext[i]); } } printf("\n"); return 0; }<file_sep><?php require("../includes/config.php"); $id = get_user_id(); if ($_SERVER["REQUEST_METHOD"] == "GET") { $portfolios = CS50::query("SELECT * FROM portfolios WHERE user_id = ?", $id); if (count($portfolios) == 0) { render( "report.php", [ "title" => "Sell", "header" => "Empty", "message" => "You don't have stocks to sell." ] ); } $positions = []; foreach ($portfolios as $portfolio) { $stock = lookup($portfolio["symbol"]); if (!$stock) { apologize("Symbol not finded."); } $positions[] = [ "name" => $stock["name"], "price" => $stock["price"], "shares" => number_format($portfolio["shares"], 2, '.', ''), "symbol" => $portfolio["symbol"] ]; } render( "sell_form.php", [ "title" => "Sell", "positions" => $positions ] ); } else if ($_SERVER["REQUEST_METHOD"] == "POST") { if (empty($_POST["symbol"])) { apologize("Symbol not selected."); } $symbol = $_POST["symbol"]; if (empty($_POST["shares"])) { apologize("Shares not selected."); } $sell_shares = $_POST["shares"]; if ($sell_shares <= 0) { apologize("Shares value invalid."); } $stock = lookup($symbol); if (!$stock) { apologize("Symbol not finded."); } $price = $stock["price"]; if ($price <= 0) { apologize("Price invalid."); } $portfolio = CS50::query( "SELECT * FROM portfolios WHERE user_id = ? AND symbol = ?", $id, $symbol ); if (count($portfolio) != 1) { apologize("Price invalid."); } $user = CS50::query("SELECT * FROM users WHERE id = ?", $id); if (count($user) != 1) { apologize("User is not found."); } $shares_left = $portfolio[0]["shares"] - $sell_shares; if ($shares_left < 0) { apologize("You trying sell more shares than have."); } $cash_gain = $sell_shares * $price; $cash = $user[0]["cash"] + $cash_gain; $cash_update_result = CS50::query( "UPDATE users SET cash = ? WHERE id = ?", $cash, $id ); if ($cash_update_result == 0) { apologize("Transaction failed."); } if ($shares_left > 0) { CS50::query( "UPDATE portfolios SET shares = ? WHERE user_id = ? AND symbol = ?", $shares_left, $id, $symbol ); } else { CS50::query( "DELETE FROM portfolios WHERE user_id = ? AND symbol = ?", $id, $symbol ); } CS50::query( "INSERT INTO history (user_id, action, symbol, shares, price, time) VALUES(?, ?, ?, ?, ?, CURRENT_TIMESTAMP())", $id, "sell", strtoupper($symbol), $sell_shares, $price ); render( "sell_report.php", [ "title" => "Index", "shares" => $sell_shares, "cash_gain" => $cash_gain, "cash_updated" => $cash ] ); } <file_sep>#!/usr/bin/env php <?php require(__DIR__ . "/../includes/config.php"); if ($argc!=2){ print("usage example: import ../db/us.txt"); exit(1); } $file = $argv[1]; if (!file_exists($file)){ print("File {$file} not finded"); exit(1); } $handle = fopen($file, "r"); if (!$handle) { print("Can't open file {$file}"); exit(1); } $added = 0; $lines = 0; while(1){ $line = fgets ($handle); if (!$line) { break; } $lines++; $place = explode("\t",$line); if (count($place)==12) { $rows = CS50::query( "INSERT INTO places (country_code, postal_code, place_name, admin_name1, admin_code1, admin_name2, admin_code2, admin_name3, admin_code3, latitude, longitude, accuracy) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", $place[0], $place[1], $place[2], $place[3], $place[4], $place[5], $place[6], $place[7], $place[8], $place[9], $place[10], $place[11] ); if ($rows == 1){ $added++; } } } fclose($handle); print("Readed {$lines} lines\n"); print("Added to DB {$added} places\n"); ?><file_sep>/* Assesses the difficulty of reading the text */ /* Build: gcc ../../vendor/cs50.c readability.c -o readability */ /* Usage example: input: Simple text. output: Before Grade 1 */ #include <stdio.h> #include "../../vendor/cs50.h" #include <string.h> #include <math.h> int main(void) { string s = get_string("Text: "); int letters = 0; int words = 0; int sentences = 0; for (int i = 0, length = strlen(s); i < length; i++) { int letter_code = (int)s[i]; if ((letter_code >= 97 && letter_code <= 122) || (letter_code >= 65 && letter_code <= 90)) { letters++; } else if (letter_code == 32) { words++; } else if (letter_code == 33 || letter_code == 46 || letter_code == 63) { sentences++; } } if (letters > 0) { words++; } float L = (letters * 100) / words; float S = (sentences * 100) / words; int grade = round(0.0588 * L - 0.296 * S - 15.8); if (grade < 1) { printf("Before Grade 1\n"); } else if (grade > 16) { printf("Grade 16+\n"); } else { printf("Grade %i\n", grade); } }<file_sep>/* The application restores jpg images from a copy of the card */ /* Usage: recover card.raw */ #include <stdio.h> #include <stdlib.h> #include <stdint.h> typedef uint8_t BYTE; int main(int argc, char *argv[]) { if (argc != 2) { printf("Usage: recover file\n"); return 1; } char *infile = argv[1]; char outfile[8]; FILE *outptr; FILE *inptr; BYTE buffer[512]; int files = 0; int is_outfile_exist = 0; inptr = fopen(infile, "r"); if (inptr == NULL) { fprintf(stderr, "Could not open %s.\n", infile); return 1; } while (fread(buffer, sizeof(BYTE), 512, inptr)) { if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0) { if (is_outfile_exist) { fclose(outptr); } sprintf(outfile, "%03i.jpg", files); outptr = fopen(outfile, "w"); if (outptr == NULL) { fclose(inptr); fprintf(stderr, "Could not create %s.\n", outfile); return 1; } is_outfile_exist = 1; files++; } if (is_outfile_exist) { fwrite(buffer, sizeof(BYTE) * 512, 1, outptr); } } if (files > 0) { fclose(outptr); } fclose(inptr); return 0; }<file_sep><?php /* Search matches in db for autocomplete location */ require(__DIR__ . "/../includes/config.php"); $query_limit = 20; function send_search_result($places = []) { header("Content-type: application/json"); print(json_encode($places, JSON_PRETTY_PRINT)); exit; } if (!isset($_GET['geo'], $_GET['geo'])) { http_response_code(400); exit; } /* First, we look for a match of a key with one field. If nothing is found, we expand the search, looking for less exact matches. */ $key = trim($_GET['geo']); $rows = CS50::query( "SELECT * FROM places WHERE country_code=? OR postal_code=? OR place_name LIKE ? OR admin_name1 LIKE ? OR admin_code1=? LIMIT {$query_limit};", $key, $key, $key . "%", $key . "%", $key ); if (count($rows) > 0) { send_search_result($rows); } $key = trim(str_replace(", ", "*, ", $_GET["geo"])) . "*"; $rows = CS50::query( "SELECT * FROM places WHERE MATCH(country_code, postal_code, place_name, admin_name1, admin_code1) AGAINST(? IN BOOLEAN MODE) LIMIT {$query_limit};", $key ); send_search_result($rows);<file_sep>/* Draws a pyramids of a given height */ /* Build: gcc ../../vendor/cs50.c mario.c -o mario */ #include <stdio.h> #include "../../vendor/cs50.h" int main(void) { int height; do { height = get_int("Height: "); } while (height < 1 || height > 8); int line_length = (height * 2) + 2; for (int i = 0; i < height; i++) { for (int j = 0; j <= line_length; j++) { if ((j >= (height - i - 1) && j < height) || (j <= (height + 2 + i) && (j >= (height + 2)))) { printf("#"); } else { printf(" "); } } if (i != height - 1) { printf("\n"); } } }<file_sep>#include "helpers.h" #include <stdio.h> #include <math.h> // Convert image to grayscale void grayscale(int height, int width, RGBTRIPLE image[height][width]) { RGBTRIPLE pixel; int average; for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { pixel = image[j][i]; average = round((pixel.rgbtBlue + pixel.rgbtGreen + pixel.rgbtRed) / 3); pixel.rgbtBlue = average; pixel.rgbtGreen = average; pixel.rgbtRed = average; image[j][i] = pixel; } } return; } // Reflect image horizontally void reflect(int height, int width, RGBTRIPLE image[height][width]) { RGBTRIPLE pixel, tmp; int middle = round(width / 2); for (int i = 0; i < height; i++) { for (int j = 0; j < middle; j++) { pixel = image[i][j]; tmp = image[i][width - j]; image[i][width - j] = pixel; image[i][j] = tmp; } } return; } RGBTRIPLE blur_pixel(int i, int j, int height, int width, RGBTRIPLE image[height][width]) { int r = 0; int g = 0; int b = 0; int pixels = 0; RGBTRIPLE point; for (int y = i - 1; y <= i + 1; y++) { for (int x = j - 1; x <= j + 1; x++) { if (y >= 0 && y < height && x >= 0 && x < width) { point = image[y][x]; r += point.rgbtRed; g += point.rgbtGreen; b += point.rgbtBlue; pixels++; } } } point.rgbtRed = round(r / pixels); point.rgbtGreen = round(g / pixels); point.rgbtBlue = round(b / pixels); return point; } // Blur image void blur(int height, int width, RGBTRIPLE image[height][width]) { RGBTRIPLE pixel, tmp; //so that blurry pixels do not affect the rest, save them first in a temporary image RGBTRIPLE tmp_image[height][width]; for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { tmp_image[i][j] = blur_pixel(i, j, height, width, image); } } for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { image[i][j] = tmp_image[i][j]; } } return; } int sobel(int gx, int gy) { int color = round(sqrt(pow(gx, 2) + pow(gy, 2))); if (color > 255) { return 255; } return color; } RGBTRIPLE edge_pixel(int i, int j, int height, int width, RGBTRIPLE image[height][width]) { int rate_x[9] = {-1, 0, 1, -2, 0, 2, -1, 0, 1}; int rate_y[9] = {-1, -2, -1, 0, 0, 0, 1, 2, 1}; int rate_index = 0; int gx_r = 0; int gx_g = 0; int gx_b = 0; int gy_r = 0; int gy_g = 0; int gy_b = 0; RGBTRIPLE point; for (int y = i - 1; y <= i + 1; y++) { for (int x = j - 1; x <= j + 1; x++) { if (y >= 0 && y < height && x >= 0 && x < width) { point = image[y][x]; gx_r += point.rgbtRed * rate_x[rate_index]; gx_g += point.rgbtGreen * rate_x[rate_index]; gx_b += point.rgbtBlue * rate_x[rate_index]; gy_r += point.rgbtRed * rate_y[rate_index]; gy_g += point.rgbtGreen * rate_y[rate_index]; gy_b += point.rgbtBlue * rate_y[rate_index]; } rate_index++; } } point.rgbtRed = sobel(gx_r, gy_r); point.rgbtGreen = sobel(gx_g, gy_g); point.rgbtBlue = sobel(gx_b, gy_b); return point; } // Detect edges void edges(int height, int width, RGBTRIPLE image[height][width]) { RGBTRIPLE pixel, tmp; //so that modified pixels do not affect the rest, save them first in a temporary image RGBTRIPLE tmp_image[height][width]; for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { tmp_image[i][j] = edge_pixel(i, j, height, width, image); } } for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { image[i][j] = tmp_image[i][j]; } } return; } <file_sep>### Problem sets from Harvard's online course CS50<file_sep><div class="container"> <h3>Sold</h3> <p><?= "You successfully sold {$shares} shares." ?></p> <p><?= "{$cash_gain}$ obtained." ?></p> <p><?= "Current cash: {$cash_updated}$." ?></p> </div> <file_sep><?php require("../includes/config.php"); if ($_SERVER["REQUEST_METHOD"] == "GET") { render("change_password.php", ["title" => "change password"]); } else if ($_SERVER["REQUEST_METHOD"] == "POST") { if (empty($_POST["new_password"])) { apologize("You must provide new password."); } else if (empty($_POST["old_password"])) { apologize("You must provide old password."); } else if ($_POST["new_password"]!=$_POST["confirmation"]) { apologize("Password must be equal to confirmation."); } $id = get_user_id(); $rows = CS50::query("SELECT * FROM users WHERE id = ?", $id); if (count($rows) == 1) { $user = $rows[0]; if (password_verify($_POST["old_password"], $user["hash"])) { $new_hash = password_hash($_POST["new_password"], PASSWORD_DEFAULT); $update_query_result = CS50::query( "UPDATE users SET hash = ? WHERE id = ?", $new_hash, $id ); if (count($update_query_result) == 1) { render( "report.php", [ "title" => "Password changed!", "header" => "Success!", "message"=> "Password was successfuly changed." ] ); } } } apologize("Failed to change password."); } ?> <file_sep># CS50 Finance(PHP version) A small web application for stock trading with several features: * getting stock price through Alphavantage API * storing user data in the database * "buy"/"sell" shares * transactions history * user registration * password change/restore ### Screenshots: <img src="/pset7/readme/screen1.jpg" alt="Screenshot 1" width="400"/> <img src="/pset7/readme/screen2.jpg" alt="Screenshot 2" width="400"/><file_sep>/* App determine the minimum number of coins required to issue change */ /* Build command: gcc ../../vendor/cs50.c cash.c -o cash */ #include <stdio.h> #include "../../vendor/cs50.h" #include <math.h> int main(void) { float dollars; do { dollars = get_float("Change owed: "); } while (dollars < 0); int cents = round(dollars * 100); int coins = 0; while (cents > 0) { if (cents >= 25) { cents -= 25; } else if (cents >= 10) { cents -= 10; } else if (cents >= 5) { cents -= 5; } else { cents -= 1; } coins++; } printf("%i\n", coins); }<file_sep><div class="container"> <h1>Bought</h1> <p><?= "You successfully bought ".htmlspecialchars($report["shares"])." shares of ".htmlspecialchars($report["symbol"])."." ?></p> <p><?= "Cash spended: ".htmlspecialchars($report["cost"])."$." ?></p> <p><?= "Current balance: ".htmlspecialchars($report["cash"])."$." ?></p> </div> <file_sep><?php require("../includes/config.php"); if ($_SERVER["REQUEST_METHOD"] == "GET") { render("restore_password.php", ["title" => "Settings"]); } else if ($_SERVER["REQUEST_METHOD"] == "POST") { if (empty($_POST["username"])) { apologize("You must provide your username."); } if (empty($_POST["email"])) { apologize("You must provide your email."); } $user = CS50::query("SELECT * FROM users WHERE username = ?", $_POST["username"]); if (count($user) != 1) { apologize("Username invalid."); } $user_email = $user[0]["email"]; if ($user_email !== $_POST["email"]) { apologize("Email invalid."); } if (empty($user_email) || $user_email == NULL) { apologize("Your account dont have email for restore."); } $pwd = bin2hex(openssl_random_pseudo_bytes(4)); $pwd_hash = password_hash($pwd, PASSWORD_DEFAULT); $subject = "Password reseted!"; $message = "Your password was reseted. New password: <PASSWORD>}"; $is_mail_delivered = mail($user_email, $subject, $message); if (!$is_mail_delivered ) { apologize("Failed to deliver mail."); } CS50::query( "UPDATE users SET hash = ? WHERE id = ?", $pwd_hash, $user[0]["id"] ); render( "report.php", [ "title" => "Password reseted!", "header" => "Password reseted!", "message"=> "Password was reseted, new password sent to your email." ] ); } ?><file_sep><div class="container"> <table class ="tab"> <tr class="tab-title"> <td>symbol</td> <td>shares</td> <td>price</td> </tr> <?php foreach ($positions as $position): ?> <tr> <td><?= htmlspecialchars($position["symbol"]) ?></td> <td><?= htmlspecialchars($position["shares"]) ?></td> <td><?= htmlspecialchars($position["price"])."$" ?></td> </tr> <?php endforeach ?> <tr> <td>cash:</td> <td colspan="2" class="al-right"> <?= htmlspecialchars($cash)."$"?></td> </tr> <tr> <td>total:</td> <td colspan="2" class="al-right"> <?= htmlspecialchars($total)."$"?></td> </tr> </table> </div> <file_sep><div class="container"> <form action="sell.php" method="post"> <select class="form-item" name="symbol"> <option disabled>Choose symbol</option> <?php foreach ($positions as $position): ?> <option value="<?= htmlspecialchars($position["symbol"]) ?>"> <?= htmlspecialchars($position["name"])." (".htmlspecialchars($position["shares"])."x".htmlspecialchars($position["price"])."$)" ?> </option> <?php endforeach ?> </select> <input class="form-item" type="number" name="shares" min="0"value="0"> <input class="form-item" type="submit" value="Sell"> </form> </div><file_sep>-- phpMyAdmin SQL Dump -- version 4.0.8 -- http://www.phpmyadmin.net -- -- Host: 127.0.0.1:3306 -- Generation Time: Mar 08, 2021 at 04:16 AM -- Server version: 5.1.71-community-log -- PHP Version: 5.5.4 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; -- -- Database: `pset7` -- -- -------------------------------------------------------- -- -- Table structure for table `history` -- CREATE TABLE IF NOT EXISTS `history` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `user_id` int(10) unsigned NOT NULL, `action` varchar(255) NOT NULL, `symbol` varchar(255) NOT NULL, `shares` decimal(65,4) unsigned NOT NULL, `price` decimal(65,4) unsigned NOT NULL, `time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`id`), UNIQUE KEY `id` (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=27 ; -- -- Dumping data for table `history` -- INSERT INTO `history` (`id`, `user_id`, `action`, `symbol`, `shares`, `price`, `time`) VALUES (18, 20, 'buy', 'IBM', '20.0000', '122.5200', '2021-03-07 22:21:28'), (19, 20, 'buy', 'FREE', '15.0000', '12.6000', '2021-03-07 22:21:39'), (20, 20, 'sell', 'IBM', '4.0000', '122.5200', '2021-03-07 22:22:03'), (21, 20, 'sell', 'IBM', '1.0000', '122.5200', '2021-03-07 22:22:13'), (22, 20, 'buy', 'IBM', '10.0000', '122.5200', '2021-03-07 22:22:25'), (23, 20, 'buy', 'IBM', '2.0000', '122.5200', '2021-03-07 23:40:30'), (24, 20, 'sell', 'FREE', '1.0000', '12.6000', '2021-03-07 23:41:18'), (25, 20, 'buy', 'IBM', '2.0000', '122.5200', '2021-03-08 00:10:48'), (26, 20, 'sell', 'FREE', '4.0000', '12.6000', '2021-03-08 00:10:59'); -- -------------------------------------------------------- -- -- Table structure for table `portfolios` -- CREATE TABLE IF NOT EXISTS `portfolios` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `user_id` int(10) unsigned NOT NULL, `symbol` varchar(255) NOT NULL, `shares` decimal(65,4) unsigned NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `id` (`id`), UNIQUE KEY `user_id` (`user_id`,`symbol`), UNIQUE KEY `user_id_2` (`user_id`,`symbol`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=25 ; -- -- Dumping data for table `portfolios` -- INSERT INTO `portfolios` (`id`, `user_id`, `symbol`, `shares`) VALUES (20, 20, 'IBM', '29.0000'), (21, 20, 'FREE', '10.0000'); -- -------------------------------------------------------- -- -- Table structure for table `users` -- CREATE TABLE IF NOT EXISTS `users` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `username` varchar(255) NOT NULL, `hash` varchar(255) NOT NULL, `cash` decimal(65,4) unsigned NOT NULL DEFAULT '0.0000', `email` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `username` (`username`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=21 ; -- -- Dumping data for table `users` -- INSERT INTO `users` (`id`, `username`, `hash`, `cash`, `email`) VALUES (1, 'andi', '$2y$10$c.e4DK7pVyLT.stmHxgAleWq4yViMmkwKz3x8XCo4b/u3r8g5OTnS', '10000.0000', NULL), (2, 'caesar', '$2y$10$0p2dlmu6HnhzEMf9UaUIfuaQP7tFVDMxgFcVs0irhGqhOxt6hJFaa', '10000.0000', NULL), (3, 'eli', '$2y$10$COO6EnTVrCPCEddZyWeEJeH9qPCwPkCS0jJpusNiru.XpRN6Jf7HW', '11500.0000', NULL), (4, 'hdan', '$2y$10$o9a4ZoHqVkVHSno6j.k34.wC.qzgeQTBHiwa3rpnLq7j2PlPJHo1G', '10000.0000', NULL), (5, 'jason', '$2y$10$ci2zwcWLJmSSqyhCnHKUF.AjoysFMvlIb1w4zfmCS7/WaOrmBnLNe', '10000.0000', NULL), (6, 'john', '$2y$10$dy.LVhWgoxIQHAgfCStWietGdJCPjnNrxKNRs5twGcMrQvAPPIxSy', '10000.0000', NULL), (7, 'levatich', '$2y$10$fBfk7L/QFiplffZdo6etM.096pt4Oyz2imLSp5s8HUAykdLXaz6MK', '10000.0000', NULL), (8, 'rob', '$2y$10$3pRWcBbGdAdzdDiVVybKSeFq6C50g80zyPRAxcsh2t5UnwAkG.I.2', '10000.0000', NULL), (9, 'skroob', '$2y$10$jhQWywLaQojJo8tGWOAWauTXue5De2WtTymKEp.aSy.DExXo/vbU6', '1129.4700', NULL), (10, 'zamyla', '$2y$10$UOaRF0LGOaeHG4oaEkfO4O7vfI34B1W23WqHr9zCpXL68hfQsS3/e', '10000.0000', NULL), (20, 'test', '$2y$10$qYcyifCabWUmsecZQUaGQuiuiRrd4zw14XIYJmFFkvlX7G/mEPmui', '6320.9200', ''); /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep>// Helper functions for music #include "helpers.h" #include <string.h> #include <stdio.h> #include <math.h> #include <ctype.h> #include <stdlib.h> // Converts a fraction formatted as X/Y to eighths int duration(string fraction) { int numerator = (int)fraction[0] - 48; int denominator = (int)fraction[2]- 48; int duration = numerator * (8/denominator); return duration; } // Calculates frequency (in Hz) of a note int frequency(string note) { const string BASE_NOTES[] = {"C", "D", "E", "F", "G", "A", "B"}; // Difference semitons from A to note from BASE_NOTES const int semitones_from_A[] = {-9, -7, -5, -4, -2, 0, 2}; const int A4_FREQUENCY = 440; int note_letter = toupper(note[0]); int current_letter; int is_note_finded = 0; int semitones = 0; for (int i = 0, n = sizeof(BASE_NOTES) / sizeof(string); i < n; i++) { current_letter = (int) BASE_NOTES[i][0]; if (current_letter == note_letter) { is_note_finded = 1; semitones = semitones_from_A[i]; } } if (!is_note_finded) { printf("Incorect note input\n"); } if (note[1] == '#') { semitones++; } if (note[1] == 'b') { semitones--; } int octave; if (isdigit(note[1])) { octave = (int)note[1] - 48; } else { octave = (int)note[2] - 48; } double frequency = A4_FREQUENCY; double exponent = (double) abs(semitones)/12; if (semitones>=0) { frequency *= pow(2.0, exponent); }else { frequency /= pow(2.0, exponent); } if (octave>4) { frequency*=pow(2.0, (double)(octave-4)); } else { frequency/=pow(2.0, (double)(4-octave)); } return (int)frequency; } // Determines whether a string represents a rest bool is_rest(string s) { if (s[0]=='\0' || s[0]=='\r' || s[0]=='\n') { return true; } return false; } <file_sep><h3><?= htmlspecialchars($header) ?></h3> <p><?= htmlspecialchars($message) ?></p> <file_sep>/* global google */ /* global _ */ /** * scripts.js * * Computer Science 50 * Problem Set 8 * * Global JavaScript. */ // Google Map let map; // markers for map let markers = []; //remember last marker for close window instead of reopening let prevMarker = false; // info window let info = new google.maps.InfoWindow(); let news = []; let newsStart = 0; let newsLimit = 5; // execute when the DOM is fully loaded $(function () { // styles for map // https://developers.google.com/maps/documentation/javascript/styling let styles = [ // hide Google's labels { featureType: "all", elementType: "labels", stylers: [ { visibility: "off" } ] }, // hide roads { featureType: "road", elementType: "geometry", stylers: [ { visibility: "off" } ] } ]; // options for map // https://developers.google.com/maps/documentation/javascript/reference#MapOptions let options = { center: { lat: 42.3770, lng: -71.1256 }, disableDefaultUI: true, mapTypeId: google.maps.MapTypeId.ROADMAP, maxZoom: 14, panControl: true, styles: styles, zoom: 13, zoomControl: true }; // get DOM node in which map will be instantiated let canvas = $("#map-canvas").get(0); // instantiate map map = new google.maps.Map(canvas, options); // configure UI once Google Map is idle (i.e., loaded) google.maps.event.addListenerOnce(map, "idle", configure); }); function getMarkerClickHandler(marker) { return () => { if (prevMarker == marker) { if (isInfoWindowOpen()) { hideInfo(); } else { info.open(map, marker); } } else { hideInfo(); info.setContent("<div id='info'><img alt='loading' src='img/ajax-loader.gif'/><div>"); info.open(map, marker); newsStart = 0; loadArticles(marker.postal_code, refreshInfowindowData); } prevMarker = marker; }; } function addMarker(place) { let myLatlng = new google.maps.LatLng(place.latitude, place.longitude); let marker = new google.maps.Marker({ position: myLatlng, title: place.place_name, postal_code: place.postal_code, }); marker.addListener("click", getMarkerClickHandler(marker)); marker.setMap(map); markers.push(marker); } /** * Configures application. */ function configure() { // update UI after map has been dragged google.maps.event.addListener(map, "dragend", function () { update(); }); // update UI after zoom level changes google.maps.event.addListener(map, "zoom_changed", function () { update(); }); // configure typeahead // https://github.com/twitter/typeahead.js/blob/master/doc/jquery_typeahead.md $("#q").typeahead({ autoselect: true, highlight: true, minLength: 1 }, { source: search, templates: { empty: "<p class='tip'>No places found yet</p>", suggestion: _.template("<p class='tip'><%- place_name %>, <%- admin_name1 %>, <%- postal_code %></p>") } }); // re-center map after place is selected from drop-down $("#q").on("typeahead:selected", function (eventObject, suggestion, name) { // ensure coordinates are numbers let latitude = (_.isNumber(suggestion.latitude)) ? suggestion.latitude : parseFloat(suggestion.latitude); let longitude = (_.isNumber(suggestion.longitude)) ? suggestion.longitude : parseFloat(suggestion.longitude); // set map's center map.setCenter({ lat: latitude, lng: longitude }); // update UI update(); }); // hide info window when text box has focus $("#q").focus(function (eventData) { hideInfo(); }); document.addEventListener("contextmenu", function (event) { event.returnValue = true; if (event.preventDefault != undefined) event.preventDefault(); if (event.stopPropagation != undefined) event.stopPropagation(); }, true); // update UI update(); // give focus to text box $("#q").focus(); } function hideInfo() { newsStart = 0; info.close(); } function removeMarkers() { markers.forEach(marker => { marker.setMap(null); }); markers = []; } /** * Searches database for typeahead's suggestions. */ function search(query, cb) { // get places matching query (asynchronously) let parameters = { geo: query }; $.getJSON("search.php", parameters) .done(function (data, textStatus, jqXHR) { // call typeahead's callback with search results (i.e., places) cb(data); }) .fail(function (jqXHR, textStatus, errorThrown) { console.log(errorThrown.toString()); }); } /** * Updates UI's markers. */ function update() { // get map's bounds let bounds = map.getBounds(); let ne = bounds.getNorthEast(); let sw = bounds.getSouthWest(); // get places within bounds (asynchronously) let parameters = { ne: ne.lat() + "," + ne.lng(), q: $("#q").val(), sw: sw.lat() + "," + sw.lng() }; $.getJSON("update.php", parameters) .done(function (data, textStatus, jqXHR) { removeMarkers(); for (let i = 0, len = data.length; i < len; i++) { addMarker(data[i]); } }) .fail(function (jqXHR, textStatus, errorThrown) { console.log(errorThrown.toString()); }); } function loadArticles(geo, cb) { let parameters = { geo: geo }; $.getJSON("articles.php", parameters) .done(function (data, textStatus, jqXHR) { cb(data); }) .fail(function (jqXHR, textStatus, errorThrown) { cb([]); }); } function getInfowindowContent(data, start) { let content = "<ul class='info-list'>"; for (let i = start, len = data.length; i < len && i < start + newsLimit; i++) { const article = data[i]; content += `<li><a href='${article.link}' target='_blank'>${article.title}</a></li>`; } content += "</ul>" if (data.length > start + newsLimit) { content += "<button onclick='moreNews()' type='button' class='btn btn-primary info-list-btn'>More</button>"; } else { content += "<button onclick='hideInfo()' type='button' class='btn btn-danger info-list-btn'>Close</button>"; } return content; } function refreshInfowindowData(data, start = 0) { news = data; let content = getInfowindowContent(data, start); info.setContent(content); } function moreNews() { if (newsStart < news.length - newsLimit) { newsStart += newsLimit; } else { newsStart = 0; } if (info) { refreshInfowindowData(news, newsStart); } } function isInfoWindowOpen() { let map = info.getMap(); return (map !== null && typeof map !== "undefined"); }<file_sep><?php require("../includes/config.php"); $id = get_user_id(); $user_history = CS50::query("SELECT * FROM history WHERE user_id = ?", $id); if (count($user_history)> 0){ $positions = []; foreach ($user_history as $row) { $splitTimeStamp = explode(" ", $row["time"]); $positions[] = [ "action" => $row["action"], "symbol" => $row["symbol"], "shares" => number_format($row["shares"], 2, '.', ''), "price" => number_format($row["price"], 2, '.', ''), "date" => $splitTimeStamp[0], "time" => $splitTimeStamp[1] ]; } render( "history.php", [ "title" => "History", "positions" => $positions ] ); } render( "report.php", [ "title" => "History", "header" => "History", "message"=> "History is empty." ] ); ?><file_sep>-- phpMyAdmin SQL Dump -- version 4.0.8 -- http://www.phpmyadmin.net -- -- Host: 127.0.0.1:3306 -- Generation Time: Mar 22, 2021 at 11:48 PM -- Server version: 5.1.71-community-log -- PHP Version: 5.5.4 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; -- -- Database: `pset8` -- -- -------------------------------------------------------- -- -- Table structure for table `places` -- CREATE TABLE IF NOT EXISTS `places` ( `id` int(11) NOT NULL AUTO_INCREMENT, `country_code` char(2) NOT NULL, `postal_code` varchar(20) NOT NULL, `place_name` varchar(180) NOT NULL, `admin_name1` varchar(100) NOT NULL, `admin_code1` varchar(20) NOT NULL, `admin_name2` varchar(100) NOT NULL, `admin_code2` varchar(20) NOT NULL, `admin_name3` varchar(100) NOT NULL, `admin_code3` varchar(20) NOT NULL, `latitude` decimal(7,4) NOT NULL, `longitude` decimal(7,4) NOT NULL, `accuracy` tinyint(4) NOT NULL, PRIMARY KEY (`id`), KEY `country_code` (`country_code`), KEY `postal_code` (`postal_code`), KEY `place_name` (`place_name`), KEY `admin_name1` (`admin_name1`), KEY `admin_code1` (`admin_code1`), KEY `admin_name2` (`admin_name2`), KEY `admin_code2` (`admin_code2`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep>/* Determines the type of payment card by number */ /* Usage example: input: 4003600000000014 output:VISA */ /* Build: gcc ../../vendor/cs50.c credit.c -o credit */ #include <stdio.h> #include "../../vendor/cs50.h" #include <math.h> int main(void) { long long number; do { number = get_long_long("Number: "); } while (number <= 999999999999 || number >= 10000000000000000); int digit; int last_summ_digit; int first_digit; int second_digit; int count = 0; int summ = 0; long long n = number; while (n >= 0) { //get digits from end of card number if (n > 10) { digit = n % 10; n = floor(n / 10); } else { digit = n; n = -1; } //count summ of digits if (count % 2 == 0) { summ += digit; } else { digit *= 2; if (digit < 10) { summ += digit; } else { summ = summ + floor(digit / 10) + (digit % 10); } } count++; last_summ_digit = summ % 10; } first_digit = number / (pow(10, (count - 1))); second_digit = number / (pow(10, (count - 2))) - first_digit * 10; if (last_summ_digit == 0 && count == 15 && first_digit == 3 && (second_digit == 4 || second_digit == 7)) { printf("AMEX\n"); } else if (last_summ_digit == 0 && count == 16 && first_digit == 5 && (second_digit >= 1 && second_digit <= 5)) { printf("MASTERCARD\n"); } else if (last_summ_digit == 0 && (count == 13 || count == 16) && first_digit == 4) { printf("VISA\n"); } else { printf("INVALID\n"); } }<file_sep><?php require("../includes/config.php"); if ($_SERVER["REQUEST_METHOD"] == "GET") { render("quote_form.php", ["title" => "Search symbol"]); } else if ($_SERVER["REQUEST_METHOD"] == "POST") { if (empty($_POST["symbol"])) { apologize("You must provide symbol."); } $stock = lookup($_POST["symbol"]); if (!$stock) { apologize("Symbol not finded."); } $price = number_format($stock["price"], 2, '.', ''); render( "quote.php", [ "title" => "Symbol information", "name" => $stock["name"], "price" =>$price ] ); } ?> <file_sep><?php require("../includes/config.php"); $id = get_user_id(); $user_cash = CS50::query("SELECT cash FROM users WHERE id = ?", $id); if (count($user_cash) == 0){ apologize("User not finded."); } $cash = number_format($user_cash[0]["cash"], 2, '.', ''); $portfolios = CS50::query("SELECT * FROM portfolios WHERE user_id = ?", $id); if (count($portfolios) == 0){ render( "report.php", [ "title" => "Portfolio", "header" => "Portfolio", "message"=> "Your portfolio is empty. Current balance: {$cash}$" ] ); } $total=0; $positions = []; foreach ($portfolios as $portfolio) { $stock = lookup($portfolio["symbol"]); if (!$stock) { apologize("Symbol not finded."); } $positions[] = [ "name" => $stock["name"], "price" => $stock["price"], "shares" => $portfolio["shares"], "symbol" => $portfolio["symbol"] ]; $total+=$stock["price"]*$portfolio["shares"]; } $total+=$cash; render( "portfolio.php", [ "positions" => $positions, "title" => "Portfolio", "cash"=>$cash, "total"=>$total ] ); ?> <file_sep><?php require("../includes/config.php"); if ($_SERVER["REQUEST_METHOD"] == "GET") { render("register_form.php", ["title" => "Register"]); } else if ($_SERVER["REQUEST_METHOD"] == "POST") { if (empty($_POST["username"])) { apologize("You must provide your username."); } else if (empty($_POST["password"])) { apologize("You must provide your password."); } else if ($_POST["password"]!=$_POST["confirmation"]) { apologize("Password must be equal to confirmation."); } //email must be empty or valid if (!empty($_POST["email"]) && !filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)) { apologize("Invalid email."); } $insert_query_result = CS50::query( "INSERT IGNORE INTO users (username, hash, cash, email) VALUES(?, ?, 10000.0000, ?)", $_POST["username"], password_hash($_POST["<PASSWORD>"], PASSWORD_DEFAULT), $_POST["email"] ); if($insert_query_result == 0){ apologize("Username already exists"); } $rows = CS50::query("SELECT LAST_INSERT_ID() AS id"); if (count($rows) == 1){ $_SESSION["id"] = $rows[0]["id"]; redirect("index.php"); } } ?>
95ca261a2fa68c8d79387b38f68003370d57b02d
[ "SQL", "Markdown", "JavaScript", "PHP", "C" ]
31
C
lytsy/cs50
17a88d5c2efa58227f785e51d2a0a491df88265f
1efe60ab6203d58fbfb4d54679400811ab534d33
refs/heads/2.1.x
<repo_name>denpamusic/php-bitcoinrpc<file_sep>/src/Responses/Response.php <?php declare(strict_types=1); namespace Denpa\Bitcoin\Responses; use Denpa\Bitcoin\Traits\Message; use Psr\Http\Message\ResponseInterface; abstract class Response implements ResponseInterface { use Message; /** * Response instance. * * @var \Psr\Http\Message\ResponseInterface */ protected $response; /** * Data container. * * @var array */ protected $container = []; /** * Constructs new json response. * * @param \Psr\Http\Message\ResponseInterface $response * * @return void */ public function __construct(ResponseInterface $response) { $this->response = $response; $this->container = json_decode((string) $response->getBody(), true); } /** * Gets raw response. * * @return \Psr\Http\Message\ResponseInterface */ public function response(): ResponseInterface { return $this->response; } /** * Sets response. * * @param \Psr\Http\Message\ResponseInterface $response * * @return self */ public function setResponse(ResponseInterface $response): self { $this->response = $response; return $this; } /** * Checks if response has error. * * @return bool */ public function hasError(): bool { return isset($this->container['error']); } /** * Gets error object. * * @return array|null */ public function error(): ?array { return $this->container['error'] ?? null; } /** * Checks if response has result. * * @return bool */ public function hasResult(): bool { return isset($this->container['result']); } /** * Gets result array. * * @return mixed */ public function result() { return $this->container['result'] ?? null; } /** * Get response status code. * * @return int */ public function getStatusCode(): int { return $this->response->getStatusCode(); } /** * Return an instance with the specified status code and, optionally, reason phrase. * * @param int $code * @param string $reasonPhrase * * @return self */ public function withStatus($code, $reasonPhrase = ''): self { $new = clone $this; return $new->setResponse( $this->response->withStatus($code, $reasonPhrase) ); } /** * Gets the response reason phrase associated with the status code. * * @return string */ public function getReasonPhrase(): string { return $this->response->getReasonPhrase(); } } <file_sep>/tests/FunctionsTest.php <?php namespace Denpa\Bitcoin\Tests; use Denpa\Bitcoin; use Denpa\Bitcoin\Exceptions\BadConfigurationException; use Denpa\Bitcoin\Exceptions\Handler as ExceptionHandler; class FunctionsTest extends TestCase { /** * Test satoshi to btc converter. * * @param int $satoshi * @param string $bitcoin * * @return void * * @dataProvider satoshiBtcProvider */ public function testToBtc(int $satoshi, string $bitcoin): void { $this->assertEquals($bitcoin, Bitcoin\to_bitcoin($satoshi)); } /** * Test bitcoin to satoshi converter. * * @param int $satoshi * @param string $bitcoin * * @return void * * @dataProvider satoshiBtcProvider */ public function testToSatoshi(int $satoshi, string $bitcoin): void { $this->assertEquals($satoshi, Bitcoin\to_satoshi($bitcoin)); } /** * Test bitcoin to ubtc/bits converter. * * @param int $ubtc * @param string $bitcoin * * @return void * * @dataProvider bitsBtcProvider */ public function testToBits(int $ubtc, string $bitcoin): void { $this->assertEquals($ubtc, Bitcoin\to_ubtc($bitcoin)); } /** * Test bitcoin to mbtc converter. * * @param float $mbtc * @param string $bitcoin * * @return void * * @dataProvider mbtcBtcProvider */ public function testToMbtc(float $mbtc, string $bitcoin): void { $this->assertEquals($mbtc, Bitcoin\to_mbtc($bitcoin)); } /** * Test float to fixed converter. * * @param float $float * @param int $precision * @param string $expected * * @return void * * @dataProvider floatProvider */ public function testToFixed( float $float, int $precision, string $expected ): void { $this->assertSame($expected, Bitcoin\to_fixed($float, $precision)); } /** * Test url parser. * * @param string $url * @param string $scheme * @param string $host * @param int|null $port * @param string|null $user * @param string|null $password * * @return void * * @dataProvider urlProvider */ public function testSplitUrl( string $url, string $scheme, string $host, ?int $port, ?string $user, ?string $pass ): void { $parts = Bitcoin\split_url($url); $this->assertEquals($parts['scheme'], $scheme); $this->assertEquals($parts['host'], $host); foreach (['port', 'user', 'pass'] as $part) { if (!is_null(${$part})) { $this->assertEquals($parts[$part], ${$part}); } } } /** * Test url parser with invalid url. * * @return array */ public function testSplitUrlWithInvalidUrl(): void { $this->expectException(BadConfigurationException::class); $this->expectExceptionMessage('Invalid url'); Bitcoin\split_url('cookies!'); } /** * Test exception handler helper. * * @return void */ public function testExceptionHandlerHelper(): void { $this->assertInstanceOf(ExceptionHandler::class, Bitcoin\exception()); } /** * Provides url strings and parts. * * @return array */ public function urlProvider(): array { return [ ['https://localhost', 'https', 'localhost', null, null, null], ['https://localhost:8000', 'https', 'localhost', 8000, null, null], ['http://localhost', 'http', 'localhost', null, null, null], ['http://localhost:8000', 'http', 'localhost', 8000, null, null], ['http://testuser@127.0.0.1:8000/', 'http', '127.0.0.1', 8000, 'testuser', null], ['http://testuser:testpass@localhost:8000', 'http', 'localhost', 8000, 'testuser', '<PASSWORD>'], ]; } /** * Provides satoshi and bitcoin values. * * @return array */ public function satoshiBtcProvider(): array { return [ [1000, '0.00001000'], [2500, '0.00002500'], [-1000, '-0.00001000'], [100000000, '1.00000000'], [150000000, '1.50000000'], [2100000000000000, '21000000.00000000'], ]; } /** * Provides satoshi and ubtc/bits values. * * @return array */ public function bitsBtcProvider(): array { return [ [10, '0.00001000'], [25, '0.00002500'], [-10, '-0.00001000'], [1000000, '1.00000000'], [1500000, '1.50000000'], ]; } /** * Provides satoshi and mbtc values. * * @return array */ public function mbtcBtcProvider(): array { return [ [0.01, '0.00001000'], [0.025, '0.00002500'], [-0.01, '-0.00001000'], [1000, '1.00000000'], [1500, '1.50000000'], ]; } /** * Provides float values with precision and result. * * @return array */ public function floatProvider(): array { return [ [1.2345678910, 0, '1'], [1.2345678910, 2, '1.23'], [1.2345678910, 4, '1.2345'], [1.2345678910, 8, '1.23456789'], ]; } } <file_sep>/src/functions.php <?php declare(strict_types=1); namespace Denpa\Bitcoin; use Denpa\Bitcoin\Exceptions\BadConfigurationException; use Denpa\Bitcoin\Exceptions\Handler as ExceptionHandler; if (!function_exists('to_bitcoin')) { /** * Converts from satoshi to bitcoin. * * @param int $satoshi * * @return string */ function to_bitcoin(int $satoshi): string { return bcdiv((string) $satoshi, (string) 1e8, 8); } } if (!function_exists('to_satoshi')) { /** * Converts from bitcoin to satoshi. * * @param string|float $bitcoin * * @return string */ function to_satoshi($bitcoin): string { return bcmul(to_fixed($bitcoin, 8), (string) 1e8); } } if (!function_exists('to_ubtc')) { /** * Converts from bitcoin to ubtc/bits. * * @param string|float $bitcoin * * @return string */ function to_ubtc($bitcoin): string { return bcmul(to_fixed($bitcoin, 8), (string) 1e6, 4); } } if (!function_exists('to_mbtc')) { /** * Converts from bitcoin to mbtc. * * @param string|float $bitcoin * * @return string */ function to_mbtc($bitcoin): string { return bcmul(to_fixed($bitcoin, 8), (string) 1e3, 4); } } if (!function_exists('to_fixed')) { /** * Brings number to fixed precision without rounding. * * @param string $number * @param int $precision * * @return string */ function to_fixed(string $number, int $precision = 8): string { $number = bcmul($number, (string) pow(10, $precision)); return bcdiv($number, (string) pow(10, $precision), $precision); } } if (!function_exists('split_url')) { /** * Splits url into parts. * * @param string $url * * @return array */ function split_url(string $url): array { $allowed = ['scheme', 'host', 'port', 'user', 'pass']; $parts = (array) parse_url($url); $parts = array_intersect_key($parts, array_flip($allowed)); if (!$parts || empty($parts)) { throw new BadConfigurationException( ['url' => $url], 'Invalid url' ); } return $parts; } } if (!function_exists('exception')) { /** * Gets exception handler instance. * * @return \Denpa\Bitcoin\Exceptions\Handler */ function exception(): ExceptionHandler { return ExceptionHandler::getInstance(); } } set_exception_handler([ExceptionHandler::getInstance(), 'handle']); <file_sep>/tests/TestCase.php <?php namespace Denpa\Bitcoin\Tests; use Denpa\Bitcoin\Responses\BitcoindResponse; use GuzzleHttp\Client as GuzzleClient; use GuzzleHttp\Exception\RequestException; use GuzzleHttp\Handler\MockHandler; use GuzzleHttp\HandlerStack; use GuzzleHttp\Middleware; use GuzzleHttp\Psr7\Response; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\UriInterface; use stdClass; abstract class TestCase extends \PHPUnit\Framework\TestCase { /** * Set-up test environment. * * @return void */ protected function setUp(): void { parent::setUp(); $this->history = []; } /** * Block header response. * * @var array */ protected static $getBlockResponse = [ 'hash' => '000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f', 'confirmations' => 449162, 'height' => null, 'version' => 1, 'versionHex' => '00000001', 'merkleroot' => '4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b', 'time' => 1231006505, 'mediantime' => 1231006505, 'nonce' => 2083236893, 'bits' => '1d00ffff', 'difficulty' => 1, 'chainwork' => '0000000000000000000000000000000000000000000000000000000100010001', 'nextblockhash' => '00000000839a8e6886ab5951d76f411475428afc90947ee320161bbf18eb6048', 'tx' => [ 'bedb088c480e5f7424a958350f2389c839d17e27dae13643632159b9e7c05482', '59b36164c777b34aee28ef623ec34700371d33ff011244d8ee22d02b0547c13b', 'ead6116a07f2a6911ac93eb0ae00ce05d49c7bb288f2fb9c338819e85414cf2c', null, ], 'test1' => [ 'test2' => [ 'test4' => [ 'amount' => 3, ], ], 'test3' => [ 'test5' => [ 'amount' => 4, ], ], ], ]; /** * Transaction error response. * * @var array */ protected static $rawTransactionError = [ 'code' => -5, 'message' => 'No information available about transaction', ]; /** * Balance response. * * @var float */ protected static $balanceResponse = 0.1; /** * Get error 500 message. * * @return string */ protected function error500(): string { return 'Server error: `POST /` '. 'resulted in a `500 Internal Server Error` response'; } /** * Get Closure mock. * * @param array $with * * @return callable */ protected function mockCallable(array $with = []): callable { $callable = $this->getMockBuilder(stdClass::class) ->setMethods(['__invoke']) ->getMock(); $callable->expects($this->once()) ->method('__invoke') ->with(...$with); return $callable; } /** * Get Guzzle mock client. * * @param array $queue * @param \GuzzleHttp\HandlerStack $handler * * @return \GuzzleHttp\Client */ protected function mockGuzzle( array $queue = [], HandlerStack $handler = null ): GuzzleClient { $handler = $handler ?: $this->bitcoind->getClient()->getConfig('handler'); if ($handler) { $middleware = Middleware::history($this->history); $handler->push($middleware); $handler->setHandler(new MockHandler($queue)); } return new GuzzleClient([ 'handler' => $handler, ]); } /** * Make block header response. * * @param int $code * * @return \Psr\Http\Message\ResponseInterface */ protected function getBlockResponse(int $code = 200): ResponseInterface { $json = json_encode([ 'result' => self::$getBlockResponse, 'error' => null, 'id' => 0, ]); return new Response($code, [], $json); } /** * Get getbalance command response. * * @param int $code * * @return \Psr\Http\Message\ResponseInterface */ protected function getBalanceResponse(int $code = 200): ResponseInterface { $json = json_encode([ 'result' => self::$balanceResponse, 'error' => null, 'id' => 0, ]); return new Response($code, [], $json); } /** * Make raw transaction error response. * * @param int $code * * @return \Psr\Http\Message\ResponseInterface */ protected function rawTransactionError(int $code = 500): ResponseInterface { $json = json_encode([ 'result' => null, 'error' => self::$rawTransactionError, 'id' => 0, ]); return new Response($code, [], $json); } /** * Return exception with response. * * @return callable */ protected function requestExceptionWithResponse(): callable { $exception = function ($request) { return new RequestException( 'test', $request, new BitcoindResponse($this->rawTransactionError()) ); }; return $exception; } /** * Return exception without response. * * @return callable */ protected function requestExceptionWithoutResponse(): callable { $exception = function ($request) { return new RequestException('test', $request); }; return $exception; } /** * Make request body. * * @param string $method * @param int $id * @param mixed $params,... * * @return array */ protected function makeRequestBody( string $method, int $id, ...$params ): array { return [ 'method' => $method, 'params' => (array) $params, 'id' => $id, ]; } /** * Get request url from history. * * @param int $index * * @return \Psr\Http\Message\UriInterface|null */ protected function getHistoryRequestUri(int $index = 0): ?UriInterface { if (isset($this->history[$index])) { return $this->history[$index]['request']->getUri(); } } /** * Get request body from history. * * @param int $index * * @return mixed */ protected function getHistoryRequestBody(int $index = 0) { if (isset($this->history[$index])) { return json_decode( $this->history[$index]['request']->getBody()->getContents(), true ); } } } <file_sep>/src/Traits/HandlesAsync.php <?php declare(strict_types=1); namespace Denpa\Bitcoin\Traits; use Exception; use Psr\Http\Message\ResponseInterface; trait HandlesAsync { /** * Handles async request success. * * @param \Psr\Http\Message\ResponseInterface $response * @param callable|null $callback * * @return void */ protected function onSuccess(ResponseInterface $response, ?callable $callback = null): void { if (!is_null($callback)) { $callback($response); } } /** * Handles async request failure. * * @param \Exception $exception * @param callable|null $callback * * @return void */ protected function onError(Exception $exception, ?callable $callback = null): void { if (!is_null($callback)) { $callback($exception); } } } <file_sep>/tests/Exceptions/BadConfigurationExceptionTest.php <?php namespace Denpa\Bitcoin\Tests\Exceptions; use Denpa\Bitcoin\Exceptions\BadConfigurationException; use Denpa\Bitcoin\Tests\TestCase; class BadConfigurationExceptionTest extends TestCase { /** * Set-up test environment. * * @return void */ protected function setUp(): void { parent::setUp(); $this->config = ['test' => 'value']; } /** * Test trowing exception. * * @return void */ public function testThrow(): void { $this->expectException(BadConfigurationException::class); $this->expectExceptionMessage('Test message'); $this->expectExceptionCode(1); throw new BadConfigurationException($this->config, 'Test message', 1); } /** * Test config getter. * * @return void */ public function testGetConfig(): void { $exception = new BadConfigurationException($this->config); $this->assertEquals($this->config, $exception->getConfig()); } /** * Test constructor parameters getter. * * @return void */ public function testGetConstructionParameters(): void { $exception = new FakeBadConfigurationException($this->config); $this->assertEquals( [ $exception->getConfig(), $exception->getMessage(), $exception->getCode(), ], $exception->getConstructorParameters() ); } } class FakeBadConfigurationException extends BadConfigurationException { public function getConstructorParameters(): array { return parent::getConstructorParameters(); } } <file_sep>/tests/ClientTest.php <?php namespace Denpa\Bitcoin\Tests; use Denpa\Bitcoin\Client as BitcoinClient; use Denpa\Bitcoin\Config; use Denpa\Bitcoin\Exceptions; use Denpa\Bitcoin\Responses\BitcoindResponse; use Denpa\Bitcoin\Responses\Response; use GuzzleHttp\Client as GuzzleHttp; use GuzzleHttp\Psr7\Response as GuzzleResponse; class ClientTest extends TestCase { /** * Set-up test environment. * * @return void */ public function setUp(): void { parent::setUp(); $this->bitcoind = new BitcoinClient(); } /** * Test client getter and setter. * * @return void */ public function testClientSetterGetter(): void { $bitcoind = new BitcoinClient('http://old_client.org'); $this->assertInstanceOf(BitcoinClient::class, $bitcoind); $base_uri = $bitcoind->getClient()->getConfig('base_uri'); $this->assertEquals($base_uri->getHost(), 'old_client.org'); $oldClient = $bitcoind->getClient(); $this->assertInstanceOf(GuzzleHttp::class, $oldClient); $newClient = new GuzzleHttp(['base_uri' => 'http://new_client.org']); $bitcoind->setClient($newClient); $base_uri = $bitcoind->getClient()->getConfig('base_uri'); $this->assertEquals($base_uri->getHost(), 'new_client.org'); } /** * Test preserve method name case config option. * * @return void */ public function testPreserveCaseOption(): void { $bitcoind = new BitcoinClient(['preserve_case' => true]); $bitcoind->setClient($this->mockGuzzle([$this->getBlockResponse()])); $bitcoind->getBlockHeader(); $request = $this->getHistoryRequestBody(); $this->assertEquals($this->makeRequestBody( 'getBlockHeader', $request['id'] ), $request); } /** * Test client config getter. * * @return void */ public function testGetConfig(): void { $this->assertInstanceOf(Config::class, $this->bitcoind->getConfig()); } /** * Test simple request. * * @return void */ public function testRequest(): void { $response = $this->bitcoind ->setClient($this->mockGuzzle([$this->getBlockResponse()])) ->request( 'getblockheader', '000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f' ); $request = $this->getHistoryRequestBody(); $this->assertEquals($this->makeRequestBody( 'getblockheader', $request['id'], '000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f' ), $request); $this->assertEquals(self::$getBlockResponse, $response->get()); } /** * Test multiwallet request. * * @return void */ public function testMultiWalletRequest(): void { $wallet = 'testwallet.dat'; $response = $this->bitcoind ->setClient($this->mockGuzzle([$this->getBalanceResponse()])) ->wallet($wallet) ->request('getbalance'); $this->assertEquals(self::$balanceResponse, $response->get()); $this->assertEquals( $this->getHistoryRequestUri()->getPath(), "/wallet/$wallet" ); } /** * Test async multiwallet request. * * @return void */ public function testMultiWalletAsyncRequest(): void { $wallet = 'testwallet2.dat'; $this->bitcoind ->setClient($this->mockGuzzle([$this->getBalanceResponse()])) ->wallet($wallet) ->requestAsync('getbalance', []); $this->bitcoind->wait(); $this->assertEquals( $this->getHistoryRequestUri()->getPath(), "/wallet/$wallet" ); } /** * Test async request. * * @return void */ public function testAsyncRequest(): void { $onFulfilled = $this->mockCallable([ $this->callback(function (BitcoindResponse $response) { return $response->get() == self::$getBlockResponse; }), ]); $this->bitcoind ->setClient($this->mockGuzzle([$this->getBlockResponse()])) ->requestAsync( 'getblockheader', '000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f', function ($response) use ($onFulfilled) { $onFulfilled($response); } ); $this->bitcoind->wait(); $request = $this->getHistoryRequestBody(); $this->assertEquals($this->makeRequestBody( 'getblockheader', $request['id'], '000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f' ), $request); } /** * Test magic request. * * @return void */ public function testMagic(): void { $response = $this->bitcoind ->setClient($this->mockGuzzle([$this->getBlockResponse()])) ->getBlockHeader( '000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f' ); $request = $this->getHistoryRequestBody(); $this->assertEquals($this->makeRequestBody( 'getblockheader', $request['id'], '000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f' ), $request); } /** * Test magic request. * * @return void */ public function testAsyncMagic(): void { $onFulfilled = $this->mockCallable([ $this->callback(function (BitcoindResponse $response) { return $response->get() == self::$getBlockResponse; }), ]); $this->bitcoind ->setClient($this->mockGuzzle([$this->getBlockResponse()])) ->getBlockHeaderAsync( '000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f', function ($response) use ($onFulfilled) { $onFulfilled($response); } ); $this->bitcoind->wait(); $request = $this->getHistoryRequestBody(); $this->assertEquals($this->makeRequestBody( 'getblockheader', $request['id'], '000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f' ), $request); } /** * Test bitcoind exception. * * @return void */ public function testBitcoindException(): void { $this->expectException(Exceptions\BadRemoteCallException::class); $this->expectExceptionMessage(self::$rawTransactionError['message']); $this->expectExceptionCode(self::$rawTransactionError['code']); $this->bitcoind ->setClient($this->mockGuzzle([$this->rawTransactionError(200)])) ->getRawTransaction( '4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b' ); } /** * Test request exception with error code. * * @return void */ public function testRequestExceptionWithServerErrorCode(): void { $this->expectException(Exceptions\BadRemoteCallException::class); $this->expectExceptionMessage(self::$rawTransactionError['message']); $this->expectExceptionCode(self::$rawTransactionError['code']); $this->bitcoind ->setClient($this->mockGuzzle([$this->rawTransactionError(200)])) ->getRawTransaction( '4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b' ); } /** * Test request exception with empty response body. * * @return void */ public function testRequestExceptionWithEmptyResponseBody(): void { $this->expectException(Exceptions\ConnectionException::class); $this->expectExceptionMessage($this->error500()); $this->expectExceptionCode(500); $this->bitcoind ->setClient($this->mockGuzzle([new GuzzleResponse(500)])) ->getRawTransaction( '4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b' ); } /** * Test async request exception with empty response body. * * @return void */ public function testAsyncRequestExceptionWithEmptyResponseBody(): void { $rejected = $this->mockCallable([ $this->callback(function (Exceptions\ClientException $exception) { return $exception->getMessage() == $this->error500() && $exception->getCode() == 500; }), ]); $this->bitcoind ->setClient($this->mockGuzzle([new GuzzleResponse(500)])) ->requestAsync( 'getrawtransaction', '4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b', null, function ($exception) use ($rejected) { $rejected($exception); } ); $this->bitcoind->wait(); } /** * Test request exception with response. * * @return void */ public function testRequestExceptionWithResponseBody(): void { $this->expectException(Exceptions\BadRemoteCallException::class); $this->expectExceptionMessage(self::$rawTransactionError['message']); $this->expectExceptionCode(self::$rawTransactionError['code']); $this->bitcoind ->setClient($this->mockGuzzle([$this->requestExceptionWithResponse()])) ->getRawTransaction( '4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b' ); } /** * Test async request exception with response. * * @return void */ public function testAsyncRequestExceptionWithResponseBody(): void { $onRejected = $this->mockCallable([ $this->callback(function (Exceptions\BadRemoteCallException $exception) { return $exception->getMessage() == self::$rawTransactionError['message'] && $exception->getCode() == self::$rawTransactionError['code']; }), ]); $this->bitcoind ->setClient($this->mockGuzzle([$this->requestExceptionWithResponse()])) ->requestAsync( 'getrawtransaction', '4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b', null, function ($exception) use ($onRejected) { $onRejected($exception); } ); $this->bitcoind->wait(); } /** * Test request exception with no response. * * @return void */ public function testRequestExceptionWithNoResponseBody(): void { $this->expectException(Exceptions\ClientException::class); $this->expectExceptionMessage('test'); $this->expectExceptionCode(0); $this->bitcoind ->setClient($this->mockGuzzle([$this->requestExceptionWithoutResponse()])) ->getRawTransaction( '4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b' ); } /** * Test async request exception with no response. * * @return void */ public function testAsyncRequestExceptionWithNoResponseBody(): void { $rejected = $this->mockCallable([ $this->callback(function (Exceptions\ClientException $exception) { return $exception->getMessage() == 'test' && $exception->getCode() == 0; }), ]); $this->bitcoind ->setClient($this->mockGuzzle([$this->requestExceptionWithoutResponse()])) ->requestAsync( 'getrawtransaction', '4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b', null, function ($exception) use ($rejected) { $rejected($exception); } ); $this->bitcoind->wait(); } /** * Test setting different response handler class. * * @return void */ public function testSetResponseHandler(): void { $fake = new FakeClient(); $guzzle = $this->mockGuzzle([ $this->getBlockResponse(), ], $fake->getClient()->getConfig('handler')); $response = $fake ->setClient($guzzle) ->request( 'getblockheader', '000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f' ); $this->assertInstanceOf(FakeResponse::class, $response); } } class FakeClient extends BitcoinClient { /** * Gets response handler class name. * * @return string */ protected function getResponseHandler(): string { return 'Denpa\\Bitcoin\\Tests\\FakeResponse'; } } class FakeResponse extends Response { // } <file_sep>/src/Exceptions/Handler.php <?php declare(strict_types=1); namespace Denpa\Bitcoin\Exceptions; use Denpa\Bitcoin\Traits\Singleton; use GuzzleHttp\Exception\RequestException; use Throwable; class Handler { use Singleton; /** * Exception namespace. * * @var string */ protected $namespace = null; /** * Handler functions array. * * @var array */ protected $handlers = []; /** * Constructs exception handler. * * @return void */ protected function __construct() { $this->registerHandler([$this, 'namespaceHandler']); $this->registerHandler([$this, 'requestExceptionHandler']); } /** * Handle namespace change. * * @param \Throwable $exception * * @return \Throwable|null */ protected function namespaceHandler(Throwable $exception): ?Throwable { if ($this->namespace && $exception instanceof ClientException) { return $exception->withNamespace($this->namespace); } return null; } /** * Handle request exception. * * @param \Throwable $exception * * @return \Throwable|null */ protected function requestExceptionHandler(Throwable $exception): ?Throwable { if ($exception instanceof RequestException) { if ( $exception->hasResponse() && $exception->getResponse()->hasError() ) { return new BadRemoteCallException($exception->getResponse()); } return new ConnectionException( $exception->getRequest(), $exception->getMessage(), $exception->getCode() ); } return null; } /** * Registers new handler function. * * @param callable $handler * * @return self */ public function registerHandler(callable $handler): self { $this->handlers[] = $handler; return $this; } /** * Handles exception. * * @param \Throwable $exception * * @return void */ public function handle(Throwable $exception): void { foreach ($this->handlers as $handler) { $result = $handler($exception); if ($result instanceof Throwable) { $exception = $result; } } throw $exception; } /** * Sets exception namespace. * * @param string $namespace * * @return self */ public function setNamespace($namespace): self { $this->namespace = $namespace; return $this; } } <file_sep>/README.md # Simple Bitcoin JSON-RPC client based on GuzzleHttp [![Latest Stable Version](https://poser.pugx.org/denpa/php-bitcoinrpc/v/stable)](https://packagist.org/packages/denpa/php-bitcoinrpc) [![License](https://poser.pugx.org/denpa/php-bitcoinrpc/license)](https://packagist.org/packages/denpa/php-bitcoinrpc) [![ci](https://github.com/denpamusic/php-bitcoinrpc/actions/workflows/ci.yml/badge.svg)](https://github.com/denpamusic/php-bitcoinrpc/actions/workflows/ci.yml) [![Code Climate](https://codeclimate.com/github/denpamusic/php-bitcoinrpc/badges/gpa.svg)](https://codeclimate.com/github/denpamusic/php-bitcoinrpc) [![Code Coverage](https://codeclimate.com/github/denpamusic/php-bitcoinrpc/badges/coverage.svg)](https://codeclimate.com/github/denpamusic/php-bitcoinrpc/coverage) ## Installation Run ```php composer.phar require denpa/php-bitcoinrpc``` in your project directory or add following lines to composer.json ```javascript "require": { "denpa/php-bitcoinrpc": "^2.1" } ``` and run ```php composer.phar install```. ## Requirements PHP 8.0 or higher _For PHP 5.6 and 7.0 use [php-bitcoinrpc v2.0.x](https://github.com/denpamusic/php-bitcoinrpc/tree/2.0.x)._ ## Usage Create new object with url as parameter ```php /** * Don't forget to include composer autoloader by uncommenting line below * if you're not already done it anywhere else in your project. **/ // require 'vendor/autoload.php'; use Denpa\Bitcoin\Client as BitcoinClient; $bitcoind = new BitcoinClient('http://rpcuser:rpcpassword@localhost:8332/'); ``` or use array to define your bitcoind settings ```php /** * Don't forget to include composer autoloader by uncommenting line below * if you're not already done it anywhere else in your project. **/ // require 'vendor/autoload.php'; use Denpa\Bitcoin\Client as BitcoinClient; $bitcoind = new BitcoinClient([ 'scheme' => 'http', // optional, default http 'host' => 'localhost', // optional, default localhost 'port' => 8332, // optional, default 8332 'user' => 'rpcuser', // required 'password' => '<PASSWORD>', // required 'ca' => '/etc/ssl/ca-cert.pem', // optional, for use with https scheme 'preserve_case' => false, // optional, send method names as defined instead of lowercasing them ]); ``` Then call methods defined in [Bitcoin Core API Documentation](https://bitcoin.org/en/developer-reference#bitcoin-core-apis) with magic: ```php /** * Get block info. */ $block = $bitcoind->getBlock('000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f'); $block('hash')->get(); // 000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f $block['height']; // 0 (array access) $block->get('tx.0'); // 4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b $block->count('tx'); // 1 $block->has('version'); // key must exist and CAN NOT be null $block->exists('version'); // key must exist and CAN be null $block->contains(0); // check if response contains value $block->values(); // array of values $block->keys(); // array of keys $block->random(1, 'tx'); // random block txid $block('tx')->random(2); // two random block txid's $block('tx')->first(); // txid of first transaction $block('tx')->last(); // txid of last transaction /** * Send transaction. */ $result = $bitcoind->sendToAddress('mmXgiR6KAhZCyQ8ndr2BCfEq1wNG2UnyG6', 0.1); $txid = $result->get(); /** * Get transaction amount. */ $result = $bitcoind->listSinceBlock(); $bitcoin = $result->sum('transactions.*.amount'); $satoshi = \Denpa\Bitcoin\to_satoshi($bitcoin); ``` To send asynchronous request, add Async to method name: ```php $bitcoind->getBlockAsync( '000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f', function ($response) { // success }, function ($exception) { // error } ); ``` You can also send requests using request method: ```php /** * Get block info. */ $block = $bitcoind->request('getBlock', '000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f'); $block('hash'); // 000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f $block['height']; // 0 (array access) $block->get('tx.0'); // 4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b $block->count('tx'); // 1 $block->has('version'); // key must exist and CAN NOT be null $block->exists('version'); // key must exist and CAN be null $block->contains(0); // check if response contains value $block->values(); // get response values $block->keys(); // get response keys $block->first('tx'); // get txid of the first transaction $block->last('tx'); // get txid of the last transaction $block->random(1, 'tx'); // get random txid /** * Send transaction. */ $result = $bitcoind->request('sendtoaddress', 'mmXgiR6KAhZCyQ8ndr2BCfEq1wNG2UnyG6', 0.06); $txid = $result->get(); ``` or requestAsync method for asynchronous calls: ```php $bitcoind->requestAsync( 'getBlock', '000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f', function ($response) { // success }, function ($exception) { // error } ); ``` ## Multi-Wallet RPC You can use `wallet($name)` function to do a [Multi-Wallet RPC call](https://en.bitcoin.it/wiki/API_reference_(JSON-RPC)#Multi-wallet_RPC_calls): ```php /** * Get wallet2.dat balance. */ $balance = $bitcoind->wallet('wallet2.dat')->getbalance(); echo $balance->get(); // 0.10000000 ``` ## Exceptions * `Denpa\Bitcoin\Exceptions\BadConfigurationException` - thrown on bad client configuration. * `Denpa\Bitcoin\Exceptions\BadRemoteCallException` - thrown on getting error message from daemon. * `Denpa\Bitcoin\Exceptions\ConnectionException` - thrown on daemon connection errors (e. g. timeouts) ## Helpers Package provides following helpers to assist with value handling. #### `to_bitcoin()` Converts value in satoshi to bitcoin. ```php echo Denpa\Bitcoin\to_bitcoin(100000); // 0.00100000 ``` #### `to_satoshi()` Converts value in bitcoin to satoshi. ```php echo Denpa\Bitcoin\to_satoshi(0.001); // 100000 ``` #### `to_ubtc()` Converts value in bitcoin to ubtc/bits. ```php echo Denpa\Bitcoin\to_ubtc(0.001); // 1000.0000 ``` #### `to_mbtc()` Converts value in bitcoin to mbtc. ```php echo Denpa\Bitcoin\to_mbtc(0.001); // 1.0000 ``` #### `to_fixed()` Trims float value to precision without rounding. ```php echo Denpa\Bitcoin\to_fixed(0.1236, 3); // 0.123 ``` ## License This product is distributed under MIT license. ## Donations If you like this project, please consider donating:<br> **BTC**: 3L6dqSBNgdpZan78KJtzoXEk9DN3sgEQJu<br> **Bech32**: bc1qyj8v6l70c4mjgq7hujywlg6le09kx09nq8d350 ❤Thanks for your support!❤ <file_sep>/src/Traits/SerializableContainer.php <?php declare(strict_types=1); namespace Denpa\Bitcoin\Traits; trait SerializableContainer { /** * Returns array containing all the necessary state of the object. * * @return array */ public function __serialize(): array { return [ 'container' => $this->toContainer(), ]; } /** * Restores the object state from the given data array. * * @param array $serialized */ public function __unserialize(array $serialized) { $this->container = $serialized['container']; } /** * Serializes the object to a value that can be serialized by json_encode(). * * @return array */ public function jsonSerialize(): array { return $this->toContainer(); } } <file_sep>/.github/ISSUE_TEMPLATE/bug_report.md --- name: Bug report about: Create a report to help improve php-bitcoinrpc --- **Describe the bug** A clear and concise description of what the bug is. **To Reproduce** What code caused the problem. Feel free to omit any sensitive information. **Expected behavior** A clear and concise description of what you expected to happen. **Logs** If applicable, attach log files. Feel free to omit any sensitive information. **Cryptocurrency** Describe used software and network: * Software: Bitcoin Core v0.17.0 * Network: mainnet or testnet **Environment** Describe your runtime environment: * PHP: 7.0 (run `php -v` to get php version) * Web Server (if applicable): nginx/1.15.3 * System: Ubuntu 18.04.01 LTS **Additional information** Add any other information about the problem here. <file_sep>/src/Traits/Message.php <?php declare(strict_types=1); namespace Denpa\Bitcoin\Traits; use Psr\Http\Message\StreamInterface; trait Message { /** * Retrieves the HTTP protocol version as a string. * * @return string */ public function getProtocolVersion(): string { return $this->response->getProtocolVersion(); } /** * Return an instance with the specified HTTP protocol version. * * @param float|string $version * * @return self */ public function withProtocolVersion($version): self { $new = clone $this; return $new->setResponse( $this->response->withProtocolVersion($version) ); } /** * Retrieves all message header values. * * @return array */ public function getHeaders(): array { return $this->response->getHeaders(); } /** * Checks if a header exists by the given case-insensitive name. * * @param string $name * * @return bool */ public function hasHeader($name): bool { return $this->response->hasHeader($name); } /** * Retrieves a message header value by the given case-insensitive name. * * @param string $name * * @return array */ public function getHeader($name): array { return $this->response->getHeader($name); } /** * Retrieves a comma-separated string of the values for a single header. * * @param string $name * * @return string */ public function getHeaderLine($name): string { return $this->response->getHeaderLine($name); } /** * Returns an instance with the provided value replacing the specified header. * * @param string $name * @param string|array $value * * @return self */ public function withHeader($name, $value): self { $new = clone $this; return $new->setResponse($this->response->withHeader($name, $value)); } /** * Returns an instance with the specified header appended with the given value. * * @param string $name * @param string|array $value * * @return self */ public function withAddedHeader($name, $value): self { $new = clone $this; return $new->setResponse($this->response->withAddedHeader($name, $value)); } /** * Returns an instance without the specified header. * * @param string $name * * @return self */ public function withoutHeader($name): self { $new = clone $this; return $new->setResponse($this->response->withoutHeader($name)); } /** * Gets the body of the message. * * @return \Psr\Http\Message\StreamInterface */ public function getBody(): StreamInterface { return $this->response->getBody(); } /** * Returns an instance with the specified message body. * * @param \Psr\Http\Message\StreamInterface $body * * @return self */ public function withBody(StreamInterface $body): self { $new = clone $this; return $new->setResponse($this->response->withBody($body)); } } <file_sep>/src/Responses/BitcoindResponse.php <?php declare(strict_types=1); namespace Denpa\Bitcoin\Responses; use Denpa\Bitcoin\Traits\Collection; use Denpa\Bitcoin\Traits\ImmutableArray; use Denpa\Bitcoin\Traits\SerializableContainer; class BitcoindResponse extends Response implements \ArrayAccess, \Countable, \JsonSerializable { use Collection; use ImmutableArray; use SerializableContainer; /** * Gets array representation of response object. * * @return array */ public function toArray(): array { return (array) $this->result(); } /** * Gets root container of response object. * * @return array */ public function toContainer(): array { return $this->container; } } <file_sep>/tests/Exceptions/ClientExceptionTest.php <?php namespace Denpa\Bitcoin\Tests\Exceptions; use Denpa\Bitcoin\Exceptions\ClientException; use Denpa\Bitcoin\Tests\TestCase; class ClientExceptionTest extends TestCase { /** * Test exception namespace setter. * * @return void */ public function testWithNamespace(): void { $exception = (new FakeClientException()) ->withNamespace('Test\\Exceptions'); $this->assertInstanceOf( \Test\Exceptions\FakeClientException::class, $exception ); } /** * Test namespace setter with nonexistent namespace. * * @return void */ public function testWithNamespaceWithNonexistentClass(): void { $exception = (new FakeClientException()) ->withNamespace('Test\\Nonexistents'); $this->assertInstanceOf(FakeClientException::class, $exception); } /** * Test exception class name getter. * * @return void */ public function testGetClassName(): void { $exception = new FakeClientException(); $this->assertEquals($exception->getClassName(), 'FakeClientException'); } } class FakeClientException extends ClientException { // original ClientException is an abstract class public function getClassName(): string { return parent::getClassName(); } protected function getConstructorParameters(): array { return []; } } namespace Test\Exceptions; class FakeClientException extends \Denpa\Bitcoin\Tests\Exceptions\FakeClientException { // same as above in different namespace } <file_sep>/tests/Exceptions/ConnectionExceptionTest.php <?php namespace Denpa\Bitcoin\Tests\Exceptions; use Denpa\Bitcoin\Exceptions\ConnectionException; use Denpa\Bitcoin\Tests\TestCase; use GuzzleHttp\Psr7\Request; class ConnectionExceptionTest extends TestCase { /** * Set-up test environment. * * @return void */ protected function setUp(): void { parent::setUp(); $this->request = $this ->getMockBuilder(Request::class) ->disableOriginalConstructor() ->getMock(); } /** * Test trowing exception. * * @return void */ public function testThrow(): void { $this->expectException(ConnectionException::class); $this->expectExceptionMessage('Test message'); $this->expectExceptionCode(1); throw new ConnectionException($this->request, 'Test message', 1); } /** * Test request getter. * * @return void */ public function testGetRequest(): void { $exception = new ConnectionException($this->request); $this->assertInstanceOf(Request::class, $exception->getRequest()); } /** * Test constructor parameters getter. * * @return void */ public function testGetConstructionParameters(): void { $exception = new FakeConnectionException($this->request); $this->assertEquals( [ $exception->getRequest(), $exception->getMessage(), $exception->getCode(), ], $exception->getConstructorParameters() ); } } class FakeConnectionException extends ConnectionException { public function getConstructorParameters(): array { return parent::getConstructorParameters(); } } <file_sep>/tests/ConfigTest.php <?php namespace Denpa\Bitcoin\Tests; use Denpa\Bitcoin\Config; class ConfigTest extends TestCase { /** * Set up test. * * @return void */ public function setUp(): void { parent::setUp(); $this->config = new Config([ 'user' => 'testuser', 'password' => '<PASSWORD>', 'ca' => __FILE__, ]); } /** * Test CA file getter. * * @return void */ public function testGetCa(): void { $this->assertEquals(__FILE__, $this->config->getCa()); } /** * Test authentication array getter. * * @return void */ public function testGetAuth(): void { $this->assertEquals(['testuser', 'testpass'], $this->config->getAuth()); } /** * Test dsn getter. * * @return void */ public function testGetDsn(): void { $this->assertEquals('http://127.0.0.1:8332', $this->config->getDsn()); } /** * Test config setter. * * @return void */ public function testSet(): void { $this->config->set(['password' => '<PASSWORD>']); $this->assertEquals('<PASSWORD>', $this->config->get('password')); } } <file_sep>/src/Client.php <?php declare(strict_types=1); namespace Denpa\Bitcoin; use Denpa\Bitcoin\Exceptions\BadRemoteCallException; use Denpa\Bitcoin\Traits\HandlesAsync; use GuzzleHttp\Client as GuzzleHttp; use GuzzleHttp\ClientInterface; use GuzzleHttp\HandlerStack; use GuzzleHttp\Middleware; use GuzzleHttp\Promise; use Psr\Http\Message\ResponseInterface; use Throwable; class Client { use HandlesAsync; /** * Http Client. * * @var \GuzzleHttp\Client */ protected $client; /** * Client configuration. * * @var \Denpa\Bitcoin\Config */ protected $config; /** * Array of GuzzleHttp promises. * * @var array */ protected $promises = []; /** * URL path. * * @var string */ protected $path = '/'; /** * JSON-RPC Id. * * @var int */ protected $rpcId = 0; /** * Constructs new client. * * @param array|string $config * * @return void */ public function __construct($config = []) { if (is_string($config)) { $config = split_url($config); } // init configuration $provider = $this->getConfigProvider(); $this->config = new $provider($config); // construct client $this->client = new GuzzleHttp([ 'base_uri' => $this->config->getDsn(), 'auth' => $this->config->getAuth(), 'verify' => $this->config->getCa(), 'timeout' => (float) $this->config['timeout'], 'connect_timeout' => (float) $this->config['timeout'], 'handler' => $this->getHandler(), ]); } /** * Wait for all promises on object destruction. * * @return void */ public function __destruct() { $this->wait(); } /** * Gets client config. * * @return \Denpa\Bitcoin\Config */ public function getConfig(): Config { return $this->config; } /** * Gets http client. * * @return \GuzzleHttp\ClientInterface */ public function getClient(): ClientInterface { return $this->client; } /** * Sets http client. * * @param \GuzzleHttp\ClientInterface * * @return self */ public function setClient(ClientInterface $client): self { $this->client = $client; return $this; } /** * Sets wallet for multi-wallet rpc request. * * @param string $name * * @return self */ public function wallet(string $name): self { $this->path = "/wallet/$name"; return $this; } /** * Makes request to Bitcoin Core. * * @param string $method * @param mixed $params * * @return \Psr\Http\Message\ResponseInterface */ public function request(string $method, ...$params): ResponseInterface { try { $response = $this->client ->post($this->path, $this->makeJson($method, $params)); if ($response->hasError()) { // throw exception on error throw new BadRemoteCallException($response); } return $response; } catch (Throwable $exception) { throw exception()->handle($exception); } } /** * Makes async request to Bitcoin Core. * * @param string $method * @param mixed $params * @param callable|null $fulfilled * @param callable|null $rejected * * @return \GuzzleHttp\Promise\Promise */ public function requestAsync( string $method, $params = [], ?callable $fulfilled = null, ?callable $rejected = null ): Promise\Promise { $promise = $this->client ->postAsync($this->path, $this->makeJson($method, $params)); $promise->then(function ($response) use ($fulfilled) { $this->onSuccess($response, $fulfilled); }); $promise->otherwise(function ($exception) use ($rejected) { try { exception()->handle($exception); } catch (Throwable $exception) { $this->onError($exception, $rejected); } }); $this->promises[] = $promise; return $promise; } /** * Settle all promises. * * @return void */ public function wait(): void { if (!empty($this->promises)) { Promise\settle($this->promises)->wait(); } } /** * Makes request to Bitcoin Core. * * @param string $method * @param array $params * * @return \GuzzleHttp\Promise\Promise|\Psr\Http\Message\ResponseInterface */ public function __call(string $method, array $params = []) { if (strtolower(substr($method, -5)) == 'async') { return $this->requestAsync(substr($method, 0, -5), ...$params); } return $this->request($method, ...$params); } /** * Gets config provider class name. * * @return string */ protected function getConfigProvider(): string { return 'Denpa\\Bitcoin\\Config'; } /** * Gets response handler class name. * * @return string */ protected function getResponseHandler(): string { return 'Denpa\\Bitcoin\\Responses\\BitcoindResponse'; } /** * Gets Guzzle handler stack. * * @return \GuzzleHttp\HandlerStack */ protected function getHandler(): HandlerStack { $stack = HandlerStack::create(); $stack->push( Middleware::mapResponse(function (ResponseInterface $response) { $handler = $this->getResponseHandler(); return new $handler($response); }), 'bitcoind_response' ); return $stack; } /** * Construct json request. * * @param string $method * @param mixed $params * * @return array */ protected function makeJson(string $method, $params = []): array { return [ 'json' => [ 'method' => $this->config['preserve_case'] ? $method : strtolower($method), 'params' => (array) $params, 'id' => $this->rpcId++, ], ]; } } <file_sep>/src/Exceptions/ClientException.php <?php declare(strict_types=1); namespace Denpa\Bitcoin\Exceptions; use Exception; abstract class ClientException extends Exception { /** * Returns class name in provided namespace. * * @param string $namespace * * @return \Exception */ public function withNamespace($namespace): Exception { $classname = $this->getClassName(); $class = $namespace."\\$classname"; if (class_exists($class)) { return new $class(...$this->getConstructorParameters()); } return $this; } /** * Gets exception class name. * * @return string */ protected function getClassName(): string { $pos = ($pos = strrpos(static::class, '\\')) !== false ? $pos + 1 : 0; return substr(static::class, $pos); } /** * Returns array of parameters. * * @return array */ abstract protected function getConstructorParameters(); } <file_sep>/src/Traits/Singleton.php <?php declare(strict_types=1); namespace Denpa\Bitcoin\Traits; trait Singleton { /** * Singleton instance. * * @var self */ protected static $instance = null; /** * Gets singleton instance. * * @return self */ public static function getInstance(): self { if (is_null(self::$instance)) { self::$instance = new self(); } return self::$instance; } /** * Clears singleton instance. * * @return void */ public static function clearInstance(): void { self::$instance = null; } } <file_sep>/tests/Exceptions/HandlerTest.php <?php namespace Denpa\Bitcoin\Tests\Exceptions; use Denpa\Bitcoin\Exceptions; use Denpa\Bitcoin\Exceptions\Handler as ExceptionHandler; use Denpa\Bitcoin\Tests\TestCase; use Exception; class HandlerTest extends TestCase { /** * Cleans-up test environment. * * @return void */ protected function tearDown(): void { parent::tearDown(); // Remove all added handlers. ExceptionHandler::clearInstance(); } /** * Test singleton instantiation. * * @return void */ public function testSingleton(): void { $this->assertInstanceOf( ExceptionHandler::class, ExceptionHandler::getInstance() ); } /** * Test handler registration. * * @return void */ public function testRegisterHandler(): void { ExceptionHandler::getInstance()->registerHandler(function ($exception) { $this->assertEquals('Test message', $exception->getMessage()); }); $this->expectException(Exception::class); ExceptionHandler::getInstance()->handle(new Exception('Test message')); } /** * Test exception namespace setter. * * @return void */ public function testSetNamespace(): void { $this->expectException(BadConfigurationException::class); $this->expectExceptionMessage('Test message'); ExceptionHandler::getInstance()->setNamespace('Denpa\\Bitcoin\\Tests\\Exceptions'); ExceptionHandler::getInstance()->handle( new Exceptions\BadConfigurationException(['foo' => 'bar'], 'Test message') ); } } class BadConfigurationException extends Exceptions\BadConfigurationException { // } <file_sep>/SECURITY.md # Security Policy ## Supported Versions Currently there are two supported branches: - 2.1.x for php 7.1 and above - 2.0.x for php 7.0 and below Please be sure to keep your PHP installation up-to-date with recommended versions. | Version | Supported | PHP version | Support Ends | | ------- | ------------------ | ----------- | ------------ | | 2.2.x | :x: | >=7.2 | (WIP) | | 2.1.x | :white_check_mark: | >=7.1 | 01 Jun 2020 | | 2.0.x | :white_check_mark: | <=7.0 | 01 Jun 2020 | | < 2.0 | :x: | <=5.6 | 01 Jun 2018 | ## Reporting a Vulnerability Please report found vulnerabilities directly to my email: <EMAIL> You can use my public key [0xBF7537E8](https://pgp.denpa.pro/) (Fingerprint=B371 A23C C449 703F F1BF 0927 9CF6 463C BF75 37E8) to send me an encrypted message. <file_sep>/tests/Responses/BitcoindResponseTest.php <?php namespace Denpa\Bitcoin\Tests\Responses; use Denpa\Bitcoin\Responses\BitcoindResponse; use Denpa\Bitcoin\Tests\TestCase; use GuzzleHttp\Psr7\BufferStream; use GuzzleHttp\Psr7\Response; use Psr\Http\Message\ResponseInterface; class BitcoindResponseTest extends TestCase { /** * Set up test. * * @return void */ public function setUp(): void { parent::setUp(); $this->guzzleResponse = $this->getBlockResponse(); $this->response = new BitcoindResponse($this->guzzleResponse); $this->response = $this->response->withHeader('X-Test', 'test'); } /** * Test casting response to string. * * @return void */ public function testResponseToString(): void { $response = $this->response; $this->assertSame((string) $response('difficulty'), '1'); $this->assertSame((string) $response('confirmations'), '449162'); $this->assertSame( (string) $response('tx'), json_encode(self::$getBlockResponse['tx']) ); } /** * Test response with result. * * @return void */ public function testResult(): void { $this->assertTrue($this->response->hasResult()); $this->assertEquals( null, $this->response->error() ); $this->assertEquals( self::$getBlockResponse, $this->response->result() ); } /** * Test response without result. * * @return void */ public function testNoResult(): void { $response = new BitcoindResponse($this->rawTransactionError()); $this->assertFalse($response->hasResult()); } /** * Test raw response getter. * * @return void */ public function testRawResponse(): void { $response = $this->response->response(); $this->assertInstanceOf(ResponseInterface::class, $response); $this->assertInstanceOf(Response::class, $response); } /** * Test getter for status code. * * @return void */ public function testStatusCode(): void { $this->assertEquals(200, $this->response->getStatusCode()); } /** * Test getter for reason phrase. * * @return void */ public function testReasonPhrase(): void { $this->assertEquals('OK', $this->response->getReasonPhrase()); } /** * Test changing status for response. * * @return void */ public function testWithStatus(): void { $response = $this->response->withStatus(444, 'test'); $this->assertEquals(444, $response->getStatusCode()); $this->assertEquals('test', $response->getReasonPhrase()); } /** * Test error in response. * * @return void */ public function testError(): void { $response = new BitcoindResponse($this->rawTransactionError()); $this->assertTrue($response->hasError()); $this->assertEquals( null, $response->result() ); $this->assertEquals( self::$rawTransactionError, $response->error() ); } /** * Test no error in response. * * @return void */ public function testNoError(): void { $this->assertFalse($this->response->hasError()); } /** * Test getting values through ArrayAccess. * * @return void */ public function testArrayAccessGet(): void { $this->assertEquals( self::$getBlockResponse['hash'], $this->response['hash'] ); } /** * Test setting values through ArrayAccess. * * @return void */ public function testArrayAccessSet(): void { $this->expectException(\BadMethodCallException::class); $this->expectExceptionMessage('Cannot modify immutable object'); $this->response['hash'] = 'test'; } /** * Test unsetting values through ArrayAccess. * * @return void */ public function testArrayAccessUnset(): void { $this->expectException(\BadMethodCallException::class); $this->expectExceptionMessage('Cannot modify immutable object'); unset($this->response['hash']); } /** * Test checking value through ArrayAccess. * * @return void */ public function testArrayAccessIsset(): void { $this->assertTrue(isset($this->response['hash'])); $this->assertFalse(isset($this->response['cookie'])); } /** * Test setting key through invokation. * * @return void */ public function testInvoke(): void { $response = $this->response; $this->assertEquals( self::$getBlockResponse['hash'], $response('hash')->get() ); } /** * Test getting value by key. * * @return void */ public function testGet(): void { $this->assertEquals( self::$getBlockResponse['hash'], $this->response->get('hash') ); $this->assertEquals( self::$getBlockResponse['tx'][0], $this->response->get('tx.0') ); } /** * Test getting first element of array. * * @return void */ public function testFirst(): void { $this->assertEquals( self::$getBlockResponse['tx'][0], $this->response->key('tx')->first() ); $this->assertEquals( self::$getBlockResponse['tx'][0], $this->response->first('tx') ); $this->assertEquals( reset(self::$getBlockResponse), $this->response->first() ); $this->assertEquals( self::$getBlockResponse['hash'], $this->response->key('hash')->first() ); } /** * Test getting last element of array. * * @return void */ public function testLast(): void { $this->assertEquals( self::$getBlockResponse['tx'][3], $this->response->key('tx')->last() ); $this->assertEquals( self::$getBlockResponse['tx'][3], $this->response->last('tx') ); $this->assertEquals( end(self::$getBlockResponse), $this->response->last() ); $this->assertEquals( self::$getBlockResponse['hash'], $this->response->key('hash')->last() ); } /** * Test method used to check if array has key. * * @return void */ public function testHas(): void { $response = $this->response; $this->assertTrue($response->has('hash')); $this->assertTrue($response->has('tx.0')); $this->assertTrue($response('tx')->has(0)); $this->assertFalse($response->has('tx.3')); $this->assertFalse($response->has('cookies')); $this->assertFalse($response->has('height')); } /** * Test method used to check if array has key pointing to non-null value. * * @return void */ public function testExists(): void { $this->assertTrue($this->response->exists('hash')); $this->assertTrue($this->response->exists('tx.0')); $this->assertTrue($this->response->exists('tx.3')); $this->assertTrue($this->response->exists('height')); $this->assertFalse($this->response->exists('cookies')); } /** * Test method used to check if array has value. * * @return void */ public function testContains(): void { $this->assertTrue($this->response->contains('00000000839a8e6886ab5951d76f411475428afc90947ee320161bbf18eb6048')); $this->assertTrue($this->response->contains('bedb088c480e5f7424a958350f2389c839d17e27dae13643632159b9e7c05482', 'tx')); $this->assertFalse($this->response->contains('cookies')); } /** * Test method used to check if array has value on non-array. * * @return void */ public function testContainsOnNonArray(): void { $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage('method contains() should be called on array'); $this->response->key('version')->contains('test'); } /** * Test getting array keys. * * @return void */ public function testKeys(): void { $this->assertEquals( array_keys(self::$getBlockResponse), $this->response->keys() ); $this->assertEquals( array_keys(self::$getBlockResponse['tx']), $this->response->keys('tx') ); } /** * Test getting array keys on non array. * * @return void */ public function testKeysOnNonArray(): void { $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage('method keys() should be called on array'); $this->response->keys('version'); } /** * Test getting array values. * * @return void */ public function testValues(): void { $this->assertEquals( array_values(self::$getBlockResponse), $this->response->values() ); $this->assertEquals( array_values(self::$getBlockResponse['tx']), $this->response->values('tx') ); } /** * Test getting array values on non array. * * @return void */ public function testValuesOnNonArray(): void { $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage('method values() should be called on array'); $this->response->values('version'); } /** * Test getting random elements from array. * * @return void */ public function testRandom(): void { $tx1 = $this->response->random(1, 'tx'); $tx2 = $this->response->random(1, 'tx'); $this->assertContains($tx1, self::$getBlockResponse['tx']); $this->assertContains($tx2, self::$getBlockResponse['tx']); $random = $this->response->random(); $this->assertContains($random, self::$getBlockResponse); $random2 = $this->response->random(2); $this->assertCount(2, $random2); foreach ($random2 as $key => $value) { $this->assertTrue((self::$getBlockResponse[$key] ?? null) == $value); } $random3 = $this->response->random(1, 'merkleroot'); $this->assertEquals(self::$getBlockResponse['merkleroot'], $random3); $random4 = $this->response->random(6, 'tx'); $this->assertEquals(self::$getBlockResponse['tx'], $random4); $response = $this->response; $random5 = $response('tx')->random(6); $this->assertEquals(self::$getBlockResponse['tx'], $random5); } /** * Test counting number of elements in array. * * @return void */ public function testCount(): void { $this->assertEquals( count(self::$getBlockResponse), count($this->response) ); $this->assertEquals( count(self::$getBlockResponse), $this->response->count() ); $this->assertEquals( 4, $this->response->count('tx') ); } /** * Test count on non array. * * @return void */ public function testCountOnNonArray(): void { $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage('method count() should be called on array'); $this->response->count('hash'); } /** * Test getting protocol version. * * @return void */ public function testProtocolVersion(): void { $response = $this->response->withProtocolVersion('1.1'); $protocolVersion = $response->getProtocolVersion(); $this->assertEquals('1.1', $protocolVersion); } /** * Test setting response header. * * @return void */ public function testWithHeader(): void { $response = $this->response->withHeader('X-Test', 'bar'); $this->assertTrue($response->hasHeader('X-Test')); $this->assertEquals('bar', $response->getHeaderLine('X-Test')); } /** * Test adding header to response. * * @return void */ public function testWithAddedHeader(): void { $response = $this->response->withAddedHeader('X-Bar', 'baz'); $this->assertTrue($response->hasHeader('X-Test')); $this->assertTrue($response->hasHeader('X-Bar')); } /** * Test removing headers from response. * * @return void */ public function testWithoutHeader(): void { $response = $this->response->withoutHeader('X-Test'); $this->assertFalse($response->hasHeader('X-Test')); } /** * Test getting response header. * * @return void */ public function testGetHeader(): void { $response = $this->response->withHeader('X-Bar', 'baz'); $expected = [ 'X-Test' => ['test'], 'X-Bar' => ['baz'], ]; $this->assertEquals($expected, $response->getHeaders()); foreach ($expected as $name => $value) { $this->assertEquals($value, $response->getHeader($name)); } } /** * Test setting response body. * * @return void */ public function testBody(): void { $stream = new BufferStream(); $stream->write('cookies'); $response = $this->response->withBody($stream); $this->assertEquals('cookies', $response->getBody()->__toString()); } /** * Test serialization. * * @return void */ public function testSerialize(): void { $serializedContainer = serialize($this->response->__serialize()); $serialized = sprintf( 'O:%u:"%s":1:{%s}', strlen(BitcoindResponse::class), BitcoindResponse::class, substr($serializedContainer, 5, (strlen($serializedContainer) - 6)) ); $this->assertEquals( $serialized, serialize($this->response) ); } /** * Test unserialization. * * @return void */ public function testUnserialize(): void { $container = $this->response->toContainer(); $this->assertEquals( $container, unserialize(serialize($this->response))->toContainer() ); } /** * Test serialization to JSON. * * @return void */ public function testJsonSerialize(): void { $this->assertEquals( json_encode($this->response->toContainer()), json_encode($this->response) ); } /** * Test sum of array values. * * @return void */ public function testSum(): void { $response = $this->response; $this->assertEquals(7, $response('test1.*.*')->sum('amount')); $this->assertEquals(7, $response('test1.*.*.amount')->sum()); $this->assertEquals(7, $response->sum('test1.*.*.amount')); } /** * Test array flattening. * * @return void */ public function testFlatten(): void { $response = $this->response; $this->assertEquals([3, 4], $response('test1.*.*')->flatten('amount')); $this->assertEquals([3, 4], $response('test1.*.*.amount')->flatten()); $this->assertEquals([3, 4], $response->flatten('test1.*.*.amount')); } } <file_sep>/tests/Exceptions/BadRemoteCallExceptionTest.php <?php namespace Denpa\Bitcoin\Tests\Exceptions; use Denpa\Bitcoin\Exceptions\BadRemoteCallException; use Denpa\Bitcoin\Responses\Response; use Denpa\Bitcoin\Tests\TestCase; class BadRemoteCallExceptionTest extends TestCase { /** * Set-up test environment. * * @return void */ protected function setUp(): void { parent::setUp(); $this->response = $this ->getMockBuilder(Response::class) ->disableOriginalConstructor() ->getMock(); $this->response ->expects($this->once()) ->method('error') ->willReturn(['message' => 'Test message', 'code' => 1]); } /** * Test trowing exception. * * @return void */ public function testThrow(): void { $this->expectException(BadRemoteCallException::class); $this->expectExceptionMessage('Test message'); $this->expectExceptionCode(1); throw new BadRemoteCallException($this->response); } /** * Test response getter. * * @return void */ public function testGetResponse(): void { $exception = new BadRemoteCallException($this->response); $this->assertInstanceOf(Response::class, $exception->getResponse()); } /** * Test constructor parameters getter. * * @return void */ public function testGetConstructionParameters(): void { $exception = new FakeBadRemoteCallException($this->response); $this->assertEquals( [ $exception->getResponse(), ], $exception->getConstructorParameters() ); } } class FakeBadRemoteCallException extends BadRemoteCallException { public function getConstructorParameters(): array { return parent::getConstructorParameters(); } } <file_sep>/src/Exceptions/BadRemoteCallException.php <?php declare(strict_types=1); namespace Denpa\Bitcoin\Exceptions; use Denpa\Bitcoin\Responses\Response; class BadRemoteCallException extends ClientException { /** * Response object. * * @var \Denpa\Bitcoin\Responses\Response */ protected $response; /** * Constructs new bad remote call exception. * * @param \Denpa\Bitcoin\Responses\Response $response * * @return void */ public function __construct(Response $response) { $this->response = $response; $error = $response->error(); parent::__construct($error['message'], $error['code']); } /** * Gets response object. * * @return \Denpa\Bitcoin\Responses\Response */ public function getResponse(): Response { return $this->response; } /** * Returns array of parameters. * * @return array */ protected function getConstructorParameters(): array { return [ $this->getResponse(), ]; } } <file_sep>/src/Config.php <?php declare(strict_types=1); namespace Denpa\Bitcoin; use Denpa\Bitcoin\Traits\Collection; use Denpa\Bitcoin\Traits\ImmutableArray; class Config implements \ArrayAccess, \Countable { use Collection; use ImmutableArray; /** * Default configuration. * * @var array */ protected $config = [ 'scheme' => 'http', 'host' => '127.0.0.1', 'port' => 8332, 'user' => null, 'password' => <PASSWORD>, 'ca' => null, 'timeout' => false, 'preserve_case' => false, ]; /** * Constructs new configuration. * * @param array $config * * @return void */ public function __construct(array $config = []) { $this->set($config); } /** * Gets CA file from config. * * @return string|null */ public function getCa(): ?string { if (isset($this->config['ca']) && is_file($this->config['ca'])) { return $this->config['ca']; } return null; } /** * Gets authentication array. * * @return array */ public function getAuth(): array { return [ $this->config['user'], $this->config['password'], ]; } /** * Gets DSN string. * * @return string */ public function getDsn(): string { $scheme = $this->config['scheme'] ?? 'http'; return $scheme.'://'. $this->config['host'].':'. $this->config['port']; } /** * Merge config. * * @param array $config * * @return self */ public function set(array $config = []): self { // use same var name as laravel-bitcoinrpc $config['password'] = $config['password'] ?? $config['pass'] ?? null; if (is_null($config['password'])) { // use default value from getDefaultConfig() unset($config['password']); } $this->config = array_merge($this->config, $config); return $this; } /** * Gets config as array. * * @return array */ protected function toArray(): array { return $this->config; } } <file_sep>/src/Traits/Collection.php <?php declare(strict_types=1); namespace Denpa\Bitcoin\Traits; use InvalidArgumentException; trait Collection { /** * Current key. * * @var string */ protected $current; /** * Gets data by using key with dotted notation. * * @param string|null $key * * @return mixed */ public function get(?string $key = null) { $key = $this->constructKey($key); if (is_null($key)) { $array = $this->toArray(); return $this->count() == 1 ? end($array) : $array; } return $this->parseKey($key, function ($part, $result) { if (isset($result[$part])) { return $result[$part]; } }); } /** * Checks if key exists. * * @param string|null $key * * @return bool */ public function exists(?string $key = null): bool { $key = $this->constructKey($key); return $this->parseKey($key, function ($part, $result) { return array_key_exists($part, $result); }); } /** * Checks if key exists and not null. * * @param string|null $key * * @return bool */ public function has(?string $key = null): bool { $key = $this->constructKey($key); return $this->parseKey($key, function ($part, $result) { return isset($result[$part]); }); } /** * Gets first element. * * @param string|null $key * * @return mixed */ public function first(?string $key = null) { $value = $this->get($key); if (is_array($value)) { return reset($value); } return $value; } /** * Gets last element. * * @param string|null $key * * @return mixed */ public function last(?string $key = null) { $value = $this->get($key); if (is_array($value)) { return end($value); } return $value; } /** * Checks if response contains value. * * @param mixed $needle * @param string|null $key * * @return bool */ public function contains($needle, ?string $key = null): bool { $value = $this->get($key); if (!is_array($value)) { throw new InvalidArgumentException( 'method contains() should be called on array' ); } return in_array($needle, $value); } /** * Sets current key. * * @param string|null $key * * @return self */ public function key(?string $key = null): self { $new = clone $this; $new->current = $key; return $new; } /** * Gets response keys. * * @param string|null $key * * @return array */ public function keys(?string $key = null): array { $value = $this->get($key); if (!is_array($value)) { throw new InvalidArgumentException( 'method keys() should be called on array' ); } return array_keys($value); } /** * Gets response values. * * @param string|null $key * * @return array */ public function values(?string $key = null): array { $value = $this->get($key); if (!is_array($value)) { throw new InvalidArgumentException( 'method values() should be called on array' ); } return array_values($value); } /** * Gets random value. * * @param int $number * @param string|null $key * * @return mixed */ public function random(int $number = 1, ?string $key = null) { $value = $this->get($key); if (is_array($value)) { $keys = array_keys($value); $keysLength = count($keys); shuffle($keys); if ($number > $keysLength) { $number = $keysLength; } for ($result = [], $count = 0; $count < $number; $count++) { $result[$keys[$count]] = $value[$keys[$count]]; } return count($result) > 1 ? $result : current($result); } return $value; } /** * Counts response items. * * @param string|null $key * * @return int */ public function count(?string $key = null): int { if (is_null($this->constructKey($key))) { return count($this->toArray()); } $value = $this->get($key); if (!is_array($value)) { throw new InvalidArgumentException( 'method count() should be called on array' ); } return count($value); } /** * Flattens multi-dimensional array. * * @param string|null $key * * @return array */ public function flatten(?string $key = null): array { $array = new \RecursiveIteratorIterator( new \RecursiveArrayIterator((array) $this->get($key)) ); $tmp = []; foreach ($array as $value) { $tmp[] = $value; } return $tmp; } /** * Gets sum of values. * * @param string|null $key * * @return float */ public function sum(?string $key = null): float { return array_sum($this->flatten($key)); } /** * Gets response item by key. * * @param string|null $key * * @return self */ public function __invoke(?string $key = null): self { return $this->key($key); } /** * Converts response to string on current key. * * @return string */ public function __toString(): string { $value = $this->get(); if (is_array($value) || is_object($value)) { return json_encode($value); } return (string) $value; } /** * Constructs full key. * * @param string|null $key * * @return string|null */ protected function constructKey(?string $key = null): ?string { if (!is_null($key) && !is_null($this->current)) { return $this->current.'.'.$key; } if (is_null($key) && !is_null($this->current)) { return $this->current; } return $key; } /** * Parses dotted notation. * * @param array|string $key * @param callable $callback * @param array|null $result * * @return mixed */ protected function parseKey($key, callable $callback, ?array $result = null) { $parts = is_array($key) ? $key : explode('.', trim($key, '.')); $result = $result ?: $this->toArray(); while (!is_null($part = array_shift($parts))) { if ($part == '*') { array_walk($result, function (&$value) use ($parts, $callback) { $value = $this->parseKey($parts, $callback, $value); }); return $result; } if (!$return = $callback($part, $result)) { return $return; } $result = $result[$part]; } return $return; } } <file_sep>/src/Traits/ImmutableArray.php <?php declare(strict_types=1); namespace Denpa\Bitcoin\Traits; use BadMethodCallException; trait ImmutableArray { /** * Assigns a value to the specified offset. * * @param mixed $offset * @param mixed $value * * @return void */ public function offsetSet($offset, $value): void { throw new BadMethodCallException('Cannot modify immutable object'); } /** * Whether or not an offset exists. * * @param mixed $offset * * @return bool */ public function offsetExists($offset): bool { return isset($this->toArray()[$offset]); } /** * Unsets the offset. * * @param mixed $offset * * @return void */ public function offsetUnset($offset): void { throw new BadMethodCallException('Cannot modify immutable object'); } /** * Returns the value at specified offset. * * @param mixed $offset * * @return mixed */ public function offsetGet($offset): mixed { return $this->toArray()[$offset] ?? null; } } <file_sep>/src/Exceptions/BadConfigurationException.php <?php declare(strict_types=1); namespace Denpa\Bitcoin\Exceptions; class BadConfigurationException extends ClientException { /** * Configuration container. * * @var array */ protected $config; /** * Constructs new bad configuration exception. * * @param array $config * @param mixed $args,... * * @return void */ public function __construct(array $config, ...$args) { $this->config = $config; parent::__construct(...$args); } /** * Gets config data. * * @return array */ public function getConfig(): array { return $this->config; } /** * Returns array of parameters. * * @return array */ protected function getConstructorParameters(): array { return [ $this->getConfig(), $this->getMessage(), $this->getCode(), ]; } } <file_sep>/src/Exceptions/ConnectionException.php <?php declare(strict_types=1); namespace Denpa\Bitcoin\Exceptions; use GuzzleHttp\Psr7\Request; class ConnectionException extends ClientException { /** * Request object. * * @var \GuzzleHttp\Psr7\Request */ protected $request; /** * Constructs new connection exception. * * @param \GuzzleHttp\Psr7\Request $request * @param mixed $args,... * * @return void */ public function __construct(Request $request, ...$args) { $this->request = $request; parent::__construct(...$args); } /** * Gets request object. * * @return \GuzzleHttp\Psr7\Request */ public function getRequest(): Request { return $this->request; } /** * Returns array of parameters. * * @return array */ protected function getConstructorParameters(): array { return [ $this->getRequest(), $this->getMessage(), $this->getCode(), ]; } }
6a2e9a7f713421f26f46299be51450bbb6a8f958
[ "Markdown", "PHP" ]
29
PHP
denpamusic/php-bitcoinrpc
3162c0206960173dd3c03c0ca76ee879bbb8486d
de15416a12c17d3cb866e7dad52f2df046b82ea2
refs/heads/master
<repo_name>GabrielProgrammer/BD<file_sep>/BD/NetBeansProjects/Gabriel/src/gabriel/Funcionario.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package gabriel; /** * * @author aluno */ public class Funcionario extends Pessoa { private int codFuncionario; private String cartTrabalho; private String tipodesangue; private String planoSaude; private float salario; private String banco; private int numerobanco; private int ag; private int cc; /** * @return the codFuncionario */ public int getCodFuncionario() { return codFuncionario; } /** * @param codFuncionario the codFuncionario to set */ public void setCodFuncionario(int codFuncionario) { this.codFuncionario = codFuncionario; } /** * @return the cartTrabalho */ public String getCartTrabalho() { return cartTrabalho; } /** * @param cartTrabalho the cartTrabalho to set */ public void setCartTrabalho(String cartTrabalho) { this.cartTrabalho = cartTrabalho; } /** * @return the tipodesangue */ public String getTipodesangue() { return tipodesangue; } /** * @param tipodesangue the tipodesangue to set */ public void setTipodesangue(String tipodesangue) { this.tipodesangue = tipodesangue; } /** * @return the planoSaude */ public String getPlanoSaude() { return planoSaude; } /** * @param planoSaude the planoSaude to set */ public void setPlanoSaude(String planoSaude) { this.planoSaude = planoSaude; } /** * @return the salario */ public float getSalario() { return salario; } /** * @param salario the salario to set */ public void setSalario(float salario) { this.salario = salario; } /** * @return the banco */ public String getBanco() { return banco; } /** * @param banco the banco to set */ public void setBanco(String banco) { this.banco = banco; } /** * @return the numerobanco */ public int getNumerobanco() { return numerobanco; } /** * @param numerobanco the numerobanco to set */ public void setNumerobanco(int numerobanco) { this.numerobanco = numerobanco; } /** * @return the ag */ public int getAg() { return ag; } /** * @param ag the ag to set */ public void setAg(int ag) { this.ag = ag; } /** * @return the cc */ public int getCc() { return cc; } /** * @param cc the cc to set */ public void setCc(int cc) { this.cc = cc; } } <file_sep>/BD/NetBeansProjects/Gabriel/src/gabriel/Item.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package gabriel; /** * * @author aluno */ public class Item { private String quantidade; private int codProduto; private int valorunitario; /** * @return the quantidade */ public String getQuantidade() { return quantidade; } /** * @param quantidade the quantidade to set */ public void setQuantidade(String quantidade) { this.quantidade = quantidade; } /** * @return the codProduto */ public int getCodProduto() { return codProduto; } /** * @param codProduto the codProduto to set */ public void setCodProduto(int codProduto) { this.codProduto = codProduto; } /** * @return the valorunitario */ public int getValorunitario() { return valorunitario; } /** * @param valorunitario the valorunitario to set */ public void setValorunitario(int valorunitario) { this.valorunitario = valorunitario; } }
a82c929928d355a32a1addb7a849a2e93c65fb89
[ "Java" ]
2
Java
GabrielProgrammer/BD
fd9464152c1e170ace8ef7faf7d48846353e0846
cbb02473ba8813cc84954883b2088576716b6e86
refs/heads/master
<file_sep>var js = function(dbot) { var dbot = dbot; var commands = { '~js': function(data, params) { var q = data.message.valMatch(/^~js (.*)/, 2); dbot.say(data.channel, eval(q[1])); } }; return { 'onLoad': function() { return commands; } }; }; exports.fetch = function(dbot) { return js(dbot); }; <file_sep>var fs = require('fs'); var adminCommands = function(dbot) { var dbot = dbot; var commands = { 'join': function(data, params) { dbot.instance.join(params[1]); dbot.say(dbot.admin, 'Joined ' + params[1]); }, 'opme': function(data, params) { dbot.instance.send('MODE #42 +o ', dbot.admin); }, 'part': function(data, params) { dbot.instance.part(params[1]); }, 'reload': function(data, params) { dbot.db = JSON.parse(fs.readFileSync('db.json', 'utf-8')); dbot.reloadModules(); dbot.say(data.channel, 'Reloaded that shit.'); }, 'say': function(data, params) { var c = params[1]; var m = params.slice(2).join(' '); dbot.say(c, m); }, 'load': function(data, params) { dbot.moduleNames.push(params[1]); dbot.reloadModules(); dbot.say(data.channel, 'Loaded new module: ' + params[1]); }, 'unload': function(data, params) { if(dbot.moduleNames.include(params[1])) { dbot.moduleNames[params[1]] = undefined; dbot.reloadModules(); dbot.say(data.channel, 'Turned off module: ' + params[1]); } else { dbot.say(data.channel, 'Module ' + params[1] + ' isn\'t loaded... Idiot...'); } }, 'ban': function(data, params) { if(dbot.db.bans.hasOwnProperty(params[2])) { dbot.db.bans[params[2]].push(params[1]); } else { dbot.db.bans[params[2]] = [ params[1] ]; } dbot.say(data.channel, params[1] + ' banned from ' + params[2]); }, 'unban': function(data, params) { if(dbot.db.bans.hasOwnProperty(params[2]) && dbot.db.bans[params[2]].include(params[1])) { dbot.db.bans[params[2]].splice(dbot.db.bans[params[2]].indexOf(params[1]), 1); dbot.say(data.channel, params[1] + ' unbanned from ' + params[2]); } else { dbot.say(data.channel, 'It appears ' + params[1] + 'wasn\'t banned from that command, you fool.'); } }, 'modehate': function(data, params) { dbot.db.modehate.push(params[1]); dbot.say(data.channel, 'Now modehating on ' + params[1]); }, 'unmodehate': function(data, params) { dbot.db.modehate.splice(dbot.db.modehate.indexOf(params[1]), 1); dbot.say(data.channel, 'No longer modehating on ' + params[1]); }, 'lock': function(data, params) { dbot.db.locks.push(params[1]); dbot.say(data.channel, 'Locked ' + params[1] + ' quotes.'); } }; return { 'listener': function(data) { if(data.channel == dbot.name) data.channel = data.user; params = data.message.split(' '); if(commands.hasOwnProperty(params[0]) && data.user == dbot.admin) { commands[params[0]](data, params); dbot.save(); } }, 'on': 'PRIVMSG' }; }; exports.fetch = function(dbot) { return adminCommands(dbot); }; <file_sep>var puns = function(dbot) { var dbot = dbot; return { 'listener': function(data) { if(data.user == 'reality') { dbot.instance.say(data.channel, dbot.db.quoteArrs['realityonce'].random()); } else if(dbot.db.quoteArrs.hasOwnProperty(data.user.toLowerCase())) { dbot.say(data.channel, data.user + ': ' + dbot.db.quoteArrs[data.user.toLowerCase()].random()); } else if(dbot.instance.inChannel(data.channel)) { dbot.instance.say('aisbot', '.karma ' + data.user); dbot.waitingForKarma = data.channel; } }, 'on': 'JOIN' }; } exports.fetch = function(dbot) { return puns(dbot); }; <file_sep>var quotes = function(dbot) { var quotes = dbot.db.quoteArrs; var addStack = []; var rmAllowed = true; var commands = { '~q': function(data, params) { var q = data.message.valMatch(/^~q ([\d\w\s]*)/, 2); if(q) { q[1] = q[1].trim(); key = q[1].toLowerCase(); if(quotes.hasOwnProperty(key)) { dbot.say(data.channel, q[1] + ': ' + quotes[key].random()); } else { dbot.say(data.channel, 'Nobody loves ' + q[1]); } } }, '~qsearch': function(data, params) { if(params[2] === undefined) { dbot.say(data.channel, 'Next time provide a search parameter. Commence incineration.'); } else { params[1].trim(); key = params[1].toLowerCase(); if(!quotes.hasOwnProperty(key)) { dbot.say(data.channel, 'That category has no quotes in it. Commence incineration.'); } else { var matches = []; quotes[key].each(function(quote) { if(quote.indexOf(params[2]) != -1) { matches.push(quote); } }.bind(this)); if(matches.length == 0) { dbot.say(data.channel, 'No results found.'); } else { dbot.say(data.channel, params[1] + ' (' + params[2] + '): ' + matches.random() + ' [' + matches.length + ' results]'); } } } }, '~rmlast': function(data, params) { if(rmAllowed == true || data.user == dbot.admin) { var q = data.message.valMatch(/^~rmlast ([\d\w\s]*)/, 2); if(q) { q[1] = q[1].trim() key = q[1].toLowerCase(); if(quotes.hasOwnProperty(q[1])) { if(!dbot.db.locks.include(q[1])) { var quote = quotes[key].pop(); rmAllowed = false; dbot.say(data.channel, '\'' + quote + '\' removed from ' + q[1]); } else { dbot.say(data.channel, q[1] + ' is locked. Commence incineration.'); } } else { dbot.say(data.channel, 'No quotes exist under ' + q[1]); } } else { var last = addStack.pop(); if(last) { if(!dbot.db.locks.include(last)) { quotes[last].pop(); rmAllowed = false; dbot.say(data.channel, 'Last quote removed from ' + last + '.'); } else { dbot.say(data.channel, last + ' is locked. Commence incineration.'); } } else { dbot.say(data.channel, 'No quotes were added recently.'); } } } else { dbot.say(data.channel, 'No spamming that shit. Try again in a few minutes...'); } }, '~qcount': function(data, params) { var q = data.message.valMatch(/^~qcount ([\d\w\s]*)/, 2); if(q) { q[1] = q[1].trim(); key = q[1].toLowerCase(); if(quotes.hasOwnProperty(key)) { dbot.say(data.channel, q[1] + ' has ' + quotes[key].length + ' quotes.'); } else { dbot.say(data.channel, 'No quotes under ' + q[1]); } } }, '~qadd': function(data, params) { var q = data.message.valMatch(/^~qadd ([\d\w\s]*)=(.+)$/, 3); if(q) { key = q[1].toLowerCase(); if(!Object.isArray(quotes[key])) { quotes[key] = []; } else { if (q[2] in quotes[key]) { dbot.say(data.channel, 'Quote already in DB. Initiate incineration.'); return; } } quotes[key].push(q[2]); addStack.push(q[1]); rmAllowed = true; dbot.say(data.channel, 'Quote saved in \'' + q[1] + '\' (' + quotes[key].length + ')'); } else { dbot.say(data.channel, 'Invalid syntax. Initiate incineration.'); } }, '~qset': function(data, params) { var q = data.message.valMatch(/^~qset ([\d\w\s]*)=(.+)$/, 3); if(q) { q[1] = q[1].trim(); key = q[1].toLowerCase(); if(!quotes.hasOwnProperty(key) || (quotes.hasOwnProperty(key) && quotes[key].length == 1)) { quotes[key] = [q[2]]; dbot.say(data.channel, 'Quote saved as ' + q[1]); } else { dbot.say(data.channel, 'No replacing arrays, you whore.'); } } }, '~rq': function(data, params) { var rQuote = Object.keys(quotes).random(); dbot.say(data.channel, rQuote + ': ' + quotes[rQuote].random()); }, '~reality': function(data, params) { dbot.say(data.channel, dbot.db.quoteArrs['realityonce'].random()); }, '~d': function(data, params) { dbot.say(data.channel, data.user + ': ' + dbot.db.quoteArrs['depressionbot'].random()); }, '~link': function(data, params) { if(params[1] === undefined || !quotes.hasOwnProperty(params[1])) { dbot.say(data.channel, 'Syntax error. Commence incineration.'); } else { dbot.say(data.channel, 'Link to "'+params[1]+'" - http://nc.no.de:443/quotes/'+params[1]); } } }; return { 'onLoad': function() { dbot.timers.addTimer(1000 * 60 * 3, function() { rmAllowed = true; }); return commands; }, // For automatic quote retrieval 'listener': function(data, params) { if(data.user == 'reality') { var once = data.message.valMatch(/^I ([\d\w\s,'-]* once)/, 2); } else { var once = data.message.valMatch(/^reality ([\d\w\s,'-]* once)/, 2); } if(once) { if((dbot.db.bans.hasOwnProperty('~qadd') && dbot.db.bans['~qadd'].include(data.user)) || dbot.db.bans['*'].include(data.user)) { dbot.say(data.channel, data.user + ' is banned from using this command. Commence incineration.'); } else { dbot.db.quoteArrs['realityonce'].push('reality ' + once[1] + '.'); addStack.push('realityonce'); rmAllowed = true; dbot.instance.say(data.channel, '\'reality ' + once[1] + '.\' saved.'); } } }, 'on': 'PRIVMSG' }; }; exports.fetch = function(dbot) { return quotes(dbot); }; <file_sep>var timers = function() { var timers = []; return { 'addTimer': function(interval, callback) { // Because who puts the callback first. Really. timers.push(setInterval(callback, interval)); }, 'clearTimers': function() { for(var i;i<timers.length;i++) { clearInterval(timers[i]); } } }; }; exports.create = function() { return timers(); } <file_sep>var kick = function(dbot) { var dbot = dbot; return { 'listener': function(data) { if(data.kickee == dbot.name) { dbot.instance.join(data.channel); dbot.say(data.channel, 'Thou shalt not kick ' + dbot.name); dbot.db.kicks[dbot.name] += 1; } else { if(dbot.db.modehate.include(data.user)) { dbot.instance.send('KICK ' + data.channel + ' ' + data.user + ' :gtfo (MODEHATE)'); if(!dbot.db.kicks.hasOwnProperty(data.user)) { dbot.db.kicks[data.user] = 1; } else { dbot.db.kicks[data.user] += 1; } } if(!dbot.db.kicks.hasOwnProperty(data.kickee)) { dbot.db.kicks[data.kickee] = 1; } else { dbot.db.kicks[data.kickee] += 1; } if(!dbot.db.kickers.hasOwnProperty(data.user)) { dbot.db.kickers[data.user] = 1; } else { dbot.db.kickers[data.user] += 1; } dbot.say(data.channel, data.kickee + '-- (' + data.kickee + ' has been kicked ' + dbot.db.kicks[data.kickee] + ' times)'); } }, on: 'KICK' }; }; exports.fetch = function(dbot) { return kick(dbot); };
b8af097b4a1bb73ab099804706dadf5b0a357379
[ "JavaScript" ]
6
JavaScript
wasmith/depressionbot
3d79363b592c0d70c9d6cdc570b6c7d97d4c35fc
78f33b3a189c4d8e89f6107168ba4780ec0c5fa5
refs/heads/master
<repo_name>jobsonp/android-google-weather<file_sep>/trunk/GoogleWeather/src/com/android/weather/adapter/CityListItemSimpleAdapter.java /** * */ package com.android.weather.adapter; import java.util.HashMap; import java.util.List; import java.util.Map; import com.android.weather.R; import com.android.weather.db.DatabaseManager; import com.android.weather.view.NeedShowWethInfoCityListActivity; import android.app.AlertDialog; import android.content.Context; import android.content.Intent; import android.sax.StartElementListener; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.AnimationSet; import android.view.animation.DecelerateInterpolator; import android.view.animation.RotateAnimation; import android.view.animation.ScaleAnimation; import android.view.animation.TranslateAnimation; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.ImageView; import android.widget.TextView; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.Toast; /** * @author Himi * */ public class CityListItemSimpleAdapter extends BaseAdapter { private LayoutInflater mInflater; private List<HashMap<String, Object>> list; private int layoutID; private String flag[]; private int ItemIDs[]; private Context context = null; private DatabaseManager dbManager; public CityListItemSimpleAdapter(Context context, List<HashMap<String, Object>> list, int layoutID, String flag[], int ItemIDs[]) { this.mInflater = LayoutInflater.from(context); this.list = list; this.layoutID = layoutID; this.flag = flag; this.ItemIDs = ItemIDs; this.context = context; this.dbManager = new DatabaseManager(context); } @Override public int getCount() { // TODO Auto-generated method stub return list.size(); } @Override public Object getItem(int arg0) { // TODO Auto-generated method stub return 0; } @Override public long getItemId(int arg0) { // TODO Auto-generated method stub return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { convertView = mInflater.inflate(layoutID, null); for (int i = 0; i < flag.length; i++) {//备注1 if (convertView.findViewById(ItemIDs[i]) instanceof ImageView) { ImageView iv = (ImageView) convertView.findViewById(ItemIDs[i]); iv.setBackgroundResource((Integer) list.get(position).get( flag[i])); } else if (convertView.findViewById(ItemIDs[i]) instanceof TextView) { TextView tv = (TextView) convertView.findViewById(ItemIDs[i]); tv.setText((String) list.get(position).get(flag[i])); }else{ //...备注2 } } addListener(convertView); return convertView; } /** * * 备注3 */ public void addListener(View convertView) { final Button btn1 = (Button)convertView.findViewById(R.id.button1);//旋转按钮 final Button delBtn = (Button)convertView.findViewById(R.id.delbutton);//删除按钮 final ImageView imageview = (ImageView)convertView.findViewById(R.id.imageview1);//list图片 final TextView tview = (TextView)convertView.findViewById(R.id.storeListview); btn1.setOnClickListener( new View.OnClickListener() { int count = 0; @Override public void onClick(View v) { Toast.makeText(NeedShowWethInfoCityListActivity.dcity, "click", Toast.LENGTH_SHORT).show(); // AnimationSet aniSet = new AnimationSet(true); // aniSet.setInterpolator(new DecelerateInterpolator()); if(count == 0){//显示删除按钮 RotateAnimation rotate = new RotateAnimation(0, 90, Animation.RELATIVE_TO_SELF,0.5f, Animation.RELATIVE_TO_SELF, 0.5f); TranslateAnimation translate = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 1f,Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f,Animation.RELATIVE_TO_SELF, 0f); // AlphaAnimation alpha = new AlphaAnimation(0f, 1f); rotate.setDuration(800); rotate.setFillAfter(true); translate.setDuration(10); translate.setFillAfter(true); // alpha.setDuration(800); // alpha.setFillAfter(true); btn1.startAnimation(rotate); delBtn.setVisibility(View.VISIBLE); imageview.setVisibility(View.GONE); delBtn.startAnimation(translate); // delBtn.startAnimation(alpha); count += 1; }else if(count==1){//隐藏删除按钮 RotateAnimation rotate = new RotateAnimation(90, 0, Animation.RELATIVE_TO_SELF,0.5f, Animation.RELATIVE_TO_SELF, 0.5f); TranslateAnimation translate = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0f,Animation.RELATIVE_TO_SELF, 1f, Animation.RELATIVE_TO_SELF, 0f,Animation.RELATIVE_TO_SELF, 0f); // AlphaAnimation alpha = new AlphaAnimation(1f, 0f); AlphaAnimation imagealpha = new AlphaAnimation(0f, 1f); rotate.setDuration(800); rotate.setFillAfter(true); // alpha.setDuration(400); // alpha.setFillAfter(true); translate.setDuration(400); translate.setFillAfter(true); imagealpha.setDuration(400); imagealpha.setFillAfter(true); btn1.startAnimation(rotate); // delBtn.startAnimation(alpha); delBtn.startAnimation(translate); delBtn.setVisibility(View.GONE); imageview.startAnimation(imagealpha); imageview.setVisibility(View.VISIBLE); count = 0; } } }); delBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub long i = dbManager.delete("storecity.db", "storecity", "city=?", tview.getText().toString()); if(i!=-1){ Intent intent = new Intent(); intent.setClass(NeedShowWethInfoCityListActivity.dcity, NeedShowWethInfoCityListActivity.class); NeedShowWethInfoCityListActivity.dcity.startActivity(intent); // DBCityList.dcity.setContentView(R.layout.db_city_list);//不行 Toast.makeText(NeedShowWethInfoCityListActivity.dcity, "delete success", Toast.LENGTH_SHORT).show(); } } }); // ((Button)convertView.findViewById(R.id.delbutton)).setOnClickListener( // new OnClickListener() { // // @Override // public void onClick(View v) { // // TODO Auto-generated method stub // // } // }); } }<file_sep>/trunk/GoogleWeather/src/com/android/weather/utils/HttpDownloader.java package com.android.weather.utils; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.ByteArrayBuffer; import org.apache.http.util.EncodingUtils; import android.graphics.Bitmap; import android.graphics.BitmapFactory; public class HttpDownloader { /* * 仔细看这个XML的头部,<?xml version="1.0"?>, * 跟标准的XML头部相比缺少了类似encoding=UTF-8这样的编码声明。于是怀疑正是由于这一点导致SAX或者DOM解析器把本不是UTF * -8的字符编码当作UTF-8来处理,于是导致了乱码和异常。经过google搜索证实当使用hl=zh-cn时返回的是GBK编码的XML, * 并且有许多用到这个API的php代码都做了GBK->UTF-8的转换处理。 * * * 问题到了这里其实就很简单了,既然是GBK编码SAX和DOM默认当UTF-8来处理, * 并且我们不可能去更改GOOGLE的Servlet让他返回一个在XML头部带encoding * =GBK的XML。那么我们只有两个办法,要嘛就把返回的XML从GBK编码转码到UTF * -8,要嘛就让SAX和DOM解析器把XML当GBK来处理。第二种方法我找了半天没找到SAX和DOM有这个功能的函数,于是着手从第一种办法来解决。 */ /** * 下载文本文件 返回文本中的字符串 换版本了 先前的那个从网上获取weather * xml文件中的中文显示乱码,从google获取的xml文件是GBK编码 * * @param urlStr * @return */ public String downText(String urlStr) { URL url; BufferedInputStream bis = null; try { // url = new URL(urlStr.replace(" ", "%20")); // URLConnection urlconn = url.openConnection(); // urlconn.connect(); // InputStream is = urlconn.getInputStream(); bis = new BufferedInputStream( getInputStreamFromUrl(urlStr)); ByteArrayBuffer buf = new ByteArrayBuffer(50); int read_data = -1; while ((read_data = bis.read()) != -1) { buf.append(read_data); } // String resps = EncodingUtils.getString(buf.toByteArray(), "GBK"); String resp = EncodingUtils.getString(buf.toByteArray(), "GBK"); return resp; } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); return ""; } catch (IOException e) { // TODO Auto-generated catch block System.out.println("ex"); e.printStackTrace(); return ""; } finally{ if(bis!=null){ try { bis.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } /** * 从网络上获取图片 * @param url * @return */ public Bitmap getImageByURL(String url) { BufferedInputStream bis = null; Bitmap bm = null; try { URL imgURL = new URL(url); URLConnection conn = imgURL.openConnection(); conn.connect(); InputStream input = conn.getInputStream(); // HttpClient client = new DefaultHttpClient(); // HttpGet get = new HttpGet(url); // InputStream input = client.execute(get).getEntity().getContent(); bis = new BufferedInputStream(input); bm = BitmapFactory.decodeStream(bis); } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally{ if(bis!=null){ try { bis.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } return bm; } /** * 根据URL得到输入流 * * @param urlStr * @return * @throws IOException */ public InputStream getInputStreamFromUrl(String urlStr) throws IOException { // URL url = new URL(urlStr); // HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); // InputStream input = urlConn.getInputStream(); HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(urlStr); InputStream input = client.execute(get).getEntity().getContent(); return input; } } <file_sep>/trunk/GoogleWeather/src/com/android/weather/utils/WeatherIconResourceMap.java package com.android.weather.utils; import java.util.HashMap; import com.android.weather.R; public class WeatherIconResourceMap { private HashMap<String, Integer> drawableIdHash =null; public WeatherIconResourceMap(HashMap<String, Integer> drawableIdHash) { super(); this.drawableIdHash = drawableIdHash; setDrawableIdHash(); } private void setDrawableIdHash(){ drawableIdHash.put("chance_of_rain", R.drawable.chance_of_rain); drawableIdHash.put("chance_of_snow", R.drawable.chance_of_snow); drawableIdHash.put("chance_of_storm", R.drawable.chance_of_storm); drawableIdHash.put("chance_of_tstorm", R.drawable.chance_of_tstorm); drawableIdHash.put("cloudy", R.drawable.cloudy); drawableIdHash.put("dust", R.drawable.dust); drawableIdHash.put("flurries", R.drawable.flurries); drawableIdHash.put("fog", R.drawable.fog); drawableIdHash.put("haze", R.drawable.haze); drawableIdHash.put("icy", R.drawable.icy); drawableIdHash.put("mist", R.drawable.mist); drawableIdHash.put("mostly_cloudy", R.drawable.mostly_cloudy); drawableIdHash.put("mostly_sunny", R.drawable.mostly_sunny); drawableIdHash.put("partly_cloudy", R.drawable.partly_cloudy); drawableIdHash.put("rain", R.drawable.rain); drawableIdHash.put("sleet", R.drawable.sleet); drawableIdHash.put("smoke", R.drawable.smoke); drawableIdHash.put("snow", R.drawable.snow); drawableIdHash.put("storm", R.drawable.storm); drawableIdHash.put("sunny", R.drawable.sunny); drawableIdHash.put("thunderstorm", R.drawable.thunderstorm); drawableIdHash.put("cn_fog", R.drawable.cn_fog); drawableIdHash.put("cn_heavyrain", R.drawable.cn_heavyrain); drawableIdHash.put("cn_lightrain", R.drawable.cn_lightrain); drawableIdHash.put("cn_cloudy", R.drawable.cn_cloudy); } public int getIconResourceId(String wStr){ System.out.println(wStr); return drawableIdHash.get(wStr); } } <file_sep>/trunk/GoogleWeather/src/com/android/weather/utils/AppConstants.java package com.android.weather.utils; public class AppConstants { public static final String [] city ={ "北京",// "上海",// "天津",// "重庆",// "唐山",// "石家庄",// "大连",// "哈尔滨",// "海口",// "长春",// "长沙",// "成都",// "福州",// "广州",// "贵阳",// "杭州",// "合肥",// "呼和浩特",// "济南",// "昆明",// "拉萨",// "兰州",// "南昌",// "南京",// "南宁",// "青岛",// "深圳",// "沈阳",// "太原",// "乌鲁木齐",// "武汉",// "西安",// "西宁",// "厦门",// "徐州",// "银川",// "郑州"// }; } <file_sep>/trunk/GoogleWeather/src/com/android/weather/utils/GoogleWeatherHandler.java package com.android.weather.utils; import java.util.List; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import android.util.Log; import com.android.weather.model.CurrentWeatherInfo; import com.android.weather.model.WeatherInfo; public class GoogleWeatherHandler extends DefaultHandler{ private List<WeatherInfo> weatherInfos = null; private WeatherInfo weatherInfo = null; private CurrentWeatherInfo currentWeatherInfo= null; private String tagName=""; public GoogleWeatherHandler(List<WeatherInfo> weatherInfos, CurrentWeatherInfo currentWeatherInfo) { super(); this.weatherInfos = weatherInfos; this.currentWeatherInfo = currentWeatherInfo; } @Override public void characters(char[] ch, int start, int length) throws SAXException { super.characters(ch, start, length); } @Override public void startDocument() throws SAXException { // TODO Auto-generated method stub super.startDocument(); } @Override public void endDocument() throws SAXException { // TODO Auto-generated method stub super.endDocument(); } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { // TODO Auto-generated method stub super.startElement(uri, localName, qName, attributes); String data = attributes.getValue(0); tagName = localName; if(weatherInfo==null){//获取当天的详细天气信息 if(localName.equals("postal_code")){ currentWeatherInfo.setPostalCode(data); }else if(localName.equals("condition")){ currentWeatherInfo.setCondition(data); }else if(localName.equals("temp_f")){ currentWeatherInfo.setTempF(data); }else if(localName.equals("temp_c")){ currentWeatherInfo.setTempC(data); }else if(localName.equals("humidity")){ currentWeatherInfo.setHumidity(data); }else if(localName.equals("icon")){ String[] str = data.split("/"); String name = str[str.length-1]; String[] a = name.split("\\."); String preName = a[0]; currentWeatherInfo.setIconName(preName); }else if(localName.equals("wind_condition")){ currentWeatherInfo.setWindCondition(data); } } if(localName.equals("forecast_conditions")){//开始解析今后四天的天气信息包含当天的信息 weatherInfo = new WeatherInfo(); }else if(localName.equals("day_of_week")){ weatherInfo.setDayOfWeek(data); }else if(localName.equals("low")){ weatherInfo.setLowC(data); }else if(localName.equals("high")){ weatherInfo.setHighC(data); }else if(weatherInfo!=null&&localName.equals("icon")){//因为之前没对象的话,也有icon标签 所以要过滤 String[] str = data.split("/"); String name = str[str.length-1]; String[] a = name.split("\\."); String preName = a[0]; weatherInfo.setIconName(preName); }else if(weatherInfo!=null&&localName.equals("condition")){ weatherInfo.setCondition(data); } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { // TODO Auto-generated method stub super.endElement(uri, localName, qName); tagName=""; if(localName.equals("forecast_conditions")){ weatherInfos.add(weatherInfo); } } } <file_sep>/trunk/GoogleWeather/src/com/android/weather/custom/widget/EditCancel.java package com.android.weather.custom.widget; import com.android.weather.R; import com.android.weather.db.DatabaseHelper; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.text.Editable; import android.text.TextWatcher; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.EditText; import android.widget.ImageButton; import android.widget.RelativeLayout; public class EditCancel extends RelativeLayout { EditText eText; ImageButton imageBtn; DatabaseHelper helper; public EditCancel(Context context, AttributeSet attrs) { super(context, attrs); LayoutInflater.from(context).inflate(R.layout.edit_cancel_symbol, this, true); eText = (EditText)findViewById(R.id.edit); imageBtn = (ImageButton)findViewById(R.id.imagebtn); // init(); } public ImageButton getImageBtn() { return imageBtn; } public EditText geteText() { return eText; } /* private void init(){ eText = (EditText)findViewById(R.id.edit); imageBtn = (ImageButton)findViewById(R.id.imagebtn); helper = new DatabaseHelper(EditCancel.this.getContext(), "city.db3"); //为输入框添加监听文字变化的监听器 eText.addTextChangedListener(tw); imageBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub hideCancelBtn(); eText.setText(""); } }); } public void setEditText(String content){ eText.setText(content); } // 当输入框状态改变时,会调用相应的方法 TextWatcher tw = new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub if(s.length()!=0){ SQLiteDatabase db = helper.getReadableDatabase(); Cursor cursor = db.query("city", new String[]{"city","province"}, "city like '"+s+"%' or pinyin like '"+s+"%'", null, null, null, null); while(cursor.moveToNext()){ String name = cursor.getString(cursor.getColumnIndex("city")); System.out.println("name is "+ name); } } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } // 在文字改变后调用 @Override public void afterTextChanged(Editable s) { // TODO Auto-generated method stub if(s.length()==0){ hideCancelBtn(); }else{ showCancelBtn(); } } }; //显示按钮 public void showCancelBtn(){ imageBtn.setVisibility(View.VISIBLE); } //隐藏按钮 public void hideCancelBtn(){ imageBtn.setVisibility(View.GONE); } */ } <file_sep>/trunk/GoogleWeather/src/com/android/weather/model/CurrentWeatherInfo.java package com.android.weather.model; /** * 用于解析从google weather 获取的天气信息--xml数据 * @author Administrator * */ public class CurrentWeatherInfo { private String condition;//当前天气状况 private String postalCode;//行政区名称 private String humidity;//湿度 private String tempF;//华氏温度 private String tempC;//摄氏温度 private String iconName; private String windCondition;//风向风速状况 public String getCondition() { return condition; } public void setCondition(String condition) { this.condition = condition; } public String getPostalCode() { return postalCode; } public void setPostalCode(String postalCode) { this.postalCode = postalCode; } public String getHumidity() { return humidity; } public void setHumidity(String humidity) { this.humidity = humidity; } public String getTempF() { return tempF; } public void setTempF(String tempF) { this.tempF = tempF; } public String getTempC() { return tempC; } public void setTempC(String tempC) { this.tempC = tempC; } public String getIconName() { return iconName; } public void setIconName(String iconName) { this.iconName = iconName; } public String getWindCondition() { return windCondition; } public void setWindCondition(String windCondition) { this.windCondition = windCondition; } @Override public String toString() { return "CurrentWeatherInfo [condition=" + condition + ", postalCode=" + postalCode + ", humidity=" + humidity + ", tempF=" + tempF + ", tempC=" + tempC + ", iconName=" + iconName + ", windCondition=" + windCondition + "]"; } }
b4e603b2c22a714b1043f7e29054a5ce97942ba4
[ "Java" ]
7
Java
jobsonp/android-google-weather
8ac40338ea997374d64e1a5cd863fc0eb2d1d57e
9cdb9e5bd018031126f0b53b9f69397bad8045dd
refs/heads/master
<file_sep>package com.alexecollins.vbox.maven; import com.alexecollins.vbox.core.VBox; import com.alexecollins.vbox.core.task.Suspend; /** * Suspend the VM. * * @goal suspend * @author alexec (<EMAIL>) * @since 3.0.0 */ public class SuspendMojo extends AbstractVBoxesMojo { @Override protected void execute(VBox box) throws Exception { new Suspend(box).call(); } } <file_sep>package com.alexecollins.vbox.mediaregistry; import com.alexecollins.vbox.core.task.AbstractTest; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import static junit.framework.Assert.assertTrue; /** * @author <EMAIL> */ @RunWith(Parameterized.class) public class MediaRegistryTest extends AbstractTest { public MediaRegistryTest(final String name) throws Exception { super(name); } @Test public void testName() throws Exception { final MediaRegistry sut = getBox().getMediaRegistry(); assertTrue(sut.getDVDImages().getDVDImage() != null); } } <file_sep>package com.alexecollins.util; import org.apache.commons.io.FileUtils; import org.junit.Ignore; import org.junit.Test; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.Arrays; import static junit.framework.Assert.*; import static org.junit.Assert.assertArrayEquals; /** * @author alexec (<EMAIL>) */ public class FileUtils2Test { @Test @Ignore public void testCopyURLToFile() throws Exception { final URL u = new URL("http://www.alexecollins.com/sites/default/files/alex.e.collins_2.png"); final int s = 117741; final File f = File.createTempFile("alex", "jpg"); assert f.delete(); System.out.println(f.getCanonicalPath()); final Thread t = new Thread(new Runnable() { public void run() { try { FileUtils2.copyURLToFile(u, f); } catch (IOException e) { e.printStackTrace(); } } }); t.start(); Thread.sleep(150); t.stop(); Thread.sleep(100); assertTrue(f.length() > 0); assertTrue(f.length() < s) ; FileUtils2.copyURLToFile(u, f); assertEquals(s, f.length()); } @Ignore @Test public void testSignature() throws Exception { final File f = new File("test"); FileUtils.touch(f); final byte[] x = FileUtils2.getSignature(f); assertArrayEquals(x, FileUtils2.getSignature(f)); assert f.renameTo(new File("test1")); final byte[] y = FileUtils2.getSignature(f); System.out.println(Arrays.toString(x)); System.out.println(Arrays.toString(y)); assertFalse(Arrays.equals(x, y)); assert f.delete(); } }<file_sep>package com.alexecollins.vbox.core.task; import com.alexecollins.vbox.core.VBox; import com.alexecollins.vbox.core.Work; import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.util.concurrent.Callable; import static com.google.common.base.Preconditions.checkNotNull; /** * Delete a definition. * * @author alexec (<EMAIL>) * @since 3.0.0 */ public class DeleteDefinition implements Callable<Void> { private static final Logger LOGGER = LoggerFactory.getLogger(DeleteDefinition.class); private final Work work; private final VBox box; public DeleteDefinition(Work work, VBox box) { checkNotNull(work, "work"); checkNotNull(box, "box") ; this.work = work; this.box = box; } public Void call() throws Exception { // make sure the machine is gone, but attempt to be idempotent final File file = new File(box.getSrc().toURL().getFile()); if (file.exists()) { new Clean(work,box).call(); FileUtils.forceDelete(file); LOGGER.info("deleted definition '" + box.getName() + "'"); } return null; } } <file_sep>Local Repository === Boxes and download are stored locally in your home directory in ~/.vbox/. If your using Maven, you can purge this using: mvn vbox:purge-local-repository<file_sep>package com.alexecollins.vbox.core; import static com.google.common.base.Preconditions.checkNotNull; /** * A context for a box to be created in, usually project coordinates. * * @author alexec (<EMAIL>) * @since 3.0.0 */ public class Context { private final String name; public Context(String name) { checkNotNull(name, "name"); this.name = name; } public String getName() { return name; } } <file_sep>VirtualBox Java API === [![Build Status](https://api.travis-ci.org/alexec/maven-vbox-plugin.png)](https://travis-ci.org/alexec/maven-vbox-plugin) Overview === This project provides support for creating, starting and stopping VirtualBox VMs. This is aimed at development and integration testing of projects by allowing you to package a complete software stack onto a single machine, install your code and perform your tests. Some typical scenarios would be: * Provide a dev stack and a touch of a button. * Install all apps onto a VBox and test it. It provides: 1. A Java API for programmatic control of boxes. 2. A set of Maven Mojos. 3. A set of matching Ant tasks. Goals === To provide support for: * Multiple host and guest OS, not least including Linux, Windows and OS-X * Unattended install and provisioning of guest OSs. * Multiple VMs per project. * *Not* to be a replacement for VeeWee, Vagrant, Chef or Puppet. Usage === The main mojos/tasks are split into three groups: Managing Definitions --- Task that work on a single definition: * list-definitions - list available template definitions * create-definition - creates a box from template definition * delete-definition - delete the definition * list-predefined-patches - list built-in patches * patch-definition - patch a definition with one or more patches Provisioning Tasks --- Task related to setting up one or more boxes: * clean - deletes boxes * create - creates boxes, generally not used as provision will create the box if it doesn't exist * provision - provisions boxes, creating them if needs be Runtime Tasks --- Tasks related to the usage of boxes: * start - start boxes * stop - stops boxes * suspend - suspend the boxes * resume - resume boxes Examples === <iframe width="640" height="360" src="http://www.youtube.com/embed/Y4ZXD7psIuM" frameborder="0" allowfullscreen="true"></iframe> * [Five minute demo](http://www.youtube.com/watch?v=Y4ZXD7psIuM) * [Ant and Maven examples](https://github.com/alexec/maven-vbox-plugin/tree/master/vbox-examples/) * [Example Maven project](https://github.com/alexec/maven-vbox-plugin-example) Maven === Quick Start --- Add this to your pom.xml: <plugin> <groupId>com.alexecollins.vbox</groupId> <artifactId>vbox-maven-plugin</artifactId> <version>2.0.0</version> <executions> <execution> <goals> <goal>clean</goal> <goal>provision</goal> <goal>start</goal> <goal>stop</goal> </goals> </execution> </executions> </plugin> Execute this: mvn vbox:create-definition -Dvbox.name=CentOS_6_5 Execute: mvn verify Maven searches for VM definitions under src/main/vbox. Example can be [found here](https://github.com/alexec/maven-vbox-plugin/tree/master/vbox-examples/maven). Ant === Quick Start --- Add this to your build.xml: <project name="vbox-ant-tasks" default="build" xmlns:vbox="antlib:com.alexecollins.vbox.ant"> <target name="build"> <property name="context" value="ant-project:1.0.0"/> <property name="app" location="src/vbox/app1"/> <vbox:purge-local-repository/> <vbox:list-definitions/> <vbox:delete-definition dir="${app}"/> <vbox:create-definition name="CentOS_6_5" dir="${app}"/> <vbox:patch-definition dir="${app}"> <archPatch/> <predefinedPatch name="CentOS_6_5--tomcat6"/> </vbox:patch-definition> <vbox:clean dir="${app}" context="${context}"/> <vbox:create dir="${app}" context="${context}"/> <vbox:provision dir="${app}" context="${context}"/> <vbox:start dir="${app}"/> <!-- ... --> <vbox:stop dir="${app}"/> </target> </project> Add the vbox-ant-tasks-*.jar to Ant's class path. Ant tasks do not currently allow you to do multiple VMs in a single command. You'll need to use multiple ones. An example can be [found here](https://github.com/alexec/maven-vbox-plugin/tree/master/vbox-examples/ant). Definitions === Definitions can be found in src/test/vbox. Typically you'd create a series of definitions in src/main/vbox, alongside supporting files, for example an Ubuntu server might be named "UbuntuServer": * src/main/vbox/ * UbuntuServer/ - The name of the server. * MediaRegistry.xml - A list of media to get (e.g. from a URL or fileshare). Similar to a fragment of VirtualBox.xml file. * VirtualBox.xml - The configuration of the server (e.g. disk etc.). Intentionally similar to one of Virtual Box's .vbox XML files. * Manifest.xml - A list of all files used by the server (e.g. preseed.cfg, AutoUnattend.xml etc.). Optional. * Provisioning.xml - The steps required to get the box ready (e.g. install Apache, set-up DNS etc.). Intentionally similar to an Ant script. * Profile.xml - Information about the box, such as if it is headless, and how to determine if it's stared successfully. The Ubuntu example downloads (by setting the DVDImage location to the URL) and attaches it. It then uses a preseed.cfg to create the VM. You'll want to include an additional files, either a preseed.cfg for an Ubuntu VM, or an AutoUnattend.xml for a Windows. These files tell the installer how to set-up the OS. To expose them to the VM you can either: * Mount a floppy (esp. for Windows). * Access the files by HTTP. When provisioning starts up, all the files in your definition dir are available on http://${server.ip}:${server.port}/. Typically you'll want to make sure you VMs has: * SSH access (or similar). * ACPI support for graceful shutdown (many minimal installs don't). Tokens --- The following tokens are recognised in some XML documents: * ${vbox.name} - Then name of the guest OS. * ${server.ip} - The IP of the host. * ${server.port} - The port the web server is running on. * ${vbox.additions} - The path the VirtualBox Guest Additions on the host OS. Authentication --- By default the username is "vbox" and the default password "<PASSWORD>". Supported Host OS Types --- * Mac OS-X * Windows 7 Unlisted OSs should all work. Supported Guest OS Types/Supplied Definitions --- * CentOS_6_5 * UbuntuServer_12_10 * WindowsServer2008 Unlisted OSs may work. 32 Bit vs 64 Bit === Currently the definitions are all 32 bit. I _think_ you'll want to use the same bits on the guest as the host. It'll be faster. If you want use 64 bit you typically need to: - Ensure hardware virtualizaiton is enabled on the host (see (http://www.parallels.com/uk/products/novt)) - Append "_64" to the OS type, e.g. "RedHat_64". - Enable IO ACPI (as a side-effect, it'll be much faster, if your host OS is 64 bit). - Use a 64 ISO (note that Windows will install the appropriate kernel for you, but you cannot change it once it's installed). To save time, a patch is provided that will detect the host arch and apply a patch to the guest, e.g.: <patches> <archPatch/> </patches> The patch will make the appropriate changes and choose an ISO for you. Patches === A patch is a way of modifying a definition. Typically a patch will take a base definition and add support for new features. An example would be installing Tomcat onto a server. Patches are applied after a definition in created, but before the machine is created (in fact, applying a patch after a machine is created will change its (signature)[signatures.md] and result in its rebuild. There are two types of patch _predefined_, _user defined_ and _custom_. Predefined Patches --- Predefined patches can be listed with the Maven plugin: mvn vbox:list-predefined-patches Typically a predefined patch has a name which is the concatenation of the template used to create it, two dashes, and a short description. E.g.: CentOS_6_5--tomcat6 To apply a patch you need to add it to your XML. For example, you can get it to create patches as follows: <execution> <id>create-definition</id> <goals><goal>create-definition</goal></goals> <configuration> <templateName>CentOS_6_5</templateName> <name>app1</name> </configuration> </execution> <execution> <id>patch-definition</id> <goals><goal>patch-definition</goal></goals> <configuration> <patches> <predefinedPatch> <name>CentOS_6_5--tomcat6</name> </predefinedPatch> </patches> </configuration> </execution> User Defined Patches --- As pre-defined patches might not cover all cases you can also use user defined ones. The format is unified diff, so you can use diff to create the patch, e.g: $ diff -ruN app1 app2 > patches/user-defined.patch diff -ruN app1/Provisioning.xml app2/Provisioning.xml --- app1/Provisioning.xml 2013-02-03 14:54:29.000000000 +0000 +++ app2/Provisioning.xml 2013-02-03 14:33:34.000000000 +0000 @@ -22,6 +22,5 @@ </Target> <Target name="cleanup"> <Exec>vboxmanage storageattach ${vbox.name} --storagectl "Floppy Controller" --port 0 --device 0 --medium none</Exec> - <PortForward hostport="10022" guestport="22"/> </Target> </Provisioning> And XML to configure it. <patches> <userDefinedPatch> <file>src/vbox/patches/user-defined.patch</file> <!-- default level is 1 --> <level>1</level> </userDefinedPatch> </patches> Note that patches are level 1 by default. Custom Patches --- You can create a custom patch if you want. This is an advanced topic. Simple implement com.alexecollins.vbox.core.patch.Patch and add that and the appropriate information to your POM. E.g. package com.alexecollins.vbox.maven.patch; import com.alexecollins.vbox.core.VBox; import com.alexecollins.vbox.core.patch.Patch; public class NoopPatch implements Patch { public void apply(VBox box) throws Exception { // nop } public String getName() { return "NoopPatch"; } } And add the standard Maven implementation detail: <patches> <noopPatch implementation="com.alexecollins.vbox.patch.demo.NoopPatch"/> </patches>Known Issues === * US keyboard layouts only. * Limited sub-set of vbox set-up supported. Troubleshooting === * Sometimes VirtualBox gets in a state if VMs are not cleanly removed. Kill all VBox processes you can see. * Host and guest firewalls can prevent OSs getting web resources. Disable the firewall. References === * [VBoxManage](http://www.virtualbox.org/manual/ch08.html) * [Ubuntu/Debian preseed.cfg](https://help.ubuntu.com/12.10/installation-guide/i386/preseed-using.html) * [VeeWee](https://github.com/jedi4ever/veewee) * [Oracle blog on VirtualBox networking](https://blogs.oracle.com/fatbloke/entry/networking_in_virtualbox1) * [Enforcer Plugin Custom Rule](http://maven.apache.org/enforcer/enforcer-api/writing-a-custom-rule.html) * [Patch Format](http://www.markusbe.com/2009/12/how-to-read-a-patch-or-diff-and-understand-its-structure-to-apply-it-manually/#how-to-read-a-unified-diff) <file_sep>Goals === To provide support for: * Multiple host and guest OS, not least including Linux, Windows and OS-X * Unattended install and provisioning of guest OSs. * Multiple VMs per project. * *Not* to be a replacement for VeeWee, Vagrant, Chef or Puppet. <file_sep>package com.alexecollins.vbox.maven; import com.alexecollins.vbox.core.task.PurgeLocalRepository; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import java.io.IOException; /** * Purge the local repository. * * @goal purge-local-repository * @phase clean * @author alexec (<EMAIL>) * @since 3.0.0 */ public class PurgeLocalRepositoryMojo extends AbstractVBoxMojo { public void execute() throws MojoExecutionException, MojoFailureException { try { new PurgeLocalRepository().call(); } catch (IOException e) { throw new MojoExecutionException("failed to execute", e); } } } <file_sep>Definitions === Definitions can be found in src/test/vbox. Typically you'd create a series of definitions in src/main/vbox, alongside supporting files, for example an Ubuntu server might be named "UbuntuServer": * src/main/vbox/ * UbuntuServer/ - The name of the server. * MediaRegistry.xml - A list of media to get (e.g. from a URL or fileshare). Similar to a fragment of VirtualBox.xml file. * VirtualBox.xml - The configuration of the server (e.g. disk etc.). Intentionally similar to one of Virtual Box's .vbox XML files. * Manifest.xml - A list of all files used by the server (e.g. preseed.cfg, AutoUnattend.xml etc.). Optional. * Provisioning.xml - The steps required to get the box ready (e.g. install Apache, set-up DNS etc.). Intentionally similar to an Ant script. * Profile.xml - Information about the box, such as if it is headless, and how to determine if it's stared successfully. The Ubuntu example downloads (by setting the DVDImage location to the URL) and attaches it. It then uses a preseed.cfg to create the VM. You'll want to include an additional files, either a preseed.cfg for an Ubuntu VM, or an AutoUnattend.xml for a Windows. These files tell the installer how to set-up the OS. To expose them to the VM you can either: * Mount a floppy (esp. for Windows). * Access the files by HTTP. When provisioning starts up, all the files in your definition dir are available on http://${server.ip}:${server.port}/. Typically you'll want to make sure you VMs has: * SSH access (or similar). * ACPI support for graceful shutdown (many minimal installs don't). Tokens --- The following tokens are recognised in some XML documents: * ${vbox.name} - Then name of the guest OS. * ${server.ip} - The IP of the host. * ${server.port} - The port the web server is running on. * ${vbox.additions} - The path the VirtualBox Guest Additions on the host OS. Authentication --- By default the username is "vbox" and the default password "<PASSWORD>". Supported Host OS Types --- * Mac OS-X * Windows 7 Unlisted OSs should all work. Supported Guest OS Types/Supplied Definitions --- * CentOS_6_5 * UbuntuServer_12_10 * WindowsServer2008 Unlisted OSs may work. <file_sep>package de.innotek.virtualbox_settings; import com.alexecollins.vbox.core.task.AbstractTest; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; /** * @author <EMAIL> */ @RunWith(Parameterized.class) public class VirtualBoxTest extends AbstractTest { public VirtualBoxTest(final String name) throws Exception { super(name); } @Test public void testGetMachine() throws Exception { final VirtualBox sut = getBox().getVirtualBox(); assert sut.getMachine() != null; } } <file_sep>package com.alexecollins.vbox.core.task; import com.alexecollins.vbox.core.VBox; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.Callable; /** * Suspends a VMs. * * @since 3.0.0 */ public class Suspend implements Callable<Void> { private static final Logger LOGGER = LoggerFactory.getLogger(Suspend.class); private final VBox box; public Suspend(VBox box) { this.box = box; } public Void call() throws Exception { final String state = box.getProperties().getProperty("VMState"); if (!state.equals("saved")) { LOGGER.info("suspending "+ box.getName()); box.suspend(); box.awaitState(15000l, "saved"); LOGGER.info("suspended "+ box.getName()); } else { LOGGER.info("not suspending " + box.getName() + ", already suspended"); } return null; //To change body of implemented methods use File | Settings | File Templates. } }<file_sep>package com.alexecollins.util; import org.junit.Test; import static org.junit.Assert.assertArrayEquals; /** * @author alexec (<EMAIL>) */ public class Bytes2Test { @Test public void testSearchAndReplace() throws Exception { byte[] s = "${search}".getBytes(); byte[] r = "replace".getBytes(); byte[] src = "${search} and ${search} is ${search}".getBytes(); final byte[] actuals = Bytes2.searchAndReplace(src, s, r); //System.out.println("<"+new String(actuals)+">"); assertArrayEquals("replace and replace is replace".getBytes(), actuals); } @Test public void testSearchAndReplace2() throws Exception { byte[] s = "${search}".getBytes(); byte[] r = "repl".getBytes(); // shorted byte[] src = "${search} and ${search} is ${search}".getBytes(); final byte[] actuals = Bytes2.searchAndReplace(src, s, r); //System.out.println("<"+new String(actuals)+">"); assertArrayEquals("repl and repl is repl".getBytes(), actuals); }} <file_sep>package com.alexecollins.vbox.core.task; import com.alexecollins.vbox.core.TestContext; import com.alexecollins.vbox.core.VBox; import com.alexecollins.vbox.core.Work; import com.google.common.io.Files; import org.junit.After; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.xml.sax.SAXException; import javax.xml.bind.JAXBException; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.util.Arrays; import java.util.Collection; /** * @author <EMAIL> */ @RunWith(Parameterized.class) public abstract class AbstractTest { @Parameterized.Parameters(name = "{0}") public static Collection<Object[]> data() { return Arrays.asList(new Object[][]{ {"TinyCore_4_x"}, {"UbuntuServer_12_10" }, {"CentOS_6_5"} // ,{"WindowsServer2008" } }); } private final String name; private final File src; private final File target; private final TestContext context = new TestContext(); private final Work work = new Work(context); public AbstractTest(final String name) throws Exception { this.name = name; System.out.println("name=" + name); src = Files.createTempDir(); final CreateDefinition definition = new CreateDefinition(context, getName(), src); definition.call(); target = work.targetOf(getBox()); } @After public void tearDown() throws Exception { context.destroy(); } public String getName() { return name; } public VBox getBox() throws IOException, JAXBException, SAXException, URISyntaxException { return new VBox(context, src.toURI()); } public File getTarget() { return target; } public Work getWork() { return work; } public File getSrc() { return src; } } <file_sep>package com.alexecollins.vbox.ant.patch; import com.alexecollins.vbox.ant.AbstractTask; import com.alexecollins.vbox.core.VBox; import com.alexecollins.vbox.core.patch.ArchPatch; import com.alexecollins.vbox.core.patch.Patch; import com.alexecollins.vbox.core.patch.UserDefinedPatch; import com.alexecollins.vbox.core.task.PatchDefinition; import org.apache.tools.ant.BuildException; import java.util.ArrayList; import java.util.List; /** * @author alexec (<EMAIL>) * @since 2.0.0 */ public class PatchDefinitionTask extends AbstractTask { private List<Patch> patches = new ArrayList<Patch>(); public ArchPatch createArchPatch() { ArchPatch patch = new ArchPatch(); patches.add(patch); return patch; } public com.alexecollins.vbox.ant.patch.PredefinedPatch createPredefinedPatch() { com.alexecollins.vbox.ant.patch.PredefinedPatch patch = new com.alexecollins.vbox.ant.patch.PredefinedPatch(); patches.add(patch); return patch; } public UserDefinedPatch createUserDefinedPatch() { UserDefinedPatch patch = new UserDefinedPatch(); patches.add(patch); return patch; } @Override public void execute() throws BuildException { if (dir == null) { throw new BuildException("dir is null"); } try { new PatchDefinition(work(), new VBox(context(), dir.toURI()), patches).call(); } catch (Exception e) { throw new BuildException(e); } } } <file_sep>package com.alexecollins.vbox.ant; import org.junit.Test; /** * @author alexec (<EMAIL>) */ public class CleanTaskIT extends AbstractTaskTest { @Test public void testExecute() throws Exception { final CreateDefinitionTask defn = new CreateDefinitionTask(); defn.setName("CentOS_6_5"); defn.setDir(dir); defn.execute(); final CleanTask sut = new CleanTask(); sut.setDir(dir); sut.execute(); } } <file_sep><?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.alexecollins.vbox</groupId> <artifactId>maven-vbox-plugin-example</artifactId> <version>2.0.0-SNAPSHOT</version> <packaging>pom</packaging> <build> <plugins> <plugin> <groupId>com.alexecollins.vbox</groupId> <artifactId>vbox-maven-plugin</artifactId> <version>@project.version@</version> <executions> <execution> <id>clean</id> <goals> <goal>delete-definition</goal> </goals> </execution> <execution> <id>create-definition</id> <goals> <goal>create-definition</goal> </goals> <configuration> <templateName>CentOS_6_5</templateName> <name>cent-os-6-5.test</name> </configuration> </execution> <execution> <id>patch-definition</id> <goals> <goal>patch-definition</goal> </goals> <configuration> <patches> <archPatch/> <predefinedPatch> <name>CentOS_6_5--tomcat6</name> </predefinedPatch> </patches> </configuration> </execution> <execution> <id>default</id> <goals> <goal>clean</goal> <goal>provision</goal> <goal>start</goal> <goal>stop</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </project> <file_sep>package com.alexecollins.vbox.core.task; import com.alexecollins.vbox.core.TestContext; import com.alexecollins.vbox.core.VBox; import com.alexecollins.vbox.core.Work; import com.google.common.io.Files; import org.junit.Test; import java.io.File; import static junit.framework.Assert.assertFalse; import static junit.framework.TestCase.assertTrue; /** * @author alexec (<EMAIL>) */ public class DeleteDefinitionIT { @Test public void testCall() throws Exception { final File tmp = Files.createTempDir(); final File target = new File(tmp, "test"); final VBox box = new CreateDefinition(new TestContext(), "CentOS_6_5", target).call(); System.out.println("src="+box.getSrc()); assertTrue(target.exists()); new DeleteDefinition(new Work(new TestContext()), box).call(); assertFalse(target.exists()); } } <file_sep>package com.alexecollins.vbox.maven.patch; /** * A user-defined patch from a file. * * @author alexec (<EMAIL>) * @since 2.0.0 */ public class UserDefinedPatch extends com.alexecollins.vbox.core.patch.UserDefinedPatch { }<file_sep>package com.alexecollins.vbox.ant; import java.io.File; /** * @author alexec (<EMAIL>) */ public abstract class AbstractTaskTest { final File dir = new File("build/vbox/CentOS_6_5"); } <file_sep>VirtualBox Java API === [![Build Status](https://api.travis-ci.org/alexec/maven-vbox-plugin.png)](https://travis-ci.org/alexec/maven-vbox-plugin) <file_sep>#! /bin/sh set -ue yum -y install acpid kernel-headers kernel-devel gcc gcc-c++ make kernel-devel-$(uname -r) mkdir /media/cdrom mount /dev/sr0 /media/cdrom /media/cdrom/VBoxLinuxAdditions.run umount /dev/sr0 rm -R /media/cdrom yum -y install tomcat6 chkconfig tomcat6 on poweroff now <file_sep>package com.alexecollins.vbox.core.patch; import com.alexecollins.util.Bytes2; import com.alexecollins.vbox.core.VBox; import com.google.common.io.Resources; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.URL; import java.nio.charset.Charset; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * A pre-defined patch based on unified diff format. * * @author alexec (<EMAIL>) * @since 2.0.0 */ public class PredefinedPatch implements Patch { private static final Map<String,List<String>> nameToArgs = new HashMap<String, List<String>>(); static { try { for (String l : Resources.readLines(PredefinedPatch.class.getResource("manifest.txt"), Charset.forName("UTF-8"))) { final Matcher m = Pattern.compile("([^()]*)\\(([^()]*)\\)").matcher(l); if (!m.find()) {throw new IllegalStateException(l + " invalid");} nameToArgs.put(m.group(1), (m.group(2).length() > 0 ? Arrays.<String>asList(m.group(2).split(",")) : Collections.<String>emptyList())); } } catch (IOException e) { throw new AssertionError(e); } } /** * The full patch name. * * E.g. * CentOS_6_5--tomcat6 */ private String name; /** * Thing that need to be mapped. */ private Map<String,String> properties = Collections.emptyMap(); public PredefinedPatch() {} public PredefinedPatch(String name, Map<String, String> properties) { this.name = name; this.properties = properties; } public void apply(VBox box) throws Exception { if (name == null) {throw new IllegalArgumentException("name is null");} if (!nameToArgs.containsKey(name)) {throw new IllegalArgumentException(name +" not in " + nameToArgs);} if (properties == null) {throw new IllegalArgumentException(properties + " is null");} for (String arg : nameToArgs.get(name)) { if (!properties.containsKey(arg)) { throw new IllegalArgumentException("properties " + properties.keySet() + " missing '" + arg + "' (requires " + nameToArgs.get(name) + ")"); } } final URL resource = getClass().getResource("/com/alexecollins/vbox/core/patch/" + name + ".patch"); if (resource == null) { throw new IllegalStateException("unable to find patch name " + name); } byte[] patch = Resources.toByteArray(resource); for (Map.Entry<String, String> e : properties.entrySet()) { LoggerFactory.getLogger(PredefinedPatch.class).info("substituting " + e); patch = Bytes2.searchAndReplace(patch, ("${" +e.getKey() +"}").getBytes("UTF-8"), e.getValue().getBytes("UTF-8")); } new UnifiedPatch(patch, 1).apply(box); } public String getName() { return name; } public static Map<String, List<String>> list() { return nameToArgs; } public void setName(String name) { this.name = name; } public Map<String, String> getProperties() { return properties; } public void setProperties(Map<String, String> properties) { this.properties = properties; } } <file_sep>Troubleshooting === * Sometimes VirtualBox gets in a state if VMs are not cleanly removed. Kill all VBox processes you can see. * Host and guest firewalls can prevent OSs getting web resources. Disable the firewall. <file_sep>Signatures === Each box has a signature which is derived from the files that make up its definition. If those files change, the signature changes. When creating or provisioning a box, the signature is checked first. If it has changed, the box is deleted and re-built.<file_sep>package com.alexecollins.vbox.core; import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; import static com.google.common.base.Preconditions.checkNotNull; /** * A repository for storing VMs in. * * @author alexec (<EMAIL>) * @since 3.0.0 */ public class Repo { private static Repo INSTANCE; private final File path; private Repo(File path) throws IOException { checkNotNull(path, "path"); this.path = path; if (!path.exists() && !path.mkdirs()) {throw new IllegalStateException("failed to create " + path);} if (!getDownloadsDir().exists()) { FileUtils.forceMkdir(getDownloadsDir()); } if (!getContextsDir().exists()) { FileUtils.forceMkdir(getContextsDir()); } } public static Repo getInstance() { if (INSTANCE == null) { try { INSTANCE = new Repo(new File(System.getProperty("user.home"), ".vbox")); } catch (IOException e) { throw new IllegalStateException(e); } } return INSTANCE; } public File getPath() { return path; } public File pathOf(Context context, VBox box) { return new File(pathOf(context), box.getName().replaceAll("/", "_")); } public File getDownloadsDir() { return new File(getPath(), "downloads"); } public File getContextsDir() { return new File(path, "contexts"); } public File pathOf(Context context) { return new File(getContextsDir(), context.getName().replaceAll("[^a-zA-Z]", "_")); } } <file_sep>package com.alexecollins.vbox.core; /** * @author <EMAIL> */ public class Snapshot { public static final Snapshot POST_CREATION = new Snapshot("post-creation"); public static final Snapshot POST_PROVISIONING = new Snapshot("post-provisioning"); private final String name; private Snapshot(String name) { if (name == null) {throw new IllegalArgumentException();} this.name = name; } @Override public String toString() { return name; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Snapshot snapshot = (Snapshot) o; return name.equals(snapshot.name); } @Override public int hashCode() { return name.hashCode(); } public static Snapshot valueOf(String name) { return new Snapshot(name) ; } } <file_sep>package com.alexecollins.util; import org.junit.Test; import static junit.framework.Assert.assertEquals; /** * @author <EMAIL> */ public class DurationUtilsTest { @Test public void testForString() throws Exception { assert 0 == DurationUtils.millisForString(""); assert 1000 == DurationUtils.millisForString("1 second"); assert 2000 == DurationUtils.millisForString("2 seconds"); assert 60000 == DurationUtils.millisForString("1 minute"); assert 120000 == DurationUtils.millisForString("2 minutes"); assert 122000 == DurationUtils.millisForString("2 minutes 2 seconds"); } @Test public void testPrettyDuration() throws Exception { assertEquals("1 minute(s)", DurationUtils.prettyPrint(60000)); assertEquals("30 second(s)", DurationUtils.prettyPrint(30000)); } } <file_sep>package com.alexecollins.vbox.ant.patch; import com.alexecollins.vbox.core.VBox; import com.alexecollins.vbox.core.patch.Patch; import java.util.HashMap; import java.util.Map; /** * @author alexec (<EMAIL>) * @since 2.0.0 */ public class PredefinedPatch implements Patch { /** * The full patch name. * * E.g. * CentOS_6_5--tomcat6 */ private String name; /** * Thing that need to be mapped. */ private Map<String,String> properties = new HashMap<String, String>(); public void apply(VBox box) throws Exception { new com.alexecollins.vbox.core.patch.PredefinedPatch(name, properties).apply(box); } public void setName(String name) { this.name = name; } public String getName() { return name; } public void setProperties(String properties) { for (String pair : properties.split(",")) { final int i = pair.indexOf('='); this.properties.put(pair.substring(0,i), pair.substring(i+1)); } } } <file_sep>package com.alexecollins.util; import com.alexecollins.vbox.core.TestContext; import com.alexecollins.vbox.core.Work; import org.apache.commons.io.FileUtils; import org.junit.Test; import java.io.File; import static junit.framework.Assert.assertTrue; public class ImageUtilsTestTest { @Test public void testCreateImage() throws Exception { final File dest = new File("src.iso"); ImageUtils.createImage(new Work(new TestContext()), new File("src"), dest); assertTrue(dest.exists()); FileUtils.forceDelete(dest); } } <file_sep>package com.alexecollins.vbox.core.task; import com.alexecollins.util.FileUtils2; import com.alexecollins.vbox.core.VBox; import com.alexecollins.vbox.core.Work; import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; /** * @author alexec (<EMAIL>) */ public abstract class AbstractTask implements Callable<Void> { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractTask.class); protected final Work work; protected final VBox box; protected AbstractTask(Work work, VBox box) { this.work = work; this.box = box; } void verifySignature() throws Exception { if (box.exists()) { final byte[] sig = getSignature(); final File sigFile = getSignatureFile(); if (!sigFile.exists() || !Arrays.equals(FileUtils.readFileToByteArray(sigFile), sig)) { LOGGER.info(box.getName() + " signature has changed, and therefore the source files have probably changed"); new Clean(work ,box).call(); } } } File getSignatureFile() { return new File(work.targetOf(box), "signature"); } byte[] getSignature() throws NoSuchAlgorithmException, IOException { return FileUtils2.getSignature(new File(box.getSrc().toURL().getFile())); } /** * Complete the variables. */ public String subst(String line) throws IOException, InterruptedException, ExecutionException { line = line.replaceAll("\\$\\{vbox\\.additions\\}", VBox.findGuestAdditions().getPath().replaceAll("\\\\", "/")); line = line.replaceAll("\\$\\{vbox\\.name\\}", box.getName()); return line; } } <file_sep>package com.alexecollins.vbox.core.task; import com.alexecollins.vbox.core.VBox; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.Callable; import java.util.concurrent.TimeoutException; /** * Stop the box. Firstly by sending a ACPID message. If that fails, forcibly terminating it. * * @author alexec (<EMAIL>) */ public class Stop implements Callable<Void> { private static final Logger LOGGER = LoggerFactory.getLogger(Stop.class); private final VBox box; public Stop(VBox box) { this.box = box; } public Void call() throws Exception { if (box.getProperties().getProperty("VMState").equals("running")) { LOGGER.info("stopping '" + box.getName() + "'"); box.pressPowerButton(); try { box.awaitState(30000l, "poweroff"); } catch (TimeoutException e) { LOGGER.warn("failed to power down in 30 second(s) forcing power off"); box.powerOff(); box.awaitState(2000, "poweroff"); } LOGGER.info("stopped '" + box.getName() + "'"); } else { LOGGER.info("not stopping '" + box.getName() + "', already off"); } return null; } } <file_sep>package com.alexecollins.vbox.core.patch; import com.alexecollins.util.ExecUtils; import com.alexecollins.vbox.core.VBox; import java.io.File; import java.io.IOException; import java.util.concurrent.ExecutionException; /** * A patch based on the unified diff format. * * This is a very common patching algo and should suite almost all purposes. * * Typically you'd create a patch using: * * <code> * diff -ruN app0 app1 > my-patch.patch * </code> * * @author alexec (<EMAIL>) * @since 2.0.0 */ public class UnifiedPatch implements Patch { private byte[] patch; private int level; // you'll almost always want to set this to 1 public UnifiedPatch(byte[] patch, int level) { if (patch == null) {throw new IllegalArgumentException();} this.patch = patch; this.level = level; } public void apply(VBox definition) throws InterruptedException, ExecutionException, IOException { if (definition == null) {throw new IllegalArgumentException();} if (patch == null) {throw new IllegalStateException();} ExecUtils.exec(patch, new File(definition.getSrc().toURL().getFile()), "patch", "-f", "-p", String.valueOf(level)); } public String getName() { return "UnifiedPatch"; } } <file_sep>Usage === The main mojos/tasks are split into three groups: Managing Definitions --- Task that work on a single definition: * list-definitions - list available template definitions * create-definition - creates a box from template definition * delete-definition - delete the definition * list-predefined-patches - list built-in patches * patch-definition - patch a definition with one or more patches Provisioning Tasks --- Task related to setting up one or more boxes: * clean - deletes boxes * create - creates boxes, generally not used as provision will create the box if it doesn't exist * provision - provisions boxes, creating them if needs be Runtime Tasks --- Tasks related to the usage of boxes: * start - start boxes * stop - stops boxes * suspend - suspend the boxes * resume - resume boxes <file_sep>package com.alexecollins.vbox.core.task; import com.alexecollins.vbox.core.VBox; import com.alexecollins.vbox.core.ssh.PresetUserInfo; import com.alexecollins.vbox.profile.Profile; import com.jcraft.jsch.Channel; import com.jcraft.jsch.JSch; import com.jcraft.jsch.Session; import java.util.concurrent.Callable; /** * Connect to a box. * * @author alexec (<EMAIL>) * @since 3.0.0 */ public class Ssh implements Callable<Void> { private final VBox box; public Ssh(VBox box) { this.box = box; } public Void call() throws Exception { final JSch jsch = new JSch(); final Profile.SSH x = box.getProfile().getSSH(); final Session session = jsch.getSession(x.getAuth().getUsername(), x.getHostname(), x.getPort()); session.setUserInfo(new PresetUserInfo(x.getAuth().getPassword(), null)); session.connect(30000); final Channel channel=session.openChannel("shell"); channel.setInputStream(System.in); channel.setOutputStream(System.out); channel.connect(3000); try { while (channel.isConnected()) { Thread.sleep(250); // bit rubbish way of doing this } } finally { channel.disconnect(); } return null; } } <file_sep>Patches === A patch is a way of modifying a definition. Typically a patch will take a base definition and add support for new features. An example would be installing Tomcat onto a server. Patches are applied after a definition in created, but before the machine is created (in fact, applying a patch after a machine is created will change its (signature)[signatures.md] and result in its rebuild. There are two types of patch _predefined_, _user defined_ and _custom_. Predefined Patches --- Predefined patches can be listed with the Maven plugin: mvn vbox:list-predefined-patches Typically a predefined patch has a name which is the concatenation of the template used to create it, two dashes, and a short description. E.g.: CentOS_6_5--tomcat6 To apply a patch you need to add it to your XML. For example, you can get it to create patches as follows: <execution> <id>create-definition</id> <goals><goal>create-definition</goal></goals> <configuration> <templateName>CentOS_6_5</templateName> <name>app1</name> </configuration> </execution> <execution> <id>patch-definition</id> <goals><goal>patch-definition</goal></goals> <configuration> <patches> <predefinedPatch> <name>CentOS_6_5--tomcat6</name> </predefinedPatch> </patches> </configuration> </execution> User Defined Patches --- As pre-defined patches might not cover all cases you can also use user defined ones. The format is unified diff, so you can use diff to create the patch, e.g: $ diff -ruN app1 app2 > patches/user-defined.patch diff -ruN app1/Provisioning.xml app2/Provisioning.xml --- app1/Provisioning.xml 2013-02-03 14:54:29.000000000 +0000 +++ app2/Provisioning.xml 2013-02-03 14:33:34.000000000 +0000 @@ -22,6 +22,5 @@ </Target> <Target name="cleanup"> <Exec>vboxmanage storageattach ${vbox.name} --storagectl "Floppy Controller" --port 0 --device 0 --medium none</Exec> - <PortForward hostport="10022" guestport="22"/> </Target> </Provisioning> And XML to configure it. <patches> <userDefinedPatch> <file>src/vbox/patches/user-defined.patch</file> <!-- default level is 1 --> <level>1</level> </userDefinedPatch> </patches> Note that patches are level 1 by default. Custom Patches --- You can create a custom patch if you want. This is an advanced topic. Simple implement com.alexecollins.vbox.core.patch.Patch and add that and the appropriate information to your POM. E.g. package com.alexecollins.vbox.maven.patch; import com.alexecollins.vbox.core.VBox; import com.alexecollins.vbox.core.patch.Patch; public class NoopPatch implements Patch { public void apply(VBox box) throws Exception { // nop } public String getName() { return "NoopPatch"; } } And add the standard Maven implementation detail: <patches> <noopPatch implementation="com.alexecollins.vbox.patch.demo.NoopPatch"/> </patches><file_sep>package com.alexecollins.vbox.maven; import com.alexecollins.vbox.core.VBox; import com.alexecollins.vbox.core.task.Stop; /** * Stop all the boxes defined in src/main/vbox. * * @goal stop * @phase post-integration-test * @see StartMojo */ public class StopMojo extends AbstractVBoxesMojo { protected void execute(VBox box) throws Exception { new Stop(box).call(); } } <file_sep>package com.alexecollins.vbox.ant; import com.alexecollins.vbox.core.task.CreateDefinition; import org.apache.tools.ant.BuildException; /** * Create a definition from the named template. * * @author alexec (<EMAIL>) */ public class CreateDefinitionTask extends AbstractTask { private String name; public void setName(String name) { this.name = name; } @Override public void execute() throws BuildException { if (name == null) { throw new BuildException("name is null"); } if (dir == null) { throw new BuildException("dir is null"); } try { new CreateDefinition(context(), name, dir).call(); } catch (Exception e) { throw new BuildException(e); } } } <file_sep>package com.alexecollins.vbox.ant; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Task; import java.io.IOException; /** * Purge the local repo of old files. * * @author alexec (<EMAIL>) * @since 3.0.0 */ public class PurgeLocalRepositoryTask extends Task { @Override public void execute() throws BuildException { try { new com.alexecollins.vbox.core.task.PurgeLocalRepository().call(); } catch (IOException e) { throw new BuildException(e); } } } <file_sep>Ant === Quick Start --- Add this to your build.xml: <project name="vbox-ant-tasks" default="build" xmlns:vbox="antlib:com.alexecollins.vbox.ant"> <target name="build"> <property name="context" value="ant-project:1.0.0"/> <property name="app" location="src/vbox/app1"/> <vbox:purge-local-repository/> <vbox:list-definitions/> <vbox:delete-definition dir="${app}"/> <vbox:create-definition name="CentOS_6_5" dir="${app}"/> <vbox:patch-definition dir="${app}"> <archPatch/> <predefinedPatch name="CentOS_6_5--tomcat6"/> </vbox:patch-definition> <vbox:clean dir="${app}" context="${context}"/> <vbox:create dir="${app}" context="${context}"/> <vbox:provision dir="${app}" context="${context}"/> <vbox:start dir="${app}"/> <!-- ... --> <vbox:stop dir="${app}"/> </target> </project> Add the vbox-ant-tasks-*.jar to Ant's class path. Ant tasks do not currently allow you to do multiple VMs in a single command. You'll need to use multiple ones. An example can be [found here](https://github.com/alexec/maven-vbox-plugin/tree/master/vbox-examples/ant). <file_sep>package com.alexecollins.vbox.ant; import com.alexecollins.vbox.core.VBox; import com.alexecollins.vbox.core.task.Ssh; import org.apache.tools.ant.BuildException; /** * @author alexec (<EMAIL>) */ public class SshTask extends AbstractTask { @Override public void execute() throws BuildException { if (dir == null) { throw new BuildException("dir is null"); } try { new Ssh(new VBox(context(), dir.toURI())).call(); } catch (Exception e) { throw new BuildException(e); } } } <file_sep>package com.alexecollins.vbox.provisioning; import com.alexecollins.vbox.core.task.AbstractTest; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import static junit.framework.Assert.assertTrue; /** * @author <EMAIL> */ @RunWith(Parameterized.class) public class ProvisionsTest extends AbstractTest { public ProvisionsTest(final String name) throws Exception { super(name); } @Test public void testGetPortForwardOrKeyboardPutScanCodesOrSleep() throws Exception { final Provisioning sut = getBox().getProvisioning(); assertTrue(sut.getTarget().size() > 0); for (Provisioning.Target target : sut.getTarget()) { assert target.getName() != null; } } } <file_sep>Maven === Quick Start --- Add this to your pom.xml: <plugin> <groupId>com.alexecollins.vbox</groupId> <artifactId>vbox-maven-plugin</artifactId> <version>2.0.0</version> <executions> <execution> <goals> <goal>clean</goal> <goal>provision</goal> <goal>start</goal> <goal>stop</goal> </goals> </execution> </executions> </plugin> Execute this: mvn vbox:create-definition -Dvbox.name=CentOS_6_5 Execute: mvn verify Maven searches for VM definitions under src/main/vbox. Example can be [found here](https://github.com/alexec/maven-vbox-plugin/tree/master/vbox-examples/maven). <file_sep>package com.alexecollins.vbox.core.ssh; import com.jcraft.jsch.UserInfo; /** * @author alexec (<EMAIL>) * @since 3.0.0 */ public abstract class AbstractUserInfo implements UserInfo { protected String passphrase; protected String password; public String getPassphrase() { return passphrase; } public String getPassword() { return password; } } <file_sep>package com.alexecollins.vbox.maven; import com.alexecollins.vbox.core.VBox; import com.alexecollins.vbox.core.task.Ssh; /** * Connect to the box. * * @goal ssh * @author alexec (<EMAIL>) * @since 3.0.0 */ public class SshMojo extends AbstractVBoxesMojo { @Override protected void execute(VBox box) throws Exception { new Ssh(box).call(); } } <file_sep>package com.alexecollins.vbox.maven.patch; /** * @author alexec (<EMAIL>) * @since 2.0.0 */ public class ArchPatch extends com.alexecollins.vbox.core.patch.ArchPatch { } <file_sep>Vs. Vagrant === You might ask yourself "why would I use this rather than vagrant". The answer is "you almost certainly wouldn't", I know I would use Vagrant instead. This isn't intended for production use. It's more of an investigation and learning tool for me to learn about Virtual machines, networking (which is a pain) and provisioning. Here are a few differences: | Vagarant | VBox Java API | |-----------------------------+-----------------------------+------------------------------| | State | Mature & Common | Immature | | Language | Ruby | Java | | Configuration | Ruby | XML | | Base Boxes | VeeWee | In Built | | Provisioning | Chef or Puppet | SSH / Patches | | Interface | Command Line | Ant or Maven |<file_sep>package com.alexecollins.vbox.core; import org.junit.Test; import static org.junit.Assert.assertArrayEquals; /** * @author alexec (<EMAIL>) */ public class ScanCodesTest { @Test public void testGetScanCode() throws Exception { assertArrayEquals(new int[]{0x01, 0x81}, ScanCodes.forKey("Esc")); assertArrayEquals(new int[]{0x02, 0x82}, ScanCodes.forKey("1")); assertArrayEquals(new int[]{0x2a, 0x02, 0x82, 0xaa}, ScanCodes.forKey("!")); assertArrayEquals(new int[]{0x1c, 0x9c}, ScanCodes.forKey("Enter")); assertArrayEquals(new int[]{0x2a, 0x27, 0xa7, 0xaa}, ScanCodes.forKey(":")); assertArrayEquals(new int[]{0x1e, 0x9e}, ScanCodes.forKey("a")); assertArrayEquals(new int[]{0x2a, 0x1e, 0x9e, 0xaa}, ScanCodes.forKey("A")); assertArrayEquals(new int[]{0x31, 0xb1}, ScanCodes.forKey("n")); assertArrayEquals(new int[]{0x26, 0xa6}, ScanCodes.forKey("l")); assertArrayEquals(new int[]{0x35, 0xb5}, ScanCodes.forKey("/")); assertArrayEquals(new int[]{0x22, 0xa2}, ScanCodes.forKey("g")); assertArrayEquals(new int[]{57, 185}, ScanCodes.forKey(" ")); assertArrayEquals(new int[]{13, 141}, ScanCodes.forKey("=")); } @Test public void testText() { assertArrayEquals(new int[]{0x02, 0x82, 0x2a, 0x02, 0x82, 0xaa}, ScanCodes.forString("1!")); assertArrayEquals(new int[]{0x39, 0xb9}, ScanCodes.forString(" ")); } } <file_sep>package com.alexecollins.util; import com.alexecollins.vbox.core.Work; import de.tu_darmstadt.informatik.rbg.hatlak.iso9660.ISO9660RootDirectory; import de.tu_darmstadt.informatik.rbg.hatlak.iso9660.impl.CreateISO; import de.tu_darmstadt.informatik.rbg.hatlak.iso9660.impl.ISO9660Config; import de.tu_darmstadt.informatik.rbg.hatlak.iso9660.impl.ISOImageFileHandler; import de.tu_darmstadt.informatik.rbg.hatlak.joliet.impl.JolietConfig; import de.tu_darmstadt.informatik.rbg.hatlak.rockridge.impl.RockRidgeConfig; import de.tu_darmstadt.informatik.rbg.mhartle.sabre.StreamHandler; import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.concurrent.ExecutionException; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Utils for creating disk images. * * @author <EMAIL> */ public class ImageUtils { private static final Logger LOGGER = LoggerFactory.getLogger(ImageUtils.class); /** * Create an image based on file extension. */ public static void createImage(final Work work, final File src, final File dest) throws InterruptedException, ExecutionException, IOException { if (work == null) {throw new IllegalArgumentException("work is null or is not directory");} if (src == null || !src.isDirectory()) {throw new IllegalArgumentException("src is null or is not directory");} if (dest == null) {throw new IllegalArgumentException("dest must not be null and end in '.iso'");} if (dest.getName().endsWith(".img")) { createFloppyImage(work, src, dest); } else if (dest.getName().endsWith(".iso")) { createDVDImage(src, dest); } else { throw new UnsupportedOperationException("unknown file extension on " + dest); } } private static void createFloppyImage(Work work, final File source, final File dest) throws IOException, InterruptedException, ExecutionException { // http://wiki.osdev.org/Disk_Images if (dest == null || !dest.getName().endsWith(".img")) {throw new IllegalArgumentException("dest must not be null and end in '.iso'");} final String os = System.getProperty("os.name"); if (os.contains("Windows")) { final File f = new File(work.getCacheDir(), "bfi10.zip"); if (!f.exists()) FileUtils.copyURLToFile(new URL("ftp://dl.xs4all.nl/pub/mirror/nu2files/bfi10.zip"), f); assert f.exists(); ZipUtils.unzip(f, f.getParentFile()); ExecUtils.exec(new File(f.getParentFile(), "bfi.exe").getCanonicalPath(), "-f=" + dest.getCanonicalPath(), source.getCanonicalPath()); } else if (os.contains("Mac")) { // http://www.jedi.be/blog/2009/11/17/commandline-creation-of-msdos-floppy-on-macosx/ ExecUtils.exec("dd", "bs=512", "count=2880", "if=/dev/zero", "of=" + dest.getPath()); final String dev = ExecUtils.exec("hdid", "-nomount", dest.getPath()).trim(); try { ExecUtils.exec("newfs_msdos", dev); } finally { ExecUtils.exec("hdiutil", "detach", dev); } final String out = ExecUtils.exec("hdid", dest.getPath()); final Matcher m = Pattern.compile(" *(.*)").matcher(out); if (!m.find()) { throw new IllegalStateException("failed to find mount point in " + out); } final File device = new File(m.group(1).trim()); try { FileUtils.copyDirectory(source, device); } finally { ExecUtils.exec("hdiutil", "detach", device.getPath()); } } else { LOGGER.warn("unsupported OS " + os + ", hoping it's *NIX and executing some un-tested code, email me at <EMAIL> if you see this message and you have any problems"); // http://stackoverflow.com/questions/11202706/create-a-virtual-floppy-image-without-mount ExecUtils.exec("dd", "if=/dev/zero", "of=" + dest.getPath(), "count=1440","bs=1k"); ExecUtils.exec("mkfs.msdos", dest.getPath()); for (File f : source.listFiles()) { ExecUtils.exec("mcopy", "-s", "-i", dest.getPath(), f.getPath(), "::/"); } } } /** * Create an ISO image for src. */ private static void createDVDImage(final File src, final File dest) { if (dest == null || !dest.getName().endsWith(".iso")) {throw new IllegalArgumentException("dest must not be null and end in '.iso'");} final ISO9660RootDirectory root = new ISO9660RootDirectory(); try { root.addContentsRecursively(src); final StreamHandler streamHandler = new ISOImageFileHandler(dest); CreateISO iso = new CreateISO(streamHandler, root); iso.process(new ISO9660Config(), new RockRidgeConfig(), new JolietConfig(), null); } catch (Exception e) { throw new RuntimeException("failed to create image", e); } } /* private static void createFloppyImage1(final File source, final File dest) throws Exception { final FileDisk disk = FileDisk.create(dest, (long) 1440 * 1024); final FatFileSystem fs = SuperFloppyFormatter.get(disk).format(); for (final File file : source.listFiles()) { if (file.isFile()) { final FatLfnDirectoryEntry fe = fs.getRoot().addFile(file.getName()); final FatFile floppyFile = fe.getFile(); final FileInputStream fis = new FileInputStream(file); final FileChannel fci = fis.getChannel(); final ByteBuffer buffer = ByteBuffer.allocate(1024); long counter = 0; long len = 0; // http://www.kodejava.org/examples/49.html // Here we start to read the source file and write it // to the destination file. We repeat this process // until the read method of input stream channel return // nothing (-1). while (true) { // read a block of data and put it in the buffer final int read = fci.read(buffer); // did we reach the end of the channel? if yes // jump out the while-loop if (read == -1) { break; } // flip the buffer buffer.flip(); // write to the destination channel floppyFile.write(counter * 1024, buffer); counter++; len += read; // clear the buffer and user it for the next read // process buffer.clear(); } if (len != file.length()) { throw new AssertionError("expected to copy " + file.length() + ", copied " + len); } floppyFile.flush(); fis.close(); } else if (file.isDirectory()) { fs.getRoot().addDirectory(file.getName()); } else { throw new UnsupportedOperationException(); } } fs.close(); disk.close(); } */ } <file_sep>#! /bin/sh set -ue apt-get -y install acpid linux-headers-$(uname -r) build-essential mount /dev/cdrom /media/cdrom /media/cdrom/VBoxLinuxAdditions.run eject /dev/cdrom poweroff now <file_sep>32 Bit vs 64 Bit === Currently the definitions are all 32 bit. I _think_ you'll want to use the same bits on the guest as the host. It'll be faster. If you want use 64 bit you typically need to: - Ensure hardware virtualizaiton is enabled on the host (see (http://www.parallels.com/uk/products/novt)) - Append "_64" to the OS type, e.g. "RedHat_64". - Enable IO ACPI (as a side-effect, it'll be much faster, if your host OS is 64 bit). - Use a 64 ISO (note that Windows will install the appropriate kernel for you, but you cannot change it once it's installed). To save time, a patch is provided that will detect the host arch and apply a patch to the guest, e.g.: <patches> <archPatch/> </patches> The patch will make the appropriate changes and choose an ISO for you. <file_sep>Known Issues === * US keyboard layouts only. * Limited sub-set of vbox set-up supported. <file_sep>Overview === This project provides support for creating, starting and stopping VirtualBox VMs. This is aimed at development and integration testing of projects by allowing you to package a complete software stack onto a single machine, install your code and perform your tests. Some typical scenarios would be: * Provide a dev stack and a touch of a button. * Install all apps onto a VBox and test it. It provides: 1. A Java API for programmatic control of boxes. 2. A set of Maven Mojos. 3. A set of matching Ant tasks. <file_sep>References === * [VBoxManage](http://www.virtualbox.org/manual/ch08.html) * [Ubuntu/Debian preseed.cfg](https://help.ubuntu.com/12.10/installation-guide/i386/preseed-using.html) * [VeeWee](https://github.com/jedi4ever/veewee) * [Oracle blog on VirtualBox networking](https://blogs.oracle.com/fatbloke/entry/networking_in_virtualbox1) * [Enforcer Plugin Custom Rule](http://maven.apache.org/enforcer/enforcer-api/writing-a-custom-rule.html) * [Patch Format](http://www.markusbe.com/2009/12/how-to-read-a-patch-or-diff-and-understand-its-structure-to-apply-it-manually/#how-to-read-a-unified-diff) <file_sep><project name="vbox-ant-tasks" default="build" xmlns:vbox="antlib:com.alexecollins.vbox.ant"> <target name="build"> <property name="context" value="ant-project:1.0.0"/> <property name="app" location="src/vbox/app1"/> <vbox:purge-local-repository/> <vbox:list-definitions/> <vbox:delete-definition dir="${app}"/> <vbox:create-definition name="CentOS_6_5" dir="${app}"/> <vbox:patch-definition dir="${app}"> <archPatch/> <predefinedPatch name="CentOS_6_5--tomcat6"/> </vbox:patch-definition> <vbox:clean dir="${app}" context="${context}"/> <vbox:create dir="${app}" context="${context}"/> <vbox:provision dir="${app}" context="${context}"/> <vbox:start dir="${app}" context="${context}"/> <vbox:status dir="${app}" context="${context}"/> <vbox:suspend dir="${app}" context="${context}"/> <vbox:resume dir="${app}" context="${context}"/> <!-- ... --> <vbox:stop dir="${app}" context="${context}"/> </target> </project><file_sep>package com.alexecollins.vbox.core.ssh; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author alexec (<EMAIL>) */ public class PresetUserInfo extends AbstractUserInfo { private static final Logger LOGGER = LoggerFactory.getLogger(PresetUserInfo.class); public PresetUserInfo(String password, String passphrase) { this.password = <PASSWORD>; this.passphrase = passphrase; } public boolean promptPassword(String message) { return true; } public boolean promptPassphrase(String message) { return true; } public boolean promptYesNo(String message) { return true; } public void showMessage(String message) { LOGGER.info(message); } }<file_sep><?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>vbox-examples</artifactId> <groupId>com.alexecollins.vbox</groupId> <version>3.0.1-SNAPSHOT</version> <relativePath>..</relativePath> </parent> <modelVersion>4.0.0</modelVersion> <packaging>pom</packaging> <artifactId>maven-example</artifactId> <name>Maven Example</name> <profiles> <profile> <id>run-its</id> <build> <plugins> <plugin> <groupId>com.alexecollins.vbox</groupId> <artifactId>vbox-maven-plugin</artifactId> <version>3.0.1-SNAPSHOT</version> <executions> <execution> <goals> <goal>delete-definition</goal> <goal>create-definition</goal> <goal>patch-definition</goal> <goal>provision</goal> <goal>start</goal> <goal>stop</goal> </goals> <configuration> <name>app1.test</name> <templateName>CentOS_6_5</templateName> <patches> <archPatch /> <predefinedPatch> <name>CentOS_6_5--tomcat6</name> </predefinedPatch> </patches> <names>app1.test</names> </configuration> </execution> </executions> </plugin> </plugins> </build> </profile> </profiles> </project><file_sep>package com.alexecollins.vbox.core.task; import au.com.bytecode.opencsv.CSVReader; import com.alexecollins.util.DurationUtils; import com.alexecollins.util.ExecUtils; import com.alexecollins.vbox.core.ScanCodes; import com.alexecollins.vbox.core.Snapshot; import com.alexecollins.vbox.core.VBox; import com.alexecollins.vbox.core.Work; import com.alexecollins.vbox.provisioning.Provisioning; import org.apache.commons.lang.ArrayUtils; import org.mortbay.jetty.Server; import org.mortbay.jetty.handler.ResourceHandler; import org.mortbay.resource.Resource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.StringReader; import java.net.*; import java.util.*; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeoutException; public class Provision extends AbstractTask { private static final Logger LOGGER = LoggerFactory.getLogger(Provision.class); private final Server server; private final Set<String> targets; public Provision(Work work, VBox box, Set<String> targets) throws IOException { super(work, box); this.targets = targets; server = new Server(Provision.findFreePort()); } public Void call() throws Exception { if (box.exists()) { new Stop(box).call(); } verifySignature(); final Snapshot snapshot = Snapshot.POST_PROVISIONING; if (box.exists()) { box.powerOff(); if (box.getSnapshots().contains(snapshot)) { LOGGER.info("restoring '" + box.getName() + "' from snapshot " + snapshot); box.restoreSnapshot(Snapshot.POST_PROVISIONING); return null; } } // if the box doesn't exist, create it if (!box.exists()) { new Create(work, box).call(); } LOGGER.info("provisioning '" + box.getName() + "'"); // TODO startServer(box); try { final List<Provisioning.Target> targets = box.getProvisioning().getTarget(); for (Provisioning.Target target : targets) { if (this.targets.contains(target.getName()) || this.targets.equals(Collections.<String>singleton("*"))) { if (target.equals(targets.get(0)) && !box.getProperties().getProperty("VMState").equals("running")) { LOGGER.info("starting box"); box.start(); } executeTarget(box, target); if (target.equals(targets.get(targets.size() - 1))) { if (box.getProperties().getProperty("VMState").equals("running")) { LOGGER.info("stopping box"); box.pressPowerButton(); box.awaitState((long) 10000, "poweroff"); } box.takeSnapshot(snapshot); } } else { LOGGER.info("skipping target " + target.getName()); } } } finally { // TODO uncomment - stopServer(); } return null; } private void executeTarget(final VBox box, final Provisioning.Target target) throws IOException, InterruptedException, TimeoutException, ExecutionException { LOGGER.info("executing target " + target.getName()); for (Object o : target.getPortForwardOrAwaitPortOrAwaitState()) { LOGGER.debug("executing " + o); if (o instanceof Provisioning.Target.PortForward) portForward(box.getName(), (Provisioning.Target.PortForward) o); else if (o instanceof Provisioning.Target.KeyboardPutScanCodes) keyboardPutScanCodes(box.getName(), ((Provisioning.Target.KeyboardPutScanCodes) o)); else if (o instanceof Provisioning.Target.Sleep) { final Provisioning.Target.Sleep s = (Provisioning.Target.Sleep) o; final long seconds = s.getMinutes() * 60 + s.getSeconds(); LOGGER.info("sleeping for " + seconds + " second(s)"); Thread.sleep(seconds * 1000); } else if (o instanceof Provisioning.Target.Exec) { try { ExecUtils.exec(new CSVReader(new StringReader(subst(((Provisioning.Target.Exec) o).getValue())), ' ').readNext()); } catch (ExecutionException e) { if (((Provisioning.Target.Exec) o).isFailonerror()) throw e; else LOGGER.info("ignoring error " + e.getMessage()); } } else if (o instanceof Provisioning.Target.AwaitPort) { awaitPort((Provisioning.Target.AwaitPort) o); } else if (o instanceof Provisioning.Target.AwaitState) { box.awaitState( DurationUtils.millisForString(((Provisioning.Target.AwaitState) o).getTimeout()), ((Provisioning.Target.AwaitState) o).getState()); } else throw new AssertionError("unexpected provision"); } // snapshots are expensive in terms of disk space // box.takeSnapshot(Snapshot.valueOf("post-provision-" + target.getName())); } private void awaitPort(final Provisioning.Target.AwaitPort ap) throws IOException, TimeoutException, InterruptedException { awaitPort(ap.getHost(), ap.getPort(), ap.getTimeout()); } public static void awaitPort(String host, int port, String timeout) throws IOException, TimeoutException, InterruptedException { final long start = System.currentTimeMillis(); final String desc = host + ":" + port; while (true) { final long remaining = start + DurationUtils.millisForString(timeout) - System.currentTimeMillis(); LOGGER.info("awaiting " + desc + " for " + DurationUtils.prettyPrint(remaining)); try { new Socket(host, port).close(); LOGGER.info("port available"); return; } catch (ConnectException e) { // nop } if (remaining < 0) { throw new TimeoutException("timed out waiting for " + desc); } Thread.sleep(Math.min(10000l, remaining)); } } void stopServer() throws Exception { if (server.isRunning()) { LOGGER.info("stopping local web server"); server.stop(); } } void startServer(final VBox box) throws Exception { LOGGER.info("starting local web server on port " + getServerPort()); final ResourceHandler rh = new ResourceHandler(); rh.setBaseResource(Resource.newResource(box.getSrc().toURL())); LOGGER.info("serving " + rh.getResourceBase()); server.setHandler(rh); server.start(); final URL u = new URL("http://" + InetAddress.getLocalHost().getHostAddress() + ":" + getServerPort() + "/VirtualBox.xml"); LOGGER.info("testing server by getting " + u); final HttpURLConnection c = (HttpURLConnection) u.openConnection(); c.connect(); if (200 != c.getResponseCode()) throw new IllegalStateException(c.getResponseCode() + " " +c.getResponseMessage()); c.disconnect(); } private static int findFreePort() throws IOException { final ServerSocket server = new ServerSocket(0); final int port = server.getLocalPort(); server.close(); return port; } public void keyboardPutScanCodes(String name, Provisioning.Target.KeyboardPutScanCodes ksc) throws IOException, InterruptedException, ExecutionException { { final String keys = ksc.getKeys(); if (keys != null) { LOGGER.info("typing keys " + keys); final List<Integer> sc = new ArrayList<Integer>(); for (String key : keys.split(",")) { for (int c : ScanCodes.forKey(key)) { sc.add(c); } } keyboardPutScanCodes(name, ArrayUtils.toPrimitive(sc.toArray(new Integer[sc.size()]))); } } { String line; line = ksc.getLine(); if (line != null) { line = subst(line); LOGGER.info("typing line '" + line + "'"); keyboardPutScanCodes(name, ArrayUtils.addAll(ScanCodes.forString(line), ScanCodes.forKey("Enter"))); } } { String text = ksc.getValue(); if (text != null && text.length() > 0) { text = subst(text); LOGGER.info("typing text '" + text + "'"); keyboardPutScanCodes(name, ArrayUtils.addAll(ScanCodes.forString(text), ScanCodes.forKey("Enter"))); } } } @Override public String subst(String line) throws IOException, InterruptedException, ExecutionException { line = line.replaceAll("\\$\\{server\\.ip\\}", InetAddress.getLocalHost().getHostAddress()); line = line.replaceAll("\\$\\{server\\.port\\}", String.valueOf(getServerPort())); return super.subst(line); } private void keyboardPutScanCodes(String name, int[] scancodes) throws IOException, InterruptedException, ExecutionException { LOGGER.debug("typing " + Arrays.toString(scancodes)); while (scancodes.length > 0) { final List<String> command = new ArrayList<String>(); command.addAll(Arrays.asList("vboxmanage", "controlvm", name, "keyboardputscancode")); int i = 0; for (int scancode : scancodes) { command.add((scancode > 0xf ? "" : "0") + Integer.toHexString(scancode)); i++; // split on enter if (i >= 16 || scancode == 156) { break; } } ExecUtils.exec(command.toArray(new String[command.size()])); Thread.sleep(scancodes[i - 1] == 156 ? 2000 : 100); // a short sleep to let the OS digest scancodes = ArrayUtils.subarray(scancodes, i, scancodes.length); } } private void portForward(String name, Provisioning.Target.PortForward pf) throws IOException, InterruptedException, ExecutionException { final int hostPort = pf.getHostport(); final int guestPort = pf.getGuestport(); LOGGER.info("adding port forward hostport=" + hostPort + " guestport=" + guestPort); ExecUtils.exec("vboxmanage", "setextradata", name, "VBoxInternal/Devices/e1000/0/LUN#0/Config/" + guestPort + "/HostPort", String.valueOf(hostPort)); ExecUtils.exec("vboxmanage", "setextradata", name, "VBoxInternal/Devices/e1000/0/LUN#0/Config/" + guestPort + "/GuestPort", String.valueOf(guestPort)); ExecUtils.exec("vboxmanage", "setextradata", name, "VBoxInternal/Devices/e1000/0/LUN#0/Config/" + guestPort + "/Protocol", "TCP"); } public int getServerPort() { return server.getConnectors()[0].getPort(); } }<file_sep>Examples === <iframe width="640" height="360" src="http://www.youtube.com/embed/Y4ZXD7psIuM" frameborder="0" allowfullscreen="true"></iframe> * [Five minute demo](http://www.youtube.com/watch?v=Y4ZXD7psIuM) * [Ant and Maven examples](https://github.com/alexec/maven-vbox-plugin/tree/master/vbox-examples/) * [Example Maven project](https://github.com/alexec/maven-vbox-plugin-example)
63c21574bb11406a57cb5ce99cef55f07881c7d9
[ "Markdown", "Maven POM", "Java", "Ant Build System", "Shell" ]
59
Java
manniru/maven-vbox-plugin
24eacc394eda9be9738f71dd211a43c6ded73181
9ecf419168590db1859fbe4b823fa104df746c7d
refs/heads/master
<repo_name>sav6622/jfes<file_sep>/examples/examples.h /** \file examples.h \author <NAME> (http://github.com/NeonMercury) \date October, 2015 \brief Header file for declarations of examples entry points. */ #ifndef EXAMPLE_1_H_INCLUDE_GUARD #define EXAMPLE_1_H_INCLUDE_GUARD /** Entry point for example_1. */ int example_1_entry(int argc, char **argv); /** Entry point for example_2. */ int example_2_entry(int argc, char **argv); /** Entry point for example_3. */ int example_3_entry(int argc, char **argv); /** Helper function. Saves file content. \param[in] filename Filename to get content. \param[out] content Pointer to content buffer. \param[in] content_size Content buffer size. \return Zero, if function failed. Anything otherwise. */ int set_file_content(const char *filename, char *content, long content_size); /** Helper function. Loads file content. \param[in] filename Filename to get content. \param[out] content Pointer to content buffer. \param[in, out] max_content_size Maximal content buffer size. Returns file size. \return Zero, if function failed. Anything otherwise. */ int get_file_content(const char *filename, char *content, long *max_content_size); #endif<file_sep>/README.md # JFES *Based on [jsmn](https://github.com/zserge/jsmn) project.* Json For Embedded Systems (JFES) is a minimalistic [json](http://www.json.org/) engine, written in plain C. It can be easily integrated into the code for embedded systems. ## Features * compatible with C99 * no dependencies (I'm seriously!) * highly portable * you can use it only like json parser * incremental single-pass parsing ## API ### Initializing Before use you need to initialize `jfes_config_t` object. ``` /** JFES config structure. */ typedef struct jfes_config { jfes_malloc_t jfes_malloc; /**< Memory allocation function. */ jfes_free_t jfes_free; /**< Memory deallocation function. */ } jfes_config_t; ``` Below you can see prototypes of memory management functions: ``` /** Memory allocator function type. */ typedef void *(__cdecl *jfes_malloc_t)(jfes_size_t); /** Memory deallocator function type. */ typedef void (__cdecl *jfes_free_t)(void*); ``` As you can see, these functions has the same prototype with C functions from standard library. So, you can initialize JFES configuration with this code: ``` #include <stdlib.h> /* ...some useful stuff... */ jfes_config_t config; config.jfes_malloc = malloc; config.jfes_free = free; ``` But, if you need to use your own memory management functions, use them. ### Parser (optional) If you need only to parse *.json file without allocating any values (like [jsmn](https://github.com/zserge/jsmn)), you can only parse json string and separate it on tokens. In this case, you need to use only two functions: ``` /** JFES parser initialization. \param[out] parser Pointer to the jfes_parser_t object. \param[in] config JFES configuration. \return jfes_success if everything is OK. */ jfes_status_t jfes_init_parser(jfes_parser_t *parser, jfes_config_t *config); /******************************************************************/ /** Run JSON parser. It parses a JSON data string into and array of tokens, each describing a single JSON object. \param[in] parser Pointer to the jfes_parser_t object. \param[in] json JSON data string. \param[in] length JSON data length. \param[out] tokens Tokens array to fill. \param[in, out] max_tokens_count Maximal count of tokens in tokens array. Will contain tokens count. \return jfes_success if everything is OK. */ jfes_status_t jfes_parse_tokens(jfes_parser_t *parser, const char *json, jfes_size_t length, jfes_token_t *tokens, jfes_size_t *max_tokens_count); ``` You can see parsing example below. ### Loading *.json into value You can load any json data into `jfes_value_t`. ``` /** JSON value structure. */ struct jfes_value { jfes_value_type_t type; /**< JSON value type. */ jfes_value_data_t data; /**< Value data. */ }; ``` Value type (`jfes_value_type_t`) can be one of this: * `jfes_boolean` * `jfes_integer` * `jfes_double` * `jfes_string` * `jfes_array` * `jfes_object` And `jfes_value_data_t` is: ``` /** JFES value data union. */ typedef union jfes_value_data { int bool_val; /**< Boolean JSON value. */ int int_val; /**< Integer JSON value. */ double double_val; /**< Double JSON value. */ jfes_string_t string_val; /**< String JSON value. */ jfes_array_t *array_val; /**< Array JSON value. */ jfes_object_t *object_val; /**< Object JSON value. */ } jfes_value_data_t; ``` You can easily load json string into the value with this code: ``` jfes_config_t config; config.jfes_malloc = malloc; config.jfes_free = free; jfes_value_t value; jfes_parse_to_value(&config, json_data, json_size, &value); /* Do something with value */ jfes_free_value(&config, &value); ``` That's all! ### Value modification You can modify or create `jfes_value_t` with any of these functions: ``` jfes_value_t *jfes_create_boolean_value(jfes_config_t *config, int value); jfes_value_t *jfes_create_integer_value(jfes_config_t *config, int value); jfes_value_t *jfes_create_double_value(jfes_config_t *config, double value); jfes_value_t *jfes_create_string_value(jfes_config_t *config, const char *value, jfes_size_t length); jfes_value_t *jfes_create_array_value(jfes_config_t *config); jfes_value_t *jfes_create_object_value(jfes_config_t *config); jfes_value_t *jfes_get_child(jfes_value_t *value, const char *key, jfes_size_t key_length); jfes_object_map_t *jfes_get_mapped_child(jfes_value_t *value, const char *key, jfes_size_t key_length); jfes_status_t jfes_place_to_array(jfes_config_t *config, jfes_value_t *value, jfes_value_t *item); jfes_status_t jfes_place_to_array_at(jfes_config_t *config, jfes_value_t *value, jfes_value_t *item, jfes_size_t place_at); jfes_status_t jfes_remove_from_array(jfes_config_t *config, jfes_value_t *value, jfes_size_t index); jfes_status_t jfes_set_object_property(jfes_config_t *config, jfes_value_t *value, jfes_value_t *item, const char *key, jfes_size_t key_length); jfes_status_t jfes_remove_object_property(jfes_config_t *config, jfes_value_t *value, const char *key, jfes_size_t key_length); ``` ### Serializing to json string You can serialize any `jfes_value_t` to string with one line (actually, three lines, but two of them is for help): ``` char dump[1024]; jfes_size_t dump_size = 1024; jfes_value_to_string(&value, beauty_dump, &dump_size, 1); beauty_dump[dump_size] = '\0'; /* If you need null-terminated string. */ ``` `dump_size` will store dump size. If you pass fourth argument as 1, dump will be beautified. And if zero, dump will be ugly. ## Examples You can find examples [here](https://github.com/NeonMercury/jfes/tree/master/examples). ## Licence **The MIT License (MIT)** [See full text.](https://github.com/NeonMercury/jfes/blob/master/LICENSE) <file_sep>/main.c /** \file main.c \author <NAME> (http://github.com/NeonMercury) \date October, 2015 \brief Examples loader. */ #include "jfes.h" #include "examples/examples.h" /* Only for file functions. */ #include <stdio.h> /** Entry point. */ int main(int argc, char **argv) { return example_3_entry(argc, argv); } int set_file_content(const char *filename, char *content, long content_size) { if (!filename || !content || content_size <= 0) { return 0; } FILE *f = fopen(filename, "w"); if (!f) { return 0; } fwrite(content, content_size, sizeof(char), f); fclose(f); return 1; } int get_file_content(const char *filename, char *content, long *max_content_size) { if (!filename || !content || !max_content_size || *max_content_size <= 0) { return 0; } FILE *f = fopen(filename, "r"); if (!f) { return 0; } fseek(f, 0, SEEK_END); long fsize = ftell(f); fseek(f, 0, SEEK_SET); long read_size = fsize; if (*max_content_size < read_size) { read_size = *max_content_size; } fread(content, read_size, sizeof(char), f); fclose(f); *max_content_size = read_size; return 1; }<file_sep>/jfes.c /** \file jfes.c \author <NAME> (http://github.com/NeonMercury) \date October, 2015 \brief Json For Embedded Systems library source code. */ #include "jfes.h" /** Needs for the buffer in jfes_(int/double)_to_string. */ #define JFES_MAX_DIGITS 64 /** Stream helper. */ typedef struct jfes_stringstream { char *data; /**< String data. */ jfes_size_t max_size; /**< Maximal data size. */ jfes_size_t current_index; /**< Current index to the end of the data. */ } jfes_stringstream_t; /** Memory comparing function. \param[in] p1 Pointer to the first buffer. \param[in] p2 Pointer to the second buffer. \param[in] count Number of bytes to compare. \return Zero if all bytes are equal. */ static int jfes_memcmp(const void *p1, const void *p2, jfes_size_t count) { int delta = 0; unsigned char *ptr1 = (unsigned char *)p1; unsigned char *ptr2 = (unsigned char *)p2; while (count-- > 0 && delta == 0) { delta = *(ptr1++) - *(ptr2++); } return delta; } /** Copies memory. Doesn't support overlapping. \param[out] dst Output memory block. \param[in] src Input memory block. \param[in] count Bytes count to copy. \return Pointer to the destination memory. */ static const void *jfes_memcpy(const void *dst, const void *src, jfes_size_t count) { unsigned char *destination = (unsigned char *)dst; unsigned char *source = (unsigned char *)src; while (count-- > 0) { *(destination++) = *(source++); } return dst; } /** Allocates jfes_string. \param[in] config JFES configuration. \param[out] str String to be allocated. \param[in] size Size to allocate. \return jfes_success if everything is OK. */ static jfes_status_t jfes_allocate_string(jfes_config_t *config, jfes_string_t *str, jfes_size_t size) { if (!config || !str || size == 0) { return jfes_invalid_arguments; } str->size = size; str->data = config->jfes_malloc(str->size); return jfes_success; } /** Deallocates jfes_string. \param[in] config JFES configuration. \param[out] str String to be deallocated. \return jfes_success if everything is OK. */ static jfes_status_t jfes_free_string(jfes_config_t *config, jfes_string_t *str) { if (!config || !str) { return jfes_invalid_arguments; } if (str->size > 0) { str->size = 0; config->jfes_free(str->data); str->data = JFES_NULL; } return jfes_success; } /** Creates string object. \param[in] config JFES configuration. \param[out] str String to be created. \param[in] string Initial string value. \param[in] size Initial string length. \return jfes_success if everything is OK. */ static jfes_status_t jfes_create_string(jfes_config_t *config, jfes_string_t *str, const char *string, jfes_size_t size) { if (!config || !str || !string || size == 0) { return jfes_invalid_arguments; } jfes_status_t status = jfes_allocate_string(config, str, size + 1); if (jfes_status_is_bad(status)) { return status; } jfes_memcpy(str->data, string, size); str->data[size] = '\0'; return jfes_success; } /** Finds length of the null-terminated string. \param[in] data Null-terminated string. \return Length if the null-terminated string. */ static jfes_size_t jfes_strlen(const char *data) { if (!data) { return 0; } const char *p = data; while (*p++); return (jfes_size_t)(p - data) - 1; } /** Analyzes input string on the subject of whether it is null. \param[in] data Input string. \param[in] length Length if the input string. \return Zero, if input string not null. Otherwise anything. */ static int jfes_is_null(const char *data, jfes_size_t length) { if (!data || length != 4) { return 0; } return jfes_memcmp(data, "null", 4) == 0; } /** Analyzes input string on the subject of whether it is boolean. \param[in] data Input string. \param[in] length Length if the input string. \return Zero, if input string not boolean. Otherwise anything. */ static int jfes_is_boolean(const char *data, jfes_size_t length) { if (!data || length < 4) { return 0; } return jfes_memcmp(data, "true", 4) == 0 || jfes_memcmp(data, "false", 5) == 0; } /** Analyzes input string on the subject of whether it is an integer. \param[in] data Input string. \param[in] length Length if the input string. \return Zero, if input string not an integer. Otherwise anything. */ static int jfes_is_integer(const char *data, jfes_size_t length) { if (!data || length == 0) { return 0; } int offset = 0; if (data[0] == '-') { offset = 1; } for (jfes_size_t i = offset; i < length; i++) { if (data[i] < (int)'0' || data[i] > (int)'9') { return 0; } } return 1; } /** Analyzes input string on the subject of whether it is an double. \param[in] data Input string. \param[in] length Length if the input string. \return Zero, if input string not an double. Otherwise anything. */ static int jfes_is_double(const char *data, jfes_size_t length) { if (!data || length == 0) { return 0; } int offset = 0; if (data[0] == '-') { offset = 1; } int dot_already_been = 0; int exp_already_been = 0; for (jfes_size_t i = offset; i < length; i++) { if (data[i] < (int)'0' || data[i] > (int)'9') { if (data[i] == '.' && !dot_already_been) { dot_already_been = 1; continue; } else if ((data[i] == 'e' || data[i] == 'E') && i + 2 < length && (data[i + 1] == '+' || data[i + 1] == '-') && !exp_already_been) { exp_already_been = 1; i++; continue; } return 0; } } return 1; } /** Analyzes string and returns its boolean value. \param[in] data String to analysis. \param[in] length String length. \return 1, if data == 'true'. Otherwise 0. */ static int jfes_string_to_boolean(const char *data, jfes_size_t length) { if (!data || length < 4) { return 0; } if (jfes_memcmp(data, "true", 4) == 0) { return 1; } return 0; } /** Analyses string and returns its integer value. \param[in] data String to analysis. \param[in] length String length. \return Integer representation of the input data. */ static int jfes_string_to_integer(const char *data, jfes_size_t length) { if (!data || length == 0) { return 0; } int result = 0; int sign = 1; jfes_size_t offset = 0; if (data[0] == '-') { sign = -1; offset = 1; } for (jfes_size_t i = offset; i < length; i++) { char c = data[i]; if (c >= '0' && c <= '9') { result = result * 10 + (c - '0'); } } return result * sign; } /** Analyses string and returns its double value. \param[in] data String to analysis. \param[in] length String length. \return Double representation of the input data. */ static double jfes_string_to_double(const char *data, jfes_size_t length) { if (!data || length == 0) { return 0.0; } double result = 0.0; double sign = 1.0; int after_dot = 0; int exp = 0; int direction = 0; jfes_size_t index = 0; if (data[0] == '-') { sign = -1.0; index = 1; } for (; index < length; index++) { char c = data[index]; if (c >= '0' && c <= '9') { result = result * 10.0 + (c - '0'); if (after_dot) { exp--; } } else if (c == '.') { after_dot = 1; continue; } else if (index + 2 < length && (c == 'e' || c == 'E')) { index++; if (data[index] == '+') { direction = 1; index++; } else if (data[index] == '-') { direction = -1; index++; } break; } } if (index < length) { if (jfes_is_integer(data + index, length - index)) { int new_exp = jfes_string_to_integer(data + index, length - index); exp += direction * new_exp; } } while (exp < 0) { result /= 10.0; exp++; } while (exp > 0) { result *= 10.0; exp--; } return sign * result; } /** Returns boolean value as string. \param[in] value Value to stringify. \return String representation of given value. */ char *jfes_boolean_to_string(int value) { static char *true_value = "true"; static char *false_value = "false"; return value ? true_value : false_value; } /** Returns integer value as string. \param[in] value Value to stringify. \return String representation of given value. */ char *jfes_integer_to_string(int value) { static char buf[JFES_MAX_DIGITS + 3]; char *p = &buf[0] + JFES_MAX_DIGITS + 2; *--p = '\0'; int sign = 1; if (value < 0) { sign = -1; } do { *--p = '0' + sign * (value % 10); value /= 10; } while (value != 0); if (sign < 0) { *--p = '-'; } return p; } /** Returns double value as string. \param[in] value Value to stringify. \return String representation of given value. */ char *jfes_double_to_string(double value) { static char buf[JFES_MAX_DIGITS + 2]; static double precision_eps = 0.000000001; int int_value = (int)value; double fractional_value = value - int_value; if (fractional_value < 0) { fractional_value = -fractional_value; } double precision = precision_eps; while (precision < 1.0) { fractional_value *= 10; if (fractional_value - (int)fractional_value < precision_eps) { break; } precision *= 10.0; } int fractional_int = (int)fractional_value; char *int_value_s = jfes_integer_to_string(int_value); jfes_size_t value_length = jfes_strlen(int_value_s); jfes_memcpy(&buf[0], int_value_s, value_length); buf[value_length] = '.'; char *fractional_value_s = jfes_integer_to_string(fractional_int); jfes_size_t fractional_value_length = jfes_strlen(fractional_value_s); jfes_memcpy(&buf[value_length + 1], fractional_value_s, fractional_value_length); buf[value_length + 1 + fractional_value_length] = '\0'; return &buf[0]; } /** Initialize jfes_stringstream object. \param[out] stream Object to initialize. \param[in] data Pointer to the memory. \param[in] max_size Size of allocated memory. \return jfes_success if everything is OK. */ jfes_status_t jfes_initialize_stringstream(jfes_stringstream_t *stream, char *data, jfes_size_t max_size) { if (!stream || !data || max_size == 0) { return jfes_invalid_arguments; } stream->data = data; stream->max_size = max_size; stream->current_index = 0; return jfes_success; } /** Adds given data to the given stream. \param[out] stream Stringstream object. \param[in] data Data to add. \param[in] data_length Optional. Child key length. You can pass 0, if key string is zero-terminated. \return jfes_success if everything is OK. */ jfes_status_t jfes_add_to_stringstream(jfes_stringstream_t *stream, char *data, jfes_size_t data_length) { if (!stream || !data) { return jfes_invalid_arguments; } if (stream->current_index >= stream->max_size) { return jfes_no_memory; } if (data_length == 0) { data_length = jfes_strlen(data); } jfes_status_t status = jfes_success; jfes_size_t size_to_add = data_length; if (stream->current_index + size_to_add > stream->max_size) { size_to_add = stream->max_size - stream->current_index; status = jfes_no_memory; } jfes_memcpy(stream->data + stream->current_index, data, size_to_add); stream->current_index += size_to_add; return status; } /** Allocates a fresh unused token from the token pool. \param[in, out] parser Pointer to the jfes_parser_t object. \param[in, out] tokens Tokens array. \param[in] max_tokens Maximal tokens count. \return Pointer to an allocated token from token pool. */ static jfes_token_t *jfes_allocate_token(jfes_parser_t *parser, jfes_token_t *tokens, jfes_size_t max_tokens) { if (!parser || !tokens || max_tokens == 0 || parser->next_token >= max_tokens) { return JFES_NULL; } jfes_token_t *token = &tokens[parser->next_token++]; token->start = token->end = -1; token->size = 0; return token; } /** Analyzes the source string and returns most likely type. \param[in] data Source string bytes. \param[in] length Source string length. \return Most likely token type or `jfes_undefined`. */ static jfes_token_type_t jfes_get_token_type(const char *data, jfes_size_t length) { if (!data || length == 0) { return jfes_undefined; } jfes_token_type_t type = jfes_undefined; if (jfes_is_null(data, length)) { return jfes_null; } if (jfes_is_boolean(data, length)) { return jfes_boolean; } else if (jfes_is_integer(data, length)) { return jfes_integer; } else if (jfes_is_double(data, length)) { return jfes_double; } return jfes_undefined; } /** Fills token type and boundaries. \param[in, out] token Pointer to the token to fill. \param[in] type Token type. \param[in] start Token boundary start. \param[in] end Token boundary end. */ static void jfes_fill_token(jfes_token_t *token, jfes_token_type_t type, int start, int end) { if (token) { token->type = type; token->start = start; token->end = end; token->size = 0; } } /** Fills next available token with JSON primitive. \param[in, out] parser Pointer to the jfes_parser_t object. \param[in] json JSON data string. \param[in] length JSON data length. \param[out] tokens Tokens array to fill. \param[in] max_tokens_count Maximal count of tokens in tokens array. \return jfes_success if everything is OK. */ static jfes_status_t jfes_parse_primitive(jfes_parser_t *parser, const char *json, jfes_size_t length, jfes_token_t *tokens, jfes_size_t max_tokens_count) { if (!parser || !json || length == 0 || !tokens || max_tokens_count == 0) { return jfes_invalid_arguments; } int found = 0; char c = '\0'; jfes_size_t start = parser->pos; while (length && json[parser->pos] != '\0') { c = json[parser->pos]; if (c == '\t' || c == '\n' || c == '\r' || c == ' ' || c == ',' || c == ']' || c == '}' #ifndef JFES_STRICT || c == ':' #endif ) { found = 1; break; } parser->pos++; } #ifdef JFES_STRICT if (!found) { parser->pos = start; return jfes_error_part; } #endif jfes_token_t *token = jfes_allocate_token(parser, tokens, max_tokens_count); if (!token) { parser->pos = start; return jfes_no_memory; } jfes_size_t token_length = parser->pos - start; jfes_token_type_t type = jfes_get_token_type(json + start, token_length); jfes_fill_token(token, type, start, parser->pos); parser->pos--; return jfes_success; } /** Fills next available token with JSON string. \param[in, out] parser Pointer to the jfes_parser_t object. \param[in] json JSON data string. \param[in] length JSON data length. \param[out] tokens Tokens array to fill. \param[in] max_tokens_count Maximal count of tokens in tokens array. \return jfes_success if everything is OK. */ static jfes_status_t jfes_parse_string(jfes_parser_t *parser, const char *json, jfes_size_t length, jfes_token_t *tokens, jfes_size_t max_tokens_count) { if (!parser || !json || length == 0 || !tokens || max_tokens_count == 0) { return jfes_invalid_arguments; } jfes_size_t start = parser->pos++; while (parser->pos < length && json[parser->pos] != '\0') { char c = json[parser->pos]; if (c == '\"') { jfes_token_t *token = jfes_allocate_token(parser, tokens, max_tokens_count); if (!token) { parser->pos = start; return jfes_no_memory; } jfes_fill_token(token, jfes_string, start + 1, parser->pos); return jfes_success; } else if (c == '\\' && parser->pos + 1 < length) { parser->pos++; switch (json[parser->pos]) { case '\"': case '/': case '\\': case 'b': case 'f': case 'r': case 'n': case 't': break; case 'u': parser->pos++; for (jfes_size_t i = 0; i < 4 && parser->pos < length && json[parser->pos] != '\0'; i++, parser->pos++) { char symbol = json[parser->pos]; if ((symbol < (int)'0' || symbol > (int)'9') && (symbol < (int)'A' || symbol > (int)'F') && (symbol < (int)'a' || symbol > (int)'f')) { parser->pos = start; return jfes_invalid_input; } } parser->pos--; break; default: parser->pos = start; return jfes_invalid_input; } } parser->pos++; } parser->pos = start; return jfes_error_part; } int jfes_status_is_good(jfes_status_t status) { return status == jfes_success; } int jfes_status_is_bad(jfes_status_t status) { return !jfes_status_is_good(status); } jfes_status_t jfes_init_parser(jfes_parser_t *parser, jfes_config_t *config) { if (!parser || !config) { return jfes_invalid_arguments; } parser->config = config; return jfes_reset_parser(parser); } jfes_status_t jfes_reset_parser(jfes_parser_t *parser) { if (!parser) { return jfes_invalid_arguments; } parser->pos = 0; parser->next_token = 0; parser->superior_token = -1; return jfes_success; } jfes_status_t jfes_parse_tokens(jfes_parser_t *parser, const char *json, jfes_size_t length, jfes_token_t *tokens, jfes_size_t *max_tokens_count) { if (!parser || !json || length == 0 || !tokens || !max_tokens_count || *max_tokens_count == 0) { return jfes_invalid_arguments; } jfes_reset_parser(parser); jfes_token_t *token = JFES_NULL; jfes_size_t count = parser->next_token; while (parser->pos < length && json[parser->pos] != '\0') { char c = json[parser->pos]; switch (c) { case '{': case '[': { count++; token = jfes_allocate_token(parser, tokens, *max_tokens_count); if (!token) { return jfes_no_memory; } if (parser->superior_token != -1) { tokens[parser->superior_token].size++; } token->type = (c == '{' ? jfes_object : jfes_array); token->start = parser->pos; parser->superior_token = parser->next_token - 1; } break; case '}': case ']': { jfes_token_type_t type = (c == '}' ? jfes_object : jfes_array); int i = 0; for (i = (int)parser->next_token - 1; i >= 0; i--) { token = &tokens[i]; if (token->start != -1 && token->end == -1) { parser->superior_token = -1; token->end = parser->pos + 1; break; } } if (i == -1) { return jfes_invalid_input; } while (i >= 0) { token = &tokens[i]; if (token->start != -1 && token->end == -1) { parser->superior_token = i; break; } i--; } } break; case '\"': { jfes_status_t status = jfes_parse_string(parser, json, length, tokens, *max_tokens_count); if (jfes_status_is_bad(status)) { return status; } count++; if (parser->superior_token != -1 && tokens != JFES_NULL) { tokens[parser->superior_token].size++; } } break; case '\t': case '\r': case '\n': case ' ': break; case ':': parser->superior_token = parser->next_token - 1; break; case ',': { if (parser->superior_token != -1 && tokens[parser->superior_token].type != jfes_array && tokens[parser->superior_token].type != jfes_object) { for (int i = parser->next_token - 1; i >= 0; i--) { if (tokens[i].type == jfes_array || tokens[i].type == jfes_object) { if (tokens[i].start != -1 && tokens[i].end == -1) { parser->superior_token = i; break; } } } } } break; #ifdef JFES_STRICT case '-': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 't': case 'f': case 'n': if (parser->superior_token != -1) { jfes_token_t *token = &tokens[parser->superior_token]; if (token->type == jfes_object || (token->type == jfes_string && token->size != 0)) { return jfes_invalid_input; } } #else default: #endif { jfes_status_t status = jfes_parse_primitive(parser, json, length, tokens, *max_tokens_count); if (jfes_status_is_bad(status)) { return status; } count++; if (parser->superior_token != -1) { tokens[parser->superior_token].size++; } } break; #ifdef JFES_STRICT default: return jfes_invalid_input; #endif } parser->pos++; } for (int i = (int)parser->next_token - 1; i >= 0; i--) { if (tokens[i].start != -1 && tokens[i].end == -1) { return jfes_error_part; } } *max_tokens_count = count; return jfes_success; } /** Creates jfes value node from tokens sequence. \param[in] tokens_data Pointer to the jfes_tokens_data_t object. \param[out] value Pointer to the value to create node. \return jfes_success if everything is OK. */ jfes_status_t jfes_create_node(jfes_tokens_data_t *tokens_data, jfes_value_t *value) { if (!tokens_data || !value) { return jfes_invalid_arguments; } if (tokens_data->current_token >= tokens_data->tokens_count) { return jfes_invalid_arguments; } jfes_malloc_t jfes_malloc = tokens_data->config->jfes_malloc; jfes_free_t jfes_free = tokens_data->config->jfes_free; jfes_token_t *token = &tokens_data->tokens[tokens_data->current_token]; tokens_data->current_token++; value->type = (jfes_value_type_t)token->type; switch (token->type) { case jfes_null: break; case jfes_boolean: value->data.bool_val = jfes_string_to_boolean(tokens_data->json_data + token->start, token->end - token->start); break; case jfes_integer: value->data.int_val = jfes_string_to_integer(tokens_data->json_data + token->start, token->end - token->start); break; case jfes_double: value->data.double_val = jfes_string_to_double(tokens_data->json_data + token->start, token->end - token->start); break; case jfes_string: jfes_create_string(tokens_data->config, &value->data.string_val, tokens_data->json_data + token->start, token->end - token->start); break; case jfes_array: value->data.array_val = jfes_malloc(sizeof(jfes_array_t)); if (token->size > 0) { value->data.array_val->count = token->size; value->data.array_val->items = jfes_malloc(token->size * sizeof(jfes_value_t*)); jfes_status_t status = jfes_success; for (jfes_size_t i = 0; i < token->size; i++) { jfes_value_t *item = jfes_malloc(sizeof(jfes_value_t)); value->data.array_val->items[i] = item; status = jfes_create_node(tokens_data, item); if (jfes_status_is_bad(status)) { value->data.array_val->count = i + 1; jfes_free_value(tokens_data->config, value); return status; } } } break; case jfes_object: value->data.object_val = jfes_malloc(sizeof(jfes_object_t)); if (token->size > 0) { value->data.object_val->count = token->size; value->data.object_val->items = jfes_malloc(token->size * sizeof(jfes_object_map_t*)); jfes_status_t status = jfes_success; for (jfes_size_t i = 0; i < token->size; i++) { jfes_object_map_t *item = jfes_malloc(sizeof(jfes_object_map_t)); value->data.object_val->items[i] = item; jfes_token_t *key_token = &tokens_data->tokens[tokens_data->current_token++]; jfes_size_t key_length = key_token->end - key_token->start; jfes_create_string(tokens_data->config, &item->key, tokens_data->json_data + key_token->start, key_length); item->value = jfes_malloc(sizeof(jfes_value_t)); status = jfes_create_node(tokens_data, item->value); if (jfes_status_is_bad(status)) { value->data.object_val->count = i + 1; jfes_free_value(tokens_data->config, value); return status; } } } break; default: return jfes_unknown_type; } return jfes_success; } jfes_status_t jfes_parse_to_value(jfes_config_t *config, const char *json, jfes_size_t length, jfes_value_t *value) { if (!config || !json || length == 0 || !value) { return jfes_invalid_arguments; } jfes_parser_t parser; jfes_status_t status = jfes_init_parser(&parser, config); if (jfes_status_is_bad(status)) { return status; } jfes_size_t tokens_count = 1024; jfes_token_t *tokens = JFES_NULL; status = jfes_no_memory; while (status == jfes_no_memory && tokens_count <= JFES_MAX_TOKENS_COUNT) { jfes_reset_parser(&parser); tokens = parser.config->jfes_malloc(tokens_count * sizeof(jfes_token_t)); long current_tokens_count = tokens_count; status = jfes_parse_tokens(&parser, json, length, tokens, &current_tokens_count); if (jfes_status_is_good(status)) { tokens_count = current_tokens_count; break; } tokens_count *= 2; parser.config->jfes_free(tokens); } if (jfes_status_is_bad(status)) { return status; } jfes_tokens_data_t tokens_data = { config, json, length, tokens, tokens_count, 0 }; status = jfes_create_node(&tokens_data, value); parser.config->jfes_free(tokens); return jfes_success; } jfes_status_t jfes_free_value(jfes_config_t *config, jfes_value_t *value) { if (!config || !value) { return jfes_invalid_arguments; } if (value->type == jfes_array) { if (value->data.array_val->count > 0) { for (jfes_size_t i = 0; i < value->data.array_val->count; i++) { jfes_value_t *item = value->data.array_val->items[i]; jfes_free_value(config, item); config->jfes_free(item); } config->jfes_free(value->data.array_val->items); } config->jfes_free(value->data.array_val); } else if (value->type == jfes_object) { if (value->data.object_val->count > 0) { for (jfes_size_t i = 0; i < value->data.object_val->count; i++) { jfes_object_map_t *object_map = value->data.object_val->items[i]; config->jfes_free(object_map->key.data); jfes_free_value(config, object_map->value); config->jfes_free(object_map->value); config->jfes_free(object_map); } config->jfes_free(value->data.object_val->items); } config->jfes_free(value->data.object_val); } else if (value->type == jfes_string) { if (value->data.string_val.size > 0) { config->jfes_free(value->data.string_val.data); } } return jfes_success; } jfes_value_t *jfes_create_null_value(jfes_config_t *config) { if (!config) { return JFES_NULL; } jfes_value_t *result = (jfes_value_t*)config->jfes_malloc(sizeof(jfes_value_t)); result->type = jfes_null; return result; } jfes_value_t *jfes_create_boolean_value(jfes_config_t *config, int value) { if (!config) { return JFES_NULL; } jfes_value_t *result = (jfes_value_t*)config->jfes_malloc(sizeof(jfes_value_t)); result->type = jfes_boolean; result->data.bool_val = value; return result; } jfes_value_t *jfes_create_integer_value(jfes_config_t *config, int value) { if (!config) { return JFES_NULL; } jfes_value_t *result = (jfes_value_t*)config->jfes_malloc(sizeof(jfes_value_t)); result->type = jfes_integer; result->data.int_val = value; return result; } jfes_value_t *jfes_create_double_value(jfes_config_t *config, double value) { if (!config) { return JFES_NULL; } jfes_value_t *result = (jfes_value_t*)config->jfes_malloc(sizeof(jfes_value_t)); result->type = jfes_double; result->data.double_val = value; return result; } jfes_value_t *jfes_create_string_value(jfes_config_t *config, const char *value, jfes_size_t length) { if (!config || !value) { return JFES_NULL; } if (length == 0) { length = jfes_strlen(value); } jfes_value_t *result = (jfes_value_t*)config->jfes_malloc(sizeof(jfes_value_t)); result->type = jfes_string; jfes_status_t status = jfes_create_string(config, &result->data.string_val, value, length); if (jfes_status_is_bad(status)) { config->jfes_free(result); return JFES_NULL; } return result; } jfes_value_t *jfes_create_array_value(jfes_config_t *config) { if (!config) { return JFES_NULL; } jfes_value_t *result = (jfes_value_t*)config->jfes_malloc(sizeof(jfes_value_t)); result->type = jfes_array; result->data.array_val = (jfes_array_t*)config->jfes_malloc(sizeof(jfes_array_t)); result->data.array_val->count = 0; result->data.array_val->items = JFES_NULL; return result; } jfes_value_t *jfes_create_object_value(jfes_config_t *config) { if (!config) { return JFES_NULL; } jfes_value_t *result = (jfes_value_t*)config->jfes_malloc(sizeof(jfes_value_t)); result->type = jfes_object; result->data.object_val = (jfes_object_t*)config->jfes_malloc(sizeof(jfes_object_t)); result->data.object_val->count = 0; result->data.object_val->items = JFES_NULL; return result; } jfes_value_t *jfes_get_child(jfes_value_t *value, const char *key, jfes_size_t key_length) { jfes_object_map_t *mapped_item = jfes_get_mapped_child(value, key, key_length); if (mapped_item) { return mapped_item->value; } return JFES_NULL; } jfes_object_map_t *jfes_get_mapped_child(jfes_value_t *value, const char *key, jfes_size_t key_length) { if (!value || !key || value->type != jfes_object) { return JFES_NULL; } if (key_length == 0) { key_length = jfes_strlen(key); } for (jfes_size_t i = 0; i < value->data.object_val->count; i++) { jfes_object_map_t *item = value->data.object_val->items[i]; if ((item->key.size - 1) != key_length || jfes_memcmp(item->key.data, key, key_length) != 0) { continue; } return item; } return JFES_NULL; } jfes_status_t jfes_place_to_array(jfes_config_t *config, jfes_value_t *value, jfes_value_t *item) { if (!config || !value || !item || value->type != jfes_array) { return jfes_invalid_arguments; } return jfes_place_to_array_at(config, value, item, value->data.array_val->count); } jfes_status_t jfes_place_to_array_at(jfes_config_t *config, jfes_value_t *value, jfes_value_t *item, jfes_size_t place_at) { if (!config || !value || !item || value->type != jfes_array) { return jfes_invalid_arguments; } if (place_at > value->data.array_val->count) { place_at = value->data.array_val->count; } jfes_value_t **items_array = config->jfes_malloc((value->data.array_val->count + 1) * sizeof(jfes_value_t*)); jfes_size_t offset = 0; for (jfes_size_t i = 0; i < value->data.array_val->count; i++) { if (i == place_at) { offset = 1; } items_array[i + offset] = value->data.array_val->items[i]; } items_array[place_at] = item; value->data.array_val->count++; config->jfes_free(value->data.array_val->items); value->data.array_val->items = items_array; return jfes_success; } jfes_status_t jfes_remove_from_array(jfes_config_t *config, jfes_value_t *value, jfes_size_t index) { if (!config || !value || value->type != jfes_array) { return jfes_invalid_arguments; } if (index >= value->data.array_val->count) { return jfes_not_found; } jfes_value_t *item = value->data.array_val->items[index]; jfes_free_value(config, item); config->jfes_free(item); for (jfes_size_t i = index; i < value->data.array_val->count - 1; i++) { value->data.array_val->items[i] = value->data.array_val->items[i + 1]; } value->data.array_val->count--; return jfes_success; } jfes_status_t jfes_set_object_property(jfes_config_t *config, jfes_value_t *value, jfes_value_t *item, const char *key, jfes_size_t key_length) { if (!config || !value || !item || !key || value->type != jfes_object) { return jfes_invalid_arguments; } if (key_length == 0) { key_length = jfes_strlen(key); } jfes_object_map_t *object_map = jfes_get_mapped_child(value, key, key_length); if (object_map) { jfes_free_value(config, object_map->value); config->jfes_free(object_map->value); } else { jfes_object_map_t **items_map = config->jfes_malloc((value->data.object_val->count + 1) * sizeof(jfes_object_map_t*)); for (jfes_size_t i = 0; i < value->data.object_val->count; i++) { items_map[i] = value->data.object_val->items[i]; } items_map[value->data.object_val->count] = config->jfes_malloc(sizeof(jfes_object_map_t)); object_map = items_map[value->data.object_val->count]; jfes_status_t status = jfes_create_string(config, &object_map->key, key, key_length); if (jfes_status_is_bad(status)) { config->jfes_free(items_map); return status; } config->jfes_free(value->data.object_val->items); value->data.object_val->items = items_map; value->data.object_val->count++; } object_map->value = item; return jfes_success; } jfes_status_t jfes_remove_object_property(jfes_config_t *config, jfes_value_t *value, const char *key, jfes_size_t key_length) { if (!config || !value || value->type != jfes_object || !key) { return jfes_invalid_arguments; } if (key_length == 0) { key_length = jfes_strlen(key); } jfes_object_map_t *mapped_item = jfes_get_mapped_child(value, key, key_length); if (!mapped_item) { return jfes_not_found; } jfes_free_value(config, mapped_item->value); config->jfes_free(mapped_item->value); jfes_free_string(config, &mapped_item->key); jfes_size_t i = 0; for (i = 0; i < value->data.object_val->count; i++) { jfes_object_map_t *item = value->data.object_val->items[i]; if (item == mapped_item) { config->jfes_free(item); mapped_item = JFES_NULL; break; } } /* We found item to remove and set it to JFES_NULL. Next we need to shift other items. */ if (!mapped_item) { for (; i < value->data.object_val->count - 1; i++) { value->data.object_val->items[i] = value->data.object_val->items[i + 1]; } } value->data.object_val->count--; return jfes_success; } /** Dumps JFES value to memory. \param[in] value JFES value to dump. \param[out] data Allocated memory to store. \param[in, out] max_size Maximal size of data. Will store data length. \param[in] beautiful Beautiful JSON. \param[in] indent Indent. Works only when beautiful is true. \param[in] indent_string String to indent JSON. \return jfes_success if everything is OK. */ jfes_status_t jfes_value_to_stream_helper(jfes_value_t *value, jfes_stringstream_t *stream, int beautiful, jfes_size_t indent, const char *indent_string); /** Dumps JFES array value to memory. \param[in] value JFES value to dump. \param[out] data Allocated memory to store. \param[in, out] max_size Maximal size of data. Will store data length. \param[in] beautiful Beautiful JSON. \param[in] indent Indent. Works only when beautiful is true. \param[in] indent_string String to indent JSON. \return jfes_success if everything is OK. */ jfes_status_t jfes_array_value_to_stream_helper(jfes_value_t *value, jfes_stringstream_t *stream, int beautiful, jfes_size_t indent, const char *indent_string) { if (!value || !stream || value->type != jfes_array) { return jfes_invalid_arguments; } int with_indent = 1; jfes_add_to_stringstream(stream, "[", 0); if (beautiful) { if (value->data.array_val->count > 0 && (value->data.array_val->items[0]->type == jfes_object || value->data.array_val->items[0]->type == jfes_array)) { jfes_add_to_stringstream(stream, "\n", 0); } else { with_indent = 0; jfes_add_to_stringstream(stream, " ", 0); } } for (jfes_size_t i = 0; i < value->data.array_val->count; i++) { jfes_value_t *item = value->data.array_val->items[i]; if (beautiful && with_indent) { for (jfes_size_t i = 0; i < indent + 1; i++) { jfes_add_to_stringstream(stream, (char*)indent_string, 0); } } jfes_status_t status = jfes_value_to_stream_helper(item, stream, beautiful, indent + 1, indent_string); if (jfes_status_is_bad(status)) { return status; } if (i < value->data.array_val->count - 1) { jfes_add_to_stringstream(stream, ",", 0); } if (beautiful) { if ((i < value->data.array_val->count - 1 && (value->data.array_val->items[i + 1]->type == jfes_array || value->data.array_val->items[i + 1]->type == jfes_object)) || (i == value->data.array_val->count - 1 && with_indent) || (value->data.array_val->items[i]->type == jfes_array || value->data.array_val->items[i]->type == jfes_object)) { jfes_add_to_stringstream(stream, "\n", 0); with_indent = 1; } else { jfes_add_to_stringstream(stream, " ", 0); with_indent = 0; } } } if (beautiful && with_indent) { for (jfes_size_t i = 0; i < indent; i++) { jfes_add_to_stringstream(stream, (char*)indent_string, 0); } } return jfes_add_to_stringstream(stream, "]", 0); } /** Dumps JFES object value to memory. \param[in] value JFES value to dump. \param[out] data Allocated memory to store. \param[in, out] max_size Maximal size of data. Will store data length. \param[in] beautiful Beautiful JSON. \param[in] indent Indent. Works only when beautiful is true. \param[in] indent_string String to indent JSON. \return jfes_success if everything is OK. */ jfes_status_t jfes_object_value_to_stream_helper(jfes_value_t *value, jfes_stringstream_t *stream, int beautiful, jfes_size_t indent, const char *indent_string) { if (!value || !stream || value->type != jfes_object) { return jfes_invalid_arguments; } jfes_add_to_stringstream(stream, "{", 0); if (beautiful) { jfes_add_to_stringstream(stream, "\n", 0); } for (jfes_size_t i = 0; i < value->data.array_val->count; i++) { jfes_object_map_t *object_map = value->data.object_val->items[i]; if (beautiful) { for (jfes_size_t i = 0; i < indent + 1; i++) { jfes_add_to_stringstream(stream, (char*)indent_string, 0); } } jfes_add_to_stringstream(stream, "\"", 0); jfes_add_to_stringstream(stream, object_map->key.data, object_map->key.size - 1); jfes_add_to_stringstream(stream, "\":", 0); if (beautiful) { jfes_add_to_stringstream(stream, " ", 0); } jfes_status_t status = jfes_value_to_stream_helper(object_map->value, stream, beautiful, indent + 1, indent_string); if (jfes_status_is_bad(status)) { return status; } if (i < value->data.array_val->count - 1) { jfes_add_to_stringstream(stream, ",", 0); } if (beautiful) { jfes_add_to_stringstream(stream, "\n", 0); } } if (beautiful) { for (jfes_size_t i = 0; i < indent; i++) { jfes_add_to_stringstream(stream, (char*)indent_string, 0); } } return jfes_add_to_stringstream(stream, "}", 0); } jfes_status_t jfes_value_to_stream_helper(jfes_value_t *value, jfes_stringstream_t *stream, int beautiful, jfes_size_t indent, const char *indent_string) { if (!value || !stream) { return jfes_invalid_arguments; } switch (value->type) { case jfes_null: return jfes_add_to_stringstream(stream, "null", 0); case jfes_boolean: return jfes_add_to_stringstream(stream, jfes_boolean_to_string(value->data.bool_val), 0); case jfes_integer: return jfes_add_to_stringstream(stream, jfes_integer_to_string(value->data.int_val), 0); case jfes_double: return jfes_add_to_stringstream(stream, jfes_double_to_string(value->data.double_val), 0); case jfes_string: jfes_add_to_stringstream(stream, "\"", 0); jfes_add_to_stringstream(stream, value->data.string_val.data, value->data.string_val.size - 1); return jfes_add_to_stringstream(stream, "\"", 0); case jfes_array: return jfes_array_value_to_stream_helper(value, stream, beautiful, indent, indent_string); case jfes_object: return jfes_object_value_to_stream_helper(value, stream, beautiful, indent, indent_string); default: break; } return jfes_success; } /** Dumps JFES value to memory stream. \param[in] value JFES value to dump. \param[out] data Allocated memory to store. \param[in, out] max_size Maximal size of data. Will store data length. \param[in] beautiful Beautiful JSON. \return jfes_success if everything is OK. */ jfes_status_t jfes_value_to_stream(jfes_value_t *value, jfes_stringstream_t *stream, int beautiful) { return jfes_value_to_stream_helper(value, stream, beautiful, 0, " "); } jfes_status_t jfes_value_to_string(jfes_value_t *value, char *data, jfes_size_t *max_size, int beautiful) { if (!data || !max_size || *max_size == 0) { return jfes_invalid_arguments; } jfes_stringstream_t stream; jfes_status_t status = jfes_initialize_stringstream(&stream, data, *max_size); if (jfes_status_is_bad(status)) { return status; } status = jfes_value_to_stream(value, &stream, beautiful); if (jfes_status_is_bad(status)) { return status; } *max_size = stream.current_index; return jfes_success; }<file_sep>/jfes.h /** \file jfes.h \author <NAME> (http://github.com/NeonMercury) \date October, 2015 \brief Json For Embedded Systems library headers. */ #ifndef JFES_H_INCLUDE_GUARD #define JFES_H_INCLUDE_GUARD /** Strict JSON mode. **/ //#define JFES_STRICT /** Maximal tokens count */ #define JFES_MAX_TOKENS_COUNT 8192 /** NULL define for the jfes library. */ #ifndef JFES_NULL #define JFES_NULL ((void*)0) #endif /** size_t type for the jfes library. */ typedef unsigned int jfes_size_t; /** JFES return statuses. */ typedef enum jfes_status { jfes_unknown = 0x00, /**< Unknown status */ jfes_success = 0x01, /**< Last operation finished sucessfully. */ jfes_invalid_arguments = 0x02, /**< Invalid arguments were passed to the function. */ jfes_no_memory = 0x03, /**< Not enough tokens were provided. */ jfes_invalid_input = 0x04, /**< Invalid character in JSON string. */ jfes_error_part = 0x05, /**< The string is not a full JSON packet. More bytes expected. */ jfes_unknown_type = 0x06, /**< Unknown token type. */ jfes_not_found = 0x07, /**< Something was not found. */ } jfes_status_t; /** Memory allocator function type. */ typedef void *(__cdecl *jfes_malloc_t)(jfes_size_t); /** Memory deallocator function type. */ typedef void (__cdecl *jfes_free_t)(void*); /** JFES string type. */ typedef struct jfes_string { char *data; /**< String bytes. */ jfes_size_t size; /**< Allocated bytes count. */ } jfes_string_t; /** JFES token types */ typedef enum jfes_token_type { jfes_undefined = 0x00, /**< Undefined token type. */ jfes_null = 0x01, /**< Null token type. */ jfes_boolean = 0x02, /**< Boolean token type. */ jfes_integer = 0x03, /**< Integer token type. */ jfes_double = 0x04, /**< Double token type. */ jfes_string = 0x05, /**< String token type. */ jfes_array = 0x06, /**< Array token type. */ jfes_object = 0x07, /**< Object token type. */ } jfes_token_type_t; /** Json value type is the same as token type. */ typedef jfes_token_type_t jfes_value_type_t; /** JFES token structure. */ typedef struct jfes_token { jfes_token_type_t type; /**< Token type. */ int start; /**< Token start position. */ int end; /**< Token end position. */ jfes_size_t size; /**< Token children count. */ } jfes_token_t; /** JFES config structure. */ typedef struct jfes_config { jfes_malloc_t jfes_malloc; /**< Memory allocation function. */ jfes_free_t jfes_free; /**< Memory deallocation function. */ } jfes_config_t; /** JFES tokens data structure. */ typedef struct jfes_tokens_data { jfes_config_t *config; /**< JFES configuration. */ const char *json_data; /**< JSON string. */ jfes_size_t json_data_length; /**< JSON string length. */ jfes_token_t *tokens; /**< String parsing result in tokens. */ jfes_size_t tokens_count; /**< Tokens count. */ jfes_size_t current_token; /**< Index of current token. */ } jfes_tokens_data_t; /** JFES parser structure. */ typedef struct jfes_parser { jfes_size_t pos; /**< Current offset in json string. */ jfes_size_t next_token; /**< Next token to allocate. */ int superior_token; /**< Superior token node. */ jfes_config_t *config; /**< Pointer to jfes config. */ } jfes_parser_t; /** JSON value structure. */ typedef struct jfes_value jfes_value_t; /** JFES `key -> value` mapping structure. */ typedef struct jfes_object_map { jfes_string_t key; /**< Object key. */ jfes_value_t *value; /**< Oject value. */ } jfes_object_map_t; /** JSON array structure. */ typedef struct jfes_array { jfes_value_t **items; /**< JSON items in array. */ jfes_size_t count; /**< Items count in array. */ } jfes_array_t; /** JSON object structure. */ typedef struct jfes_object { jfes_object_map_t **items; /**< JSON items in object. */ jfes_size_t count; /**< Items count in object. */ } jfes_object_t; /** JFES value data union. */ typedef union jfes_value_data { int bool_val; /**< Boolean JSON value. */ int int_val; /**< Integer JSON value. */ double double_val; /**< Double JSON value. */ jfes_string_t string_val; /**< String JSON value. */ jfes_array_t *array_val; /**< Array JSON value. */ jfes_object_t *object_val; /**< Object JSON value. */ } jfes_value_data_t; /** JSON value structure. */ struct jfes_value { jfes_value_type_t type; /**< JSON value type. */ jfes_value_data_t data; /**< Value data. */ }; /** JFES status analizer function. \param[in] status Status variable. \return Zero, if status not equals jfes_success. Otherwise anything else. */ int jfes_status_is_good(jfes_status_t status); /** JFES status analizer function. \param[in] status Status variable. \return Zero, if status equals jfes_success. Otherwise anything else. */ int jfes_status_is_bad(jfes_status_t status); /** JFES parser initialization. \param[out] parser Pointer to the jfes_parser_t object. \param[in] config JFES configuration. \return jfes_success if everything is OK. */ jfes_status_t jfes_init_parser(jfes_parser_t *parser, jfes_config_t *config); /** Resets all parser fields, except memory allocation functions. \param[out] parser Pointer to the jfes_parser_t object. \return jfes_success if everything is OK. */ jfes_status_t jfes_reset_parser(jfes_parser_t *parser); /** Run JSON parser. It parses a JSON data string into and array of tokens, each describing a single JSON object. \param[in] parser Pointer to the jfes_parser_t object. \param[in] json JSON data string. \param[in] length JSON data length. \param[out] tokens Tokens array to fill. \param[in, out] max_tokens_count Maximal count of tokens in tokens array. Will contain tokens count. \return jfes_success if everything is OK. */ jfes_status_t jfes_parse_tokens(jfes_parser_t *parser, const char *json, jfes_size_t length, jfes_token_t *tokens, jfes_size_t *max_tokens_count); /** Run JSON parser and fills jfes_value_t object. \param[in] config JFES configuration. \param[in] json JSON data string. \param[in] length JSON data length. \param[out] value Output value; \return jfes_success if everything is OK. */ jfes_status_t jfes_parse_to_value(jfes_config_t *config, const char *json, jfes_size_t length, jfes_value_t *value); /** Free all resources, captured by object. \param[in] config JFES configuration. \param[in,out] value Object to free. \return jfes_success if everything is OK. */ jfes_status_t jfes_free_value(jfes_config_t *config, jfes_value_t *value); /** Allocates new null value. \param[in] config JFES configuration. \return Allocated JFES value or JFES_NULL, if something went wrong. */ jfes_value_t *jfes_create_null_value(jfes_config_t *config); /** Allocates new boolean value. \param[in] config JFES configuration. \param[in] value Value to pass it to the object. \return Allocated JFES value or JFES_NULL, if something went wrong. */ jfes_value_t *jfes_create_boolean_value(jfes_config_t *config, int value); /** Allocates new integer value. \param[in] config JFES configuration. \param[in] value Value to pass it to the object. \return Allocated JFES value or JFES_NULL, if something went wrong. */ jfes_value_t *jfes_create_integer_value(jfes_config_t *config, int value); /** Allocates new double value. \param[in] config JFES configuration. \param[in] value Value to pass it to the object. \return Allocated JFES value or JFES_NULL, if something went wrong. */ jfes_value_t *jfes_create_double_value(jfes_config_t *config, double value); /** Allocates new string value. \param[in] config JFES configuration. \param[in] value Value to pass it to the object. \param[in] length Optional. String length. You can pass 0, if string is zero-terminated. \return Allocated JFES value or JFES_NULL, if something went wrong. */ jfes_value_t *jfes_create_string_value(jfes_config_t *config, const char *value, jfes_size_t length); /** Allocates new array value. \param[in] config JFES configuration. \return Allocated JFES value or JFES_NULL, if something went wrong. */ jfes_value_t *jfes_create_array_value(jfes_config_t *config); /** Allocates new object value. \param[in] config JFES configuration. \return Allocated JFES value or JFES_NULL, if something went wrong. */ jfes_value_t *jfes_create_object_value(jfes_config_t *config); /** Finds child value, if given parent value is object. \param[in] value Parent object value. \param[in] key Child key. \param[in] key_length Optional. Child key length. You can pass 0, if key string is zero-terminated. \return Child value by given key or JFES_NULL, if nothing was found. */ jfes_value_t *jfes_get_child(jfes_value_t *value, const char *key, jfes_size_t key_length); /** Finds child value, if given parent value is object. \param[in] value Parent object value. \param[in] key Child key. \param[in] key_length Optional. Child key length. You can pass 0, if key string is zero-terminated. \return Mapped child value with given key or JFES_NULL, if nothing was found. */ jfes_object_map_t *jfes_get_mapped_child(jfes_value_t *value, const char *key, jfes_size_t key_length); /** Adds new item to the given array value. \param[in] config JFES configuration. \param[in] value Array value. \param[in] item Item to add. Must be allocated on heap. \return jfes_success if everything is OK. */ jfes_status_t jfes_place_to_array(jfes_config_t *config, jfes_value_t *value, jfes_value_t *item); /** Adds new item to the given array value on the given place. \param[in] config JFES configuration. \param[in] value Array value. \param[in] item Item to add. Must be allocated on heap. \param[in] place_at Index to place. \return jfes_success if everything is OK. */ jfes_status_t jfes_place_to_array_at(jfes_config_t *config, jfes_value_t *value, jfes_value_t *item, jfes_size_t place_at); /** Removes an item with fiven index from array. \param[in] config JFES configuration. \param[in] value Array value. \param[in] index Index to remove. \return jfes_success if everything is OK. */ jfes_status_t jfes_remove_from_array(jfes_config_t *config, jfes_value_t *value, jfes_size_t index); /** Adds new item to the given object. \param[in] config JFES configuration. \param[in] value Array value. \param[in] item Item to add. Must be allocated on heap. \param[in] key Child key. \param[in] key_length Optional. Child key length. You can pass 0, if key string is zero-terminated. \return jfes_success if everything is OK. */ jfes_status_t jfes_set_object_property(jfes_config_t *config, jfes_value_t *value, jfes_value_t *item, const char *key, jfes_size_t key_length); /** Removes object child with the given key. \param[in] config JFES configuration. \param[in] value Array value. \param[in] key Child key. \param[in] key_length Optional. Child key length. You can pass 0, if key string is zero-terminated. \return jfes_success if everything is OK. */ jfes_status_t jfes_remove_object_property(jfes_config_t *config, jfes_value_t *value, const char *key, jfes_size_t key_length); /** Dumps JFES value to memory. \param[in] value JFES value to dump. \param[out] data Allocated memory to store. \param[in, out] max_size Maximal size of data. Will store data length. \param[in] beautiful Beautiful JSON. \return jfes_success if everything is OK. */ jfes_status_t jfes_value_to_string(jfes_value_t *value, char *data, jfes_size_t *max_size, int beautiful); #endif
b7823b7da8fb4ed3aedde13c15c33f61679a9f86
[ "Markdown", "C" ]
5
C
sav6622/jfes
5571f911316d1bc827c7f16d0764b0ab2bc2c9ab
60ae5ad6d327d50145a27555eabf9d2e30fd694f
refs/heads/master
<file_sep>const Validator = require("validator"); const isEmpty = require("./isEmpty"); module.exports = function validateTodoInput(data) { let errors = {}; data.name = !isEmpty(data.name) ? data.name : ""; data.description = !isEmpty(data.description) ? data.description : ""; data.creator = !isEmpty(data.creator) ? data.creator : ""; data.duration = !isEmpty(data.duration) ? data.duration : ""; if (Validator.isEmpty(data.name)) { errors.name = "Name field is required."; } if (Validator.isEmpty(data.description)) { errors.description = "Description field is required"; } if (Validator.isEmpty(data.creator)) { errors.description = "Creator field is required"; } if (Validator.isEmpty(data.duration)) { errors.description = "Duration field is required"; } return { errors: errors, isValid: isEmpty(errors), }; };
3dee00d43c4073dd46dcf4fc6a4b107ffbebff38
[ "JavaScript" ]
1
JavaScript
UJKEM/Todo-Hackathon
868685335420d8e50fe9f1a2a1e90a28220dc498
c6cf28379a1c000dfa88fc183bd2f04bcee8f01d
refs/heads/master
<repo_name>kannanGc/Stock-trading-app<file_sep>/backbone/assets/js/script_backBone.js $(function(){ var app = app || {Utils: {}}; // Defining routers var appRouter = Backbone.Router.extend({ routes: { "": "indexRoute", "fetchRoute": "fetchDetailsRoute", "addRoute": "addDetailsRoute", "updateRoute":"updateDetailsRoute" } }); // Method to return the filtered data app.Utils.filterCollection = function(collection, filterValue) { if (filterValue == "") return collection.models; return collection.filter(function(data) { return _.some(_.values(data.toJSON()), function(value) { if (_.isNumber(value)) value = value.toString(); if (_.isString(value)) { if( value.toLowerCase().indexOf(filterValue.toLowerCase()) != -1){ return true; }else{ return false; } } return false; }); }); } Backbone.Collection.prototype.filterValues = function(filterValues) { return app.Utils.filterCollection(this, filterValues); } // Method to get the filtered data and append the filtered data in the table. var FilterView = Backbone.View.extend({ el: "#container", events: { "keyup #search" : "filter" }, filter: function(e) { $(".stockBody").html(""); stockCollections.model.tempModels = stocks.filterValues($(e.target).val()); if(stockCollections.model.tempModels.length == 0){ $(".addDetailsAnc").show(); searchValue = $("#search").val() $(".inputVal").html(searchValue); $(".addDetailsInput").val(searchValue); }else{ $(".addDetailsAnc").hide(); } stockCollections.renderUpdated(); } }); // updating the stock collection when clicking ADD button and append the updated data in table var addDetailsView = Backbone.View.extend({ el: "#addDetails", events: { 'click #addButton' : 'addDetailsFromForm' }, addDetailsFromForm: function(){ var companyNameAddDetails = $(".addDetailsInput").val(); var currenctPriceAddDetails = $(".addDetailsCurrenctPrice").val(); var purchasepriceAddDetails = $(".addDetailsPurchaseprice").val(); var netProfiltAddDetails = $(".addDetailsNetProfit").val(); var json = {"companyName":companyNameAddDetails ,"currentPrice":currenctPriceAddDetails, "purchasePrice":currenctPriceAddDetails, "netProfit":netProfiltAddDetails}; stockCollections.model.add(json); location.href="#updateRoute"; } }); // Method to render data in table and event binding for DELETE button in the table. var StockView = Backbone.View.extend({ el: ".stockBody", template: _.template($('#stockTemplate').html()), render: function(eventName) { _.each(this.model.models, function(stock){ var stockTemplate = this.template(stock.toJSON()); $(this.el).append(stockTemplate); }, this); $("#preLoader").hide(); return this; }, renderUpdated: function(eventName) { _.each(this.model.tempModels, function(stock){ var stockTemplate = this.template(stock.toJSON()); $(this.el).append(stockTemplate); }, this); return this; }, events: { 'click .deleteAnc' : 'deleteModel' }, deleteModel: function(e){ var textContent = e.target.parentElement.parentElement.children[0].textContent.trim(); stockCollections.model.remove(stockCollections.model.where({companyName: textContent})); $(".stockBody").html(""); stockCollections.render(); } }); app.Router = new appRouter(); // router for index page app.Router.on('route:indexRoute', function() { $("#tableHolder,#addDetails").hide(); $("#landingInfoDiv").show(); }); // router for add details page app.Router.on('route:addDetailsRoute', function() { $("#tableHolder,#landingInfoDiv").hide(); $(".addDetailsPurchaseprice,.addDetailsNetProfit,.addDetailsCurrenctPrice").val(""); $("#addDetails").show(); }); // router for table view page app.Router.on('route:fetchDetailsRoute', function() { $("#tableHolder,#preLoader").show(); $("#landingInfoDiv,#addDetails").hide(); $(".stockBody").html(""); var stock = Backbone.Model.extend(); var StockList = Backbone.Collection.extend({ model: stock, url: 'https://api.myjson.com/bins/e2ltp', }); stocks = new StockList(); stockCollections = new StockView({model: stocks}); stocks.fetch({ success: function(response) { stockCollections.render(); } }); }); // router for updated details page. app.Router.on('route:updateDetailsRoute', function() { $("#tableHolder").show(); $("#addDetails,.addDetailsAnc,#landingInfoDiv").hide(); $("#search").val(""); stockCollections.render(); }); //variable declaration Backbone.history.start(); var filterView = new FilterView(); var addView = new addDetailsView(); var stocks,searchValue; });<file_sep>/README.md # Stock-trading-app test tetst
db2b2c2ede8c6fa985b1f49e43b7f6c31c35e4b3
[ "JavaScript", "Markdown" ]
2
JavaScript
kannanGc/Stock-trading-app
d8148c20ae1bf2914b3ccc511c8ee1b58c657c89
8deddb10cdb7ea9e9677795fba41a2f0a702b04d
refs/heads/master
<repo_name>nevoalm/securenative-java<file_sep>/src/main/java/models/ActionType.java package models; public class ActionType { public enum type { ALLOW, BLOCK, REDIRECT, MFA } } <file_sep>/src/main/java/models/EventOptions.java package models; import java.util.Map; public class EventOptions { private String ip; private String userAgent; private String remoteIP; private User user; private String device; private String cookieName; private String eventType; private Map params; public EventOptions(String ip, String remoteIP, String userAgent, String device, User user, String cookieName, String eventType, Map params) { this.ip = ip; this.remoteIP = remoteIP; this.userAgent = userAgent; this.device = device; this.user = user; this.cookieName = cookieName; this.eventType = eventType; this.params = params; } public EventOptions(String ip, String userAgent,String eventType) { this.ip = ip; this.userAgent = userAgent; this.eventType = eventType; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public String getUserAgent() { return userAgent; } public void setUserAgent(String userAgent) { this.userAgent = userAgent; } public String getRemoteIP() { return remoteIP; } public void setRemoteIP(String remoteIP) { this.remoteIP = remoteIP; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public String getDevice() { return device; } public void setDevice(String device) { this.device = device; } public String getCookieName() { return cookieName; } public void setCookieName(String cookieName) { this.cookieName = cookieName; } public String getEventType() { return eventType; } public void setEventType(String eventType) { this.eventType = eventType; } public Map getParams() { return params; } public void setParams(Map params) { this.params = params; } } <file_sep>/src/main/java/snlogic/VerifyWebHookMiddleware.java package snlogic; import com.google.common.base.Strings; import org.springframework.beans.factory.annotation.Autowired; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.stream.Collectors; public class VerifyWebHookMiddleware implements Filter { @Autowired private ISDK sn; @Autowired private Utils utils; private final String HEADER_KEY = "X-SECURENATIVE"; @Override public void init(FilterConfig filterConfig) { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException { HttpServletRequest req = (HttpServletRequest) servletRequest; HttpServletResponse res = (HttpServletResponse) servletResponse; String payload = req.getReader().lines().collect(Collectors.joining(System.lineSeparator())); if (Strings.isNullOrEmpty(payload)) { res.sendError(500, "empty request"); } try { String digest = "sha1=" + utils.calculateRFC2104HMAC(payload,sn.getApiKey()); String checksum = req.getHeader(HEADER_KEY); if (checksum == null || digest != checksum) { res.sendError(500,"Request body digest did not match "); } } catch (Exception e){ System.out.println("Error"); } } @Override public void destroy() { } } <file_sep>/src/test/java/snlogic/UtilsTest.java package snlogic; import models.ClientFingurePrint; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class UtilsTest { Utils utils; HttpServletRequest request; @Before public void setup() { request = mock(HttpServletRequest.class); utils = new Utils(); } @Test public void getCookieWhenRequestNullExpectNullTest(){ String cookie = utils.getCookie(null, ""); Assert.assertEquals(cookie,null); } @Test public void getCookieWhenCookieNameEmpytExpectDefaultTest(){ Cookie[] cookies = {new Cookie("_sn","value")}; when(request.getCookies()).thenReturn(cookies); String cookie = utils.getCookie(request, ""); Assert.assertEquals(cookie,"value"); } @Test public void parseClientFPWhenJsonValid(){ String validJson = "{\"cid\": \"cid\",\"fp\": \"fp\" }"; ClientFingurePrint clientFingurePrint = utils.parseClientFP(validJson); Assert.assertEquals(clientFingurePrint.getCid(),"cid"); Assert.assertEquals(clientFingurePrint.getFp(),"fp"); } @Test public void parseClientFPWhenInvalidJson(){ String validJson = "{\"cid\": \"cid\",\"fp\": \"fp\", }"; ClientFingurePrint clientFingurePrint = utils.parseClientFP(validJson); Assert.assertEquals(clientFingurePrint,null); } @Test public void remoteIpFromRequestWhenRequestNullExpectEmptyString(){ Assert.assertEquals(utils.remoteIpFromRequest(null),""); } } <file_sep>/src/main/java/snlogic/VerifyRequestMiddleware.java package snlogic; import com.google.common.base.Strings; import models.ActionResult; import models.ActionType; import models.EventOptions; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class VerifyRequestMiddleware implements Filter { private SecureNative sn; private Utils utils; public VerifyRequestMiddleware(SecureNative sn) { this.sn = sn; } @Override public void init(FilterConfig filterConfig){ } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) servletRequest; HttpServletResponse res = (HttpServletResponse) servletResponse; String cookie = utils.getCookie(req, null); if (Strings.isNullOrEmpty(cookie)){ ActionResult response = this.sn.verify(new EventOptions(utils.remoteIpFromRequest(req), req.getHeader("user-agent"), EventTypes.types.get(EventTypes.EventKey.VERIFY)), req); if (ActionType.type.BLOCK == response.getAction()){ res.sendRedirect(String.valueOf(500)); } if (ActionType.type.REDIRECT == response.getAction()){ res.sendRedirect("/error"); } } filterChain.doFilter(req,res); } @Override public void destroy() {} } <file_sep>/README.md # securenative-java SDK + agent for Secure Native paltform Installation Add the dependency to your pom.xml Option Type Optional Default Value Description apiKey string false none SecureNative api key apiUrl string true https://api.securenative.com/v1/collector Default api base address interval number true 1000 Default interval for SDK to try to persist events maxEvents number true 1000 Max in-memory events queue timeout number true 1500 API call timeout in ms autoSend Boolean true true Should api auto send the events Event tracking WebHook Use verifyWebhook middleware to ensure that webhook is comming from SecureNative <file_sep>/src/main/java/snlogic/EventManager.java package snlogic; import models.ActionResult; import models.EventOptions; import models.SnEvent; import javax.servlet.http.HttpServletRequest; public interface EventManager { SnEvent buildEvent(final HttpServletRequest request, final EventOptions options); ActionResult sendSync(SnEvent event, String requestUrl); void sendAsync(SnEvent event,String url); } <file_sep>/src/test/java/snlogic/SnEventManagerTest.java package snlogic; import models.EventOptions; import models.SecureNativeOptions; import models.SnEvent; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class SnEventManagerTest { EventManager snEventManager; HttpServletRequest request; Utils utils; @Before public void setup() { request = mock(HttpServletRequest.class); utils = mock(Utils.class); } @Test(expected = Exception.class) public void buildEventMangerWithNullOptions() throws Exception { snEventManager = new SnEventManager("1234", null); } @Test(expected = Exception.class) public void buildEventMangerWithNullApiKey() throws Exception { snEventManager = new SnEventManager(null, new SecureNativeOptions()); } @Test public void buildEventTest() throws Exception { snEventManager = new SnEventManager("key",new SecureNativeOptions()); when(request.getRemoteAddr()).thenReturn("address"); when(request.getHeader("header")).thenReturn("header"); when(utils.getCookie(any(),anyString())).thenReturn("cookie"); when(request.getCookies()).thenReturn(new Cookie[]{new Cookie("k","v"),new Cookie("_sn","X3NuX3ZhbHVl")}); when(utils.base64decode(anyString())).thenReturn("base"); SnEvent snEvent = snEventManager.buildEvent(request, new EventOptions("ip", "userAgent","eventType")); Assert.assertEquals("eventType", snEvent.getEvent()); } }
5ed2de7f0fdccafceb22afdcc0228ae6801f720c
[ "Markdown", "Java" ]
8
Java
nevoalm/securenative-java
b514602213e229c2321baf47767b36329fa10377
2f8d1dca053eba1effecc7a1457255ef5fce2fc6
refs/heads/master
<file_sep>const express = require('express'); const router = express.Router(); const { check, validationResult } = require('express-validator/check'); const { matchedData, sanitize } = require('express-validator/filter'); // Article model let Article = require('../models/article'); // User model let User = require('../models/user'); // Add route router.get('/add', ensureAuthenticated, (req, res) => { res.render('add_article', { title: 'Add article' }); }); // Add submit POST route router.post('/add', ensureAuthenticated, [ check('title').trim().isLength({min:1}).withMessage('Title required'), check('body').trim().isLength({min:1}).withMessage('Body required') ], (req, res) => { const errors = validationResult(req); if(!errors.isEmpty()) { res.render('add_article', { title: 'Add Article', errors: errors.mapped() }); } else { let article = new Article({ title: req.body.title, author: req.user.id, body: req.body.body }); article.save(err => { if(err) { console.log(err); } else { req.flash('success', 'Article Added'); res.redirect('/'); } }); } }); router.get('/edit/:id', ensureAuthenticated, (req, res) => { Article.findById(req.params.id, (err, article) => { if(err) throw err; if(article.author !== req.user.id) { req.flash('danger', 'Not authorized'); return res.redirect('/'); } res.render('edit_article', { title: 'Edit Article', article: article }) }); }); // Update submit POST route router.post('/edit/:id', ensureAuthenticated, (req, res) => { let article = { title: req.body.title, author: req.user.id, body: req.body.body }; let query = {_id:req.params.id}; Article.update(query, article, err => { if(err) { console.log(err); return; } else { req.flash('success', 'Article Updated'); res.redirect('/'); } }); }); router.delete('/:id', (req, res) => { if(!req.user._id) { res.status(401).end(); } let query = {_id: req.params.id}; Article.findById(req.params.id, (err, article) => { if(err) throw err; if(article.author !== req.user.id) { res.status(401).end(); } else { Article.deleteOne(query, err => { if(err) { console.log(err); } else { res.send('Success'); } }); } }); }); // Get single article router.get('/:id', (req, res) => { Article.findById(req.params.id, (err, article) => { if(err) throw err; User.findById(article.author, (err, user) => { if(err) throw err; res.render('article', { article: article, author: user.name }); }); }); }); // Access control function ensureAuthenticated(req, res, next) { if(req.isAuthenticated()) { return next(); } else { req.flash('danger', 'Please login'); res.redirect('/users/login'); } } module.exports = router;
445c6e455a67981c7f30002ceebbd08d32b6d347
[ "JavaScript" ]
1
JavaScript
dcgab/nodekb
c7b5da516793f37b5ddb5edcd9ba5ecb4208339e
cd3cc1675f350bb32d4d02654cc51aa428769f42
refs/heads/master
<repo_name>Wojtec/test-restapi<file_sep>/src/controllers/user.js const { generateAccessToken } = require('../services/auth'); /** * * USER CONTROLLERS * * */ const clients = [{ id: 1, username: 'test', password: '<PASSWORD>', role: 'user', }, { id: 2, username: 'test2', password: '<PASSWORD>', role: 'admin', }]; // Verify user with clients normal will be data base // eslint-disable-next-line consistent-return const verifyUser = ({ username, password }) => { const user = clients.find((u) => u.username === username && u.password === password); if (user) { // eslint-disable-next-line no-shadow const { password, ...onlyUser } = user; return onlyUser; } }; // login user with verification and function to generate access token const login = (req, res, next) => { try { const data = req.body; const user = verifyUser(data); if (!user) res.status(401).send({ message: 'Username or password is not valid.' }); const accessToken = generateAccessToken(user); res.status(200).send(accessToken); next(); } catch (err) { next(err); } }; module.exports = { verifyUser, login, }; <file_sep>/src/controllers/policies.js const { getPolicies } = require('../actions'); /** * * POLICIES CONTROLLERS * * */ // Get policies with query limit example: /api/v1/policies?limit=10 // eslint-disable-next-line consistent-return const getPoliciesData = async (req, res, next) => { try { const policies = []; const { limit } = req.query; const data = await getPolicies(); const limitData = data.slice(0, limit || 10); limitData.map((p) => { const { clientId, ...withoutClientId } = p; return policies.push(withoutClientId); }); return res.status(200).json(policies); } catch (err) { next(err); } }; // Get policies by Id example:/api/v1/policies/e8fd159b-57c4-4d36-9bd7-a59ca13057bb // eslint-disable-next-line consistent-return const getPoliciesById = async (req, res, next) => { try { const { id } = req.params; const data = await getPolicies(); const findById = data.find((p) => p.id === id); if (!findById) return res.status(404).send({ message: 'Not Found error' }); return res.status(200).json(findById); } catch (err) { next(err); } }; module.exports = { getPoliciesData, getPoliciesById, }; <file_sep>/README.md # Mandatory points * Authentication and authorization. The authentication model must be based on https://tools.ietf.org/html/rfc6750. * Include tests (at least 1 unit test, 1 integration test and one end to end tests). * Using JavaScript ES6. * Deliver the codebase on github or any source control tool. It would be great if we can see incremental steps at the commits history. * Use Latest Node.js LTS version. * DON'T USE A DB. The API REST youyr must to deliver is a middleware, so is very important to propagate the request to the data source INSURANCE API REST and to manage the error handling and the asynchronism. * Configuration of a linter and some specific rules to maintain code coherence style. For example https://github.com/airbnb/javascript/tree/master/packages/eslint-config-airbnb-base. ## Contact If you have any questions about project you can contact with me by email. Email: `<EMAIL>` Name: `Wojtek` ## Installation To get started with test-restApi you need to clone project from git repository. In your terminal: ``` git clone https://github.com/Wojtec/test-restAPI.git ``` ## Run application Open project in your code editor and install all dependencies Make sure that you are in correct path `/test-restAPI#` in your terminal and write : ``` npm install ``` ``` npm start ``` Server should be listening on `http://localhost:3000` To use application you will need some API testing tool for example `Postman` Available on [Postman](https://docs.api.getpostman.com/) ## Tests To run tests make sure that you have Jest and supertest installed in your devDependiency. Start test writing in your terminal: ``` npm test ``` Test includes : 7 unit tests ````csharp Verify User ✓ Unit test for verify user (31 ms) Auth middleware ✓ should populate req.user with token (9 ms) ✓ should return catch error (1 ms) Consuming API ✓ readToken function reading token from file (23 ms) ✓ Should handle a readFile error from readToken (1 ms) ✓ Should handle a refreshToken catch error (1 ms) ✓ Should handle a loginApi catch error (329 ms) ```` 21 integration tests ````csharp Endpoints tests GET /api/v1/login ✓ Should return token (70 ms) ✓ Should return 401 username or password not valid (11 ms) GET /api/v1/policies ✓ Should return all policies 10 by default (438 ms) ✓ Should return 401 Unauthorized error. (3 ms) ✓ Should return 401 Unauthorized error.Token is not valid (2 ms) ✓ Should return policies limited by query string (453 ms) ✓ Should return policies matched to object schema (304 ms) GET /api/v1/policies/:id ✓ Should return policie by id (252 ms) ✓ Should return 401 Unauthorized (9 ms) ✓ Should return 404 Not Found error (249 ms) GET /api/v1/clients ✓ Should return 10 elements by default and status 200 (588 ms) ✓ Should return elements limited by query string (607 ms) ✓ Should return elements by name query string (476 ms) ✓ Should return elements by name and limit query string (475 ms) ✓ Should return 401 unauthorized error (3 ms) GET /api/v1/clients/:id ✓ Should return client's details by id (685 ms) ✓ Should return 401 unauthorized error (11 ms) ✓ Should return 404 not Found error (469 ms) ✓ Should return client's policies (774 ms) ✓ Should return 401 unauthorized error (8 ms) ✓ Should return 404 not Found error (8 ms) ```` I didn't make automation tests because I don't use UI. ## Endpoints #CLIENT_CREDENTIALS For get role "user" username: "test" password: "<PASSWORD>" For get role "admin" username: "test2" password: "<PASSWORD>" #Login Retrieve the auth token. ``` POST /api/v1/login ``` This endpoint will allow for the user login to the application and recive token if veryfication will be valid. ````csharp { "token": "<KEY>", "type": "Bearer", "expiresIn": 1600017164 } ```` In folder `/src/controllers/user.js` you can find middleware to this endpoint. ````csharp const login = (req, res, next) => { try{ // get data from request body const data = req.body; // verify user const user = verifyUser(data); // if user is not verified response 401 with message if(!user) res.status(401).send({message: "Username or password is not valid."}); // if user is verified send user grant to generate token const accessToken = generateAccessToken(user); // response status 200 and sent object with access token res.status(200).send(accessToken); // next to call another function from this endpoint next(); }catch(err){ // if is an error in block try catch error and send to error handler in /src/app.js next(err) } } ```` In folder `/src/services/auth.js` you can find controller and middleware to `Authorization/Authentication`. ````csharp //Generate access token const generateAccessToken = (user) => { //Create expiring time for token const exp = Math.floor(Date.now() / 1000) + (60 * 60); //Create token const token = jwt.sign(user, config.secret,{ algorithm: 'HS256', expiresIn: exp }); //Return a valid Bearer access token for the valid client_credentials provided. return { token, type:"Bearer", expiresIn: exp }; } ```` ````csharp //Verify token access const verifyToken = (req, res, next) => { try{ //Get token from headers const bearerHeader = req.headers['authorization']; //Separate token from Bearer const token = bearerHeader && bearerHeader.split(' ')[1]; //Check if token is true if(!token) return res.status(401).send({message: 'Unauthorized'}); //Verify token jwt.verify(token, config.secret, (err, user) => { //Check if token is valid if(err) return res.status(401).send({message: 'Token is not valid'}); //Set user payload from token req.user = user; //Call next function from endpoint next(); }) }catch(err){ //If is error send to error handler in /src/app.js next(err); } } ```` #Policies Get the list of policies' client paginated and limited to 10 elements by default. ``` Get /api/v1/policies ``` This endpoint will allow for the user recive policies data. ````csharp { "id": "64cceef9-3a01-49ae-a23b-3761b604800b", "amountInsured": "1825.89", "email": "<EMAIL>", "inceptionDate": "2016-06-01T03:33:32Z", "installmentPayment": true } ```` In folder `/src/controllers/policies.js` you can find middleware to this endpoint. ````csharp // Get policies with query limit example: /api/v1/policies?limit=10 const getPoliciesData = async (req, res, next) => { try{ //Array for policies let policies = []; //Destructurise limit from query string const { limit } = req.query; //Consume Api policies route const data = await getPolicies(); //Limit data by query string or by default 10 const limitData = data.slice(0, limit || 10); //Change data content and push to array with policies limitData.map(p => { const { clientId, ...withoutClientId } = p; return policies.push(withoutClientId) }) //Return response with policies data json return res.status(200).json(policies); }catch(err){ //If is error send to handler error what is in /src/app.js next(err); } } ```` #Policies by ID Get the details of a policy's client. ``` Get /api/v1/policies/:id ``` This endpoint will allow for the user recive client policy details. ````csharp { "id": "64cceef9-3a01-49ae-a23b-3761b604800b", "amountInsured": "1825.89", "email": "<EMAIL>", "inceptionDate": "2016-06-01T03:33:32Z", "installmentPayment": true, "clientId": "e8fd159b-57c4-4d36-9bd7-a59ca13057bb" } ```` In folder `/src/controllers/policies.js` you can find middleware to this endpoint. ````csharp // Get policies by Id example:/api/v1/policies/e8fd159b-57c4-4d36-9bd7-a59ca13057bb const getPoliciesById = async (req, res, next) => { try{ //Get policy id from req.param const { id } = req.params; //Consume Api and get policies data const data = await getPolicies(); //Find policy by id const findById = data.find(p => p.id === id); //If policy not exist return 404 not found error if(!findById) return res.status(404).send({message: 'Not Found error'}) //Return policy details return res.status(200).json(findById); }catch(err){ //If is error send to handler error what is in /src/app.js next(err); } } ```` #Clients Get the list of clients details paginated and limited to 10 elements by default also an optional filter query to filter by client name. ``` Get /api/v1/clients ``` * Query string ``` Get /api/v1/clients?limit=10&name=Britney ``` This endpoint will allow for the user recive clients details paginated separeted by roles. * User role. ````csharp { "id": "a3b8d425-2b60-4ad7-becc-bedf2ef860bd", "name": "Barnett", "email": "<EMAIL>", "role": "user", "policie": [] } ```` * Admin role. ````csharp { "id": "a0ece5db-cd14-4f21-812f-966633e7be86", "name": "Britney", "email": "<EMAIL>", "role": "admin", "policie": [ { "id": "7b624ed3-00d5-4c1b-9ab8-c265067ef58b", "amountInsured": "399.89", "inceptionDate": "2015-07-06T06:55:49Z" } ] } ```` In folder `/src/controllers/clients.js` you can find middleware to this endpoint. ````csharp //Get clients by roles and filter by query limit and name example URL:/api/v1/clients?limit=5&name=Manning const getClientsData = async (req, res, next) => { try{ //After veryfication get role from request const { role } = req.user; //Get query data from query string const { limit, name } = req.query; //Consume Api and get clients data const data = await getClients(); //Consume Api and get policies data const dataPolicies = await getPolicies(); //Check is roles not exist throw 403 error if(!role) return res.status(403).send({message: 'Forbidden error'}) //Check condition if is true run code for user if(role === "user"){ //Filter client data and return array with only users clients const dataByRole = data.filter(user => user.role === role); //For each user client check if exsit policies dataByRole.map(user => { //Array policies with objects inside const objPolice = []; //Filter policies data and return array policies if client id === user id const policies = dataPolicies.filter(u => u.clientId === user.id); //Create new Array with data what is required policies.map(p => { objPolice.push({ id: p.id, amountInsured: p.amountInsured, inceptionDate: p.inceptionDate }) }) //Create value policie in user object and assign destructured Array user.policie = [...objPolice]; }) //Check if is query string if(limit || name ){ //If is query string name filter users by name const findByName = name ? dataByRole.filter(user => user.name === name) : dataByRole; //If is query string limit slice data to number of limits const limitData = findByName ? findByName.slice(0, limit) : dataByRole.slice(0, 10); //If query string is true response 200 with data return res.status(200).json(limitData); } //If endpoint is without query strings response with limit set by default 10 with status 200 const limitedByDefault = dataByRole.slice(0, 10); return res.status(200).json(limitedByDefault); } //Check condition if is true run code for admin if(role === "admin"){ //For each user in Array set new vale with policies data.map(user => { //New Array with objects policies const objPolice = []; //Check data policies and filter with user id const policies = dataPolicies.filter(u => u.clientId === user.id); //For each policie retrive required values policies.map(p => { //Push values to new Array objPolice.push({ id: p.id, amountInsured: p.amountInsured, inceptionDate: p.inceptionDate }) }) //Create value policie in user object and assign destructured Array user.policie = [...objPolice]; }) //Check if is query string if(limit || name ){ //If is query string name filter users by name const findByName = name ? data.filter(user => user.name === name) : data; //If is query string limit slice data to number of limits const limitData = findByName ? findByName.slice(0, limit) : data.slice(0, 10); //If query string is true response 200 with data return res.status(200).json(limitData); } //If endpoint is without query strings response with status 200 return res.status(200).json(data); } }catch(err){ //If is error send to handler error what is in /src/app.js next(err); } } ```` #Clients by ID Get the client's details ``` Get /api/v1/clients/:id ``` Can be accessed by client with role user and admin. * User role. ````csharp { "id": "a3b8d425-2b60-4ad7-becc-bedf2ef860bd", "name": "Barnett", "email": "<EMAIL>", "role": "user", "policies": [] } ```` * Admin role. ````csharp { "id": "a0ece5db-cd14-4f21-812f-966633e7be86", "name": "Britney", "email": "<EMAIL>", "role": "admin", "policie": [ { "id": "7b624ed3-00d5-4c1b-9ab8-c265067ef58b", "amountInsured": "399.89", "inceptionDate": "2015-07-06T06:55:49Z" } ] } ```` In folder `/src/controllers/clients.js` you can find middleware to this endpoint. ````csharp //Get clients by roles and by ID with policies example URL: /api/v1/clients/a0ece5db-cd14-4f21-812f-966633e7be86 const getClientsById = async (req, res, next) => { try{ //After veryfication get role from request const { role } = req.user; //Get client id from req.param const { id } = req.params; //Consume Api and get clients data const dataClient = await getClients(); //Consume Api and get policies data const dataPolicies = await getPolicies(); //Check is roles not exist throw 403 error if(!role) return res.status(403).send({message: 'Forbidden error'}) //Check condition if is true run code for user if(role === "user"){ //Filter client data and return array with only users clients const dataByRole = dataClient.filter(user => user.role === role); //If role not exist in data base return 404 if(!dataByRole) return res.status(404).send({message: "Not Found error."}); //Find client from data base by id const findClientById = dataByRole.find(c => c.id === id); //If client not exist in data base return 404 if(!findClientById) return res.status(404).send({message: "Not Found error."}); //Create new array for objects policies const policies = [] //Filter data policies and return by client id const findPoliciesById = dataPolicies.filter(c => c.clientId === id); //Return new object data with value requeried findPoliciesById.map(p => { policies.push({ "id" : p.id, "amountInsured" : p.amountInsured, "inceptionDate": p.inceptionDate }) }) //Create value policie in user object and assign destructured Array findClientById.policies = [...policies]; //Assing to client data new array policies with objects and return response status 200 const clientData = Object.assign([findClientById]); return res.status(200).json(clientData); } //Check condition if is true run code for admin if(role === "admin"){ //Find client from data base by id const findClientById = dataClient.find(c => c.id === id); //If client not exist return 404 not found if(!findClientById) return res.status(404).send({message: "Not Found error."}); //Create new array for objects policies const policies = [] //Filter data policies and return by client id const findPoliciesById = dataPolicies.filter(c => c.clientId === id); //Return new object data with value requeried findPoliciesById.map(p => { policies.push({ "id" : p.id, "amountInsured" : p.amountInsured, "inceptionDate": p.inceptionDate }) }) //Create value policie in user object and assign destructured Array findClientById.policies = [...policies]; //Assing to client data new array policies with objects and return response status 200 const clientData = Object.assign([findClientById]); return res.status(200).json(clientData); } }catch(err){ //If is error send to handler error what is in /src/app.js next(err); } } ```` #Clients by ID and policies Get the client's policies ``` Get /api/v1/clients/:id/policies ``` Can be accessed by client with role user and admin. * User role. ````csharp { [] //Empty array becuase any user dont have policices assign } ```` * Admin role. ````csharp { "id": "7b624ed3-00d5-4c1b-9ab8-c265067ef58b", "amountInsured": "399.89", "email": "<EMAIL>", "inceptionDate": "2015-07-06T06:55:49Z", "installmentPayment": true } ```` In folder `/src/controllers/clients.js` you can find middleware to this endpoint. ````csharp //Get policies by client Id example URL:/api/v1/clients/a74c83c5-e271-4ecf-a429-d47af952cfd4/policies const getPoliciesByClientId = async (req, res, next) => { try{ //After veryfication get role from request const { role } = req.user; //Get client id from req.param const { id } = req.params; //Consume Api and get clients data const dataClient = await getClients(); //Consume Api and get policies data const dataPolicies = await getPolicies(); //Check is roles not exist throw 403 error if(!role) return res.status(403).send({message: 'Forbidden error'}) //Check condition if is true run code for user if(role === "user"){ //Filter client data and return array with only users clients const dataByRole = dataClient.filter(user => user.role === role); //If role not exist in data base return 404 if(!dataByRole) return res.status(404).send({message: "Not Found error."}); //Create new array for objects policies const policies = []; //Find client from data base by id const getClientById = dataByRole.find(user => user.id === id); //If client not exist in data base return 404 if(!getClientById) return res.status(404).send({message: "Not Found error."}); //Filter data policies and return by client id const getPoliciesByClientId = dataPolicies.filter(policies => policies.clientId === getClientById.id); //Return new object data with value requeried getPoliciesByClientId.map(policie => { policies.push({ "id": policie.id, "amountInsured": policie.amountInsured, "email": policie.email, "inceptionDate": policie.inceptionDate, "installmentPayment": policie.installmentPayment }) }) //Return response with status 200 and policie return res.status(200).send(policies); } //Check condition if is true run code for user if(role === "admin"){ //Filter client data and return array with only users clients const getClientById = dataClient.find(user => user.id === id); //If role not exist in data base return 404 if(!getClientById) return res.status(404).send({message: "Not Found error."}); //Create new array for objects policies const policies = []; //Filter data policies and return by client id const getPoliciesByClientId = dataPolicies.filter(policies => policies.clientId === getClientById.id); //Return new object data with value requeried getPoliciesByClientId.map(policie => { policies.push({ "id": policie.id, "amountInsured": policie.amountInsured, "email": policie.email, "inceptionDate": policie.inceptionDate, "installmentPayment": policie.installmentPayment }) }) //Return response with status 200 and policie return res.status(200).send(policies); } }catch(err){ //If is error send to handler error what is in /src/app.js next(err); } } ````<file_sep>/src/services/auth.js const jwt = require('jsonwebtoken'); const config = require('../config'); /** * * AUTHORIZATION SERVICE * * 1.Function generateAccessToken create new token with user payload. * 2.Function verifyToken is checking Authorization header and verifying token * * */ // Generate access token const generateAccessToken = (user) => { const exp = Math.floor(Date.now() / 1000) + (60 * 60); const token = jwt.sign(user, config.secret, { algorithm: 'HS256', expiresIn: exp, }); return { token, type: 'Bearer', expiresIn: exp }; }; // Verify token access // eslint-disable-next-line consistent-return const verifyToken = (req, res, next) => { try { const bearerHeader = req.headers.authorization; const token = bearerHeader && bearerHeader.split(' ')[1]; if (!token) return res.status(401).send({ message: 'Unauthorized' }); // eslint-disable-next-line consistent-return jwt.verify(token, config.secret, (err, user) => { if (err) return res.status(401).send({ message: 'Token is not valid' }); req.user = user; next(); }); } catch (err) { next(err); } }; module.exports = { verifyToken, generateAccessToken, }; <file_sep>/src/helpers/index.js const fs = require('fs').promises; const jwt = require('jsonwebtoken'); const actions = require('../actions'); /** * HELPERS FUNCTIONS * * 1.Funciton readToken for read token from API integration is stored in apiData.json . * 2.Function refreshToken is checking time of API token if is expired is generate new token. * * */ // Read token from file authData.json // eslint-disable-next-line consistent-return const readToken = async () => { try { const readFile = await fs.readFile('./apiData.json'); const data = JSON.parse(readFile); const { token } = data; return token; } catch (err) { console.error(err); } }; // Check if API token is expired // eslint-disable-next-line consistent-return const refreshToken = async (token) => { try { const decodeToken = jwt.decode(token, { complete: true }); const { payload } = decodeToken; if (Date.now() >= payload.exp * 1000) { const newToken = await actions.loginApi(); return newToken; } return token; } catch (err) { console.error(err); } }; module.exports = { readToken, refreshToken, }; <file_sep>/src/routes/policies.js const express = require('express'); const router = express.Router(); /** * * POLICIES ROUTES * * */ const { getPoliciesData, getPoliciesById } = require('../controllers/policies'); const { verifyToken } = require('../services/auth'); // Policies routes router.get('/:id', verifyToken, getPoliciesById); router.get('', verifyToken, getPoliciesData); module.exports = router; <file_sep>/src/config/index.js /** * * SECRET WORD FOR JSON WEB TOKEN * **/ module.exports = { 'secret': process.env.JWT_SECRET || "cookie" };<file_sep>/src/tests/integration.test.js /* eslint-disable no-useless-concat */ /* eslint-disable no-undef */ const request = require('supertest'); const app = require('../app'); let TOKEN; describe('Endpoints tests', () => { /** * * TEST LOGIN ROUTE * * */ describe('GET /api/v1/login', () => { it('Should return token', async (done) => { expect.assertions(2); const res = await request(app) .post('/api/v1/login') .set('Accept', 'application/json') .send({ username: 'test', password: '<PASSWORD>' }); expect(res.status).toBe(200); expect(res.body).toMatchObject({ token: expect.any(String), type: expect.any(String), expiresIn: expect.any(Number), }); TOKEN = res.body.token; done(); }); it('Should return 401 username or password not valid', async (done) => { expect.assertions(1); const res = await request(app) .post('/api/v1/login') .set('Accept', 'application/json') .send({ username: 'te', password: 'te' }); expect(res.status).toBe(401); done(); }); }); /** * * TEST POLICIES ROUTE * * */ describe('GET /api/v1/policies', () => { it('Should return all policies 10 by default', async (done) => { expect.assertions(2); const res = await request(app) .get('/api/v1/policies') .set('Authorization', `Bearer ${TOKEN}`); expect(res.status).toBe(200); expect(res.body.length).toBe(10); done(); }); it('Should return 401 Unauthorized error.', async (done) => { expect.assertions(1); const res = await request(app) .get('/api/v1/policies') .set('Authorization', 'Bearer ' + ''); expect(res.status).toBe(401); done(); }); it('Should return 401 Unauthorized error.Token is not valid', async (done) => { expect.assertions(1); const res = await request(app) .get('/api/v1/policies') .set('Authorization', 'Bearer ' + 'aaa'); expect(res.status).toBe(401); done(); }); it('Should return policies limited by query string', async (done) => { const limit = 5; expect.assertions(2); const res = await request(app) .get(`/api/v1/policies?limit=${limit}`) .set('Authorization', `Bearer ${TOKEN}`); expect(res.status).toBe(200); expect(res.body.length).toBe(limit); done(); }); it('Should return policies matched to object schema', async (done) => { expect.assertions(2); const res = await request(app) .get('/api/v1/policies') .set('Authorization', `Bearer ${TOKEN}`); expect(res.status).toBe(200); expect(res.body).toContainEqual({ id: expect.any(String), amountInsured: expect.any(String), email: expect.any(String), inceptionDate: expect.any(String), installmentPayment: expect.any(Boolean), }); done(); }); }); describe('GET /api/v1/policies/:id', () => { it('Should return policie by id', async (done) => { const id = '5a72ae47-d077-4f74-9166-56a6577e31b9'; expect.assertions(2); const res = await request(app) .get(`/api/v1/policies/${id}`) .set('Authorization', `Bearer ${TOKEN}`); expect(res.status).toBe(200); expect(res.body).toMatchObject({ id: expect.any(String), clientId: expect.any(String), amountInsured: expect.any(String), email: expect.any(String), inceptionDate: expect.any(String), installmentPayment: expect.any(Boolean), }); done(); }); it('Should return 401 Unauthorized', async (done) => { const id = '5a72ae47-d077-4f74-9166-56a6577e31b9'; expect.assertions(1); const res = await request(app) .get(`/api/v1/policies/${id}`) .set('Authorization', 'Bearer ' + 'asd'); expect(res.status).toBe(401); done(); }); it('Should return 404 Not Found error', async (done) => { const id = '5a72ae47-d077-4f74-9166-56a6577e3'; expect.assertions(1); const res = await request(app) .get(`/api/v1/policies/${id}`) .set('Authorization', `Bearer ${TOKEN}`); expect(res.status).toBe(404); done(); }); }); /** * * TEST CLIENTS ROUTE * * */ describe('GET /api/v1/clients', () => { it('Should return 10 elements by default and status 200', async (done) => { expect.assertions(2); const res = await request(app) .get('/api/v1/clients') .set('Authorization', `Bearer ${TOKEN}`); expect(res.body.length).toBe(10); expect(res.status).toBe(200); done(); }); it('Should return elements limited by query string', async (done) => { const limit = 5; expect.assertions(2); const res = await request(app) .get(`/api/v1/clients?limit=${limit}`) .set('Authorization', `Bearer ${TOKEN}`); expect(res.body.length).toBe(limit); expect(res.status).toBe(200); done(); }); it('Should return elements by name query string', async (done) => { const name = 'Barnett'; expect.assertions(2); const res = await request(app) .get(`/api/v1/clients?name=${name}`) .set('Authorization', `Bearer ${TOKEN}`); expect(res.status).toBe(200); expect(res.body).toEqual(expect.any(Array)); done(); }); it('Should return elements by name and limit query string', async (done) => { const name = 'Barnett'; const limit = 5; expect.assertions(2); const res = await request(app) .get(`/api/v1/clients?name=${name}&limit=${limit}`) .set('Authorization', `Bearer ${TOKEN}`); expect(res.status).toBe(200); expect(res.body).toEqual(expect.any(Array)); done(); }); it('Should return 401 unauthorized error', async (done) => { const name = 'Barnett'; const limit = 5; expect.assertions(1); const res = await request(app) .get(`/api/v1/clients?name=${name}&limit=${limit}`); expect(res.status).toBe(401); done(); }); }); describe('GET /api/v1/clients/:id', () => { it("Should return client's details by id", async (done) => { expect.assertions(3); const res = await request(app) .get('/api/v1/clients/a3b8d425-2b60-4ad7-becc-bedf2ef860bd') .set('Authorization', `Bearer ${TOKEN}`); expect(res.status).toBe(200); expect(res.body.length).toBe(1); expect(res.body).toEqual(expect.any(Array)); done(); }); it('Should return 401 unauthorized error', async (done) => { expect.assertions(1); const res = await request(app) .get('/api/v1/clients/a3b8d425-2b60-4ad7-becc-bedf2ef860bd'); expect(res.status).toBe(401); done(); }); it('Should return 404 not Found error', async (done) => { expect.assertions(1); const res = await request(app) .get('/api/v1/clients/a3b8d425-2b60-4ad7-becc-bedf2e') .set('Authorization', `Bearer ${TOKEN}`); expect(res.status).toBe(404); done(); }); }); describe('GET /api/v1/clients/:id', () => { it("Should return client's policies", async (done) => { expect.assertions(2); const res = await request(app) .get('/api/v1/clients/a3b8d425-2b60-4ad7-becc-bedf2ef860bd/policies') .set('Authorization', `Bearer ${TOKEN}`); expect(res.status).toBe(200); expect(res.body).toEqual(expect.any(Array)); done(); }); it('Should return 401 unauthorized error', async (done) => { expect.assertions(1); const res = await request(app) .get('/api/v1/clients/a3b8d425-2b60-4ad7-becc-bedf2ef860bd/policies'); expect(res.status).toBe(401); done(); }); it('Should return 404 not Found error', async (done) => { expect.assertions(1); const res = await request(app) .get('/api/v1/clients/a3b8d425-2b60-4ad7-becc-bedf2ef860bd/poicies'); expect(res.status).toBe(404); done(); }); }); }); <file_sep>/src/controllers/clients.js const { getClients } = require('../actions'); const { getPolicies } = require('../actions'); /** * * CLIENT CONTROLLERS * * */ // eslint-disable-next-line max-len // Get clients by roles and filter by query limit and name example URL:/api/v1/clients?limit=5&name=Manning // eslint-disable-next-line consistent-return const getClientsData = async (req, res, next) => { try { const { role } = req.user; const { limit, name } = req.query; const data = await getClients(); const dataPolicies = await getPolicies(); if (!role) return res.status(403).send({ message: 'Forbidden error' }); if (role === 'user') { const dataByRole = data.filter((user) => user.role === role); // eslint-disable-next-line array-callback-return dataByRole.map((user) => { const objPolice = []; const policies = dataPolicies.filter((u) => u.clientId === user.id); policies.map((p) => objPolice.push({ id: p.id, amountInsured: p.amountInsured, inceptionDate: p.inceptionDate, })); // eslint-disable-next-line no-param-reassign user.policie = [...objPolice]; }); if (limit || name) { const findByName = name ? dataByRole.filter((user) => user.name === name) : dataByRole; const limitData = findByName ? findByName.slice(0, limit) : dataByRole.slice(0, 10); return res.status(200).json(limitData); } const limitedByDefault = dataByRole.slice(0, 10); return res.status(200).json(limitedByDefault); } if (role === 'admin') { // eslint-disable-next-line array-callback-return data.map((user) => { const objPolice = []; const policies = dataPolicies.filter((u) => u.clientId === user.id); policies.map((p) => objPolice.push({ id: p.id, amountInsured: p.amountInsured, inceptionDate: p.inceptionDate, })); // eslint-disable-next-line no-param-reassign user.policie = [...objPolice]; }); if (limit || name) { const findByName = name ? data.filter((user) => user.name === name) : data; const limitData = findByName ? findByName.slice(0, limit) : data.slice(0, 10); return res.status(200).json(limitData); } return res.status(200).json(data); } } catch (err) { next(err); } }; // eslint-disable-next-line max-len // Get clients by roles and by ID with policies example URL: /api/v1/clients/a0ece5db-cd14-4f21-812f-966633e7be86 // eslint-disable-next-line consistent-return const getClientsById = async (req, res, next) => { try { const { role } = req.user; const { id } = req.params; const dataClient = await getClients(); const dataPolicies = await getPolicies(); if (!role) return res.status(403).send({ message: 'Forbidden error' }); if (role === 'user') { const dataByRole = dataClient.filter((user) => user.role === role); if (!dataByRole) return res.status(404).send({ message: 'Not Found error.' }); const findClientById = dataByRole.find((c) => c.id === id); if (!findClientById) return res.status(404).send({ message: 'Not Found error.' }); const policies = []; const findPoliciesById = dataPolicies.filter((c) => c.clientId === id); findPoliciesById.map((p) => policies.push({ id: p.id, amountInsured: p.amountInsured, inceptionDate: p.inceptionDate, })); findClientById.policies = [...policies]; const clientData = Object.assign([findClientById]); return res.status(200).json(clientData); } if (role === 'admin') { const findClientById = dataClient.find((c) => c.id === id); if (!findClientById) return res.status(404).send({ message: 'Not Found error.' }); const policies = []; const findPoliciesById = dataPolicies.filter((c) => c.clientId === id); findPoliciesById.map((p) => policies.push({ id: p.id, amountInsured: p.amountInsured, inceptionDate: p.inceptionDate, })); findClientById.policies = [...policies]; const clientData = Object.assign([findClientById]); return res.status(200).json(clientData); } } catch (err) { next(err); } }; // eslint-disable-next-line max-len // Get policies by client Id example URL:/api/v1/clients/a74c83c5-e271-4ecf-a429-d47af952cfd4/policies // eslint-disable-next-line consistent-return const getPoliciesByClientId = async (req, res, next) => { try { const { role } = req.user; const { id } = req.params; const dataClient = await getClients(); const dataPolicies = await getPolicies(); if (!role) return res.status(403).send({ message: 'Forbidden error' }); if (role === 'user') { const dataByRole = dataClient.filter((user) => user.role === role); if (!dataByRole) return res.status(404).send({ message: 'Not Found error.' }); const policies = []; const getClientById = dataByRole.find((user) => user.id === id); if (!getClientById) return res.status(404).send({ message: 'Not Found error.' }); // eslint-disable-next-line max-len const getPoliciesByClient = dataPolicies.filter((p) => p.clientId === getClientById.id); getPoliciesByClient.map((policie) => policies.push({ id: policie.id, amountInsured: policie.amountInsured, email: policie.email, inceptionDate: policie.inceptionDate, installmentPayment: policie.installmentPayment, })); return res.status(200).send(policies); } if (role === 'admin') { const getClientById = dataClient.find((user) => user.id === id); if (!getClientById) return res.status(404).send({ message: 'Not Found error.' }); const policies = []; const getPoliciesByClient = dataPolicies.filter((p) => p.clientId === getClientById.id); getPoliciesByClient.map((policie) => policies.push({ id: policie.id, amountInsured: policie.amountInsured, email: policie.email, inceptionDate: policie.inceptionDate, installmentPayment: policie.installmentPayment, })); return res.status(200).send(policies); } } catch (err) { next(err); } }; module.exports = { getClientsData, getClientsById, getPoliciesByClientId, }; <file_sep>/src/app.js require('dotenv').config(); const express = require('express'); const app = express(); const bodyParser = require('body-parser'); // Routes const userRoutes = require('./routes/user'); const policiesRoutes = require('./routes/policies'); const clientRoutes = require('./routes/clients'); // parse application/x-www-form-urlencoded app.use(bodyParser.urlencoded({ extended: false })); // parse application/json app.use(bodyParser.json()); // user app.use('/api/v1/login', userRoutes); // Policies routes app.use('/api/v1/policies', policiesRoutes); // Clients routes app.use('/api/v1/clients', clientRoutes); // Error handler // eslint-disable-next-line no-unused-vars app.use((err, req, res, next) => { res.status(500).send({ error: err.message }); }); // Export app to index.js for supertest module.exports = app;
9bd7b1e83571688fb246f632dbe4800724d9d0bf
[ "JavaScript", "Markdown" ]
10
JavaScript
Wojtec/test-restapi
48a32ca02d5fac54e91115814990c8be27d57bc8
0ddbc8f5f4c4fb36e59843e8d864cd7d625554ca
refs/heads/master
<file_sep>--- title: "MAT02018 - Estatística Descritiva" subtitle: "Distribuição de Frequências (dados contínuos)" fontsize: 10pt author: | | <NAME> | `<EMAIL>` institute: | | \textsc{Universidade Federal do Rio Grande do Sul} | \textsc{Instituto de Matemática e Estatística} | \textsc{Departamento de Estatística} date: | | Porto Alegre, 2021 header-includes: - \titlegraphic{\hfill\includegraphics[height=1.5cm]{logos/Logo-40-anos-estatistica.png}} --- # Distribuição de Frequências ## Dados contínuos {.allowframebreaks} - Dados contínuos podem assumir __diversos valores diferentes__\footnote{Aqui chamamos mais uma vez a atenção para a importância de distinguirmos os diferentes tipos de variáveis. Uma variável \emph{quantitativa contínua} é uma {\bf variável}! E portanto, {\bf pode variar} de um indivíduo para outro! No entanto, a variável \emph{quantitativa contínua} possui um conjunto de valores possíveis {\bf infinito} (um intervalo da reta real), e assim, podemos observar um número de unidades com valores distintos para uma certa variável contínua maior que no caso de uma variável nominal. {\bf Exercício:} compare os valores possíveis para as variáveis {\bf altura} e {\bf estado civil}.}, mesmo em amostras pequenas. - Por essa razão, a menos que sejam em grande número, são apresentados na forma como foram coletados. ## Dados contínuos {.allowframebreaks} - Considere, como exemplo, que o pesquisador resolveu organizar as idades dos empregados da seção de orçamentos da Companhia MB em uma tabela. - Pode escrever os dados na ordem em que foram coletados, como segue: ```{r, echo=FALSE, message=FALSE, warning=FALSE, purl=FALSE} idade <- c(26, 32, 36, 20, 40, 28, 41, 43, 34, 23, 33, 27, 37, 44, 30) idade.tab <- matrix(data = idade, nrow = 3) knitr::kable(idade.tab, format = "pandoc") ``` \framebreak - Quando em grande número, os dados contínuos podem ser organizados, para apresentação, em uma tabela de distribuição de frequências. - Vamos entender como isso é feito por meio de novo exemplo. \framebreak - Foram propostas muitas maneiras de avaliar a capacidade de uma criança para o desempenho escolar. - Algumas crianças estão "prontas" para aprender a escrever aos cinco anos, outras, aos oito anos. - Imagine que um professor aplicou o _Teste de Desempenho Escolar_ (TDE) a 27 alunos da 1ª série do Ensino Fundamental. - Os dados obtidos pelo professor estão apresentados em seguida. ```{r, echo=FALSE, message=FALSE, warning=FALSE, purl=FALSE} tde <- c(7, 18, 111, 25, 101, 85, 81, 75, 100, 95, 98, 108, 100, 94, 34, 99, 84, 90, 95, 102, 96, 105, 100, 107, 117, 96, 17) tde.tab <- matrix(data = tde, nrow = 3) knitr::kable(tde.tab, format = "pandoc") ``` \framebreak - Para __conhecer o comportamento__ do desempenho escolar desses alunos, o professor deve organizar uma __distribuição de frequências__. - No entanto, para isso, é preciso __agrupar os dados em faixas__, ou __classes__\footnote{Note que se procedermos da mesma forma que procedemos para os casos anteriores, a nossa tabela de distribuição de frequências apresentaria um grande número de valores com baixas frequências. Isso nos daria tanta informação quanto a tabela de dados brutos, e portanto, não nos ajudaria a conhecer o comportamento da variável.}. + Em quantas faixas ou classes podem ser agrupados os dados? ## Dados contínuos {.allowframebreaks} - Uma __regra prática__ é a seguinte: \structure{o número de classes deve ser aproximadamente igual à raiz quadrada do tamanho da amostra.} $$ \mbox{Número de classes} = \sqrt{n}. $$ - No exemplo, são 27 alunos. + O tamanho da amostra é, portanto, $n = 27$. + A raiz quadrada de 27 está entre $5 (\sqrt{25})$ e $6 (\sqrt{36})$. Portanto, podem ser organizadas __cinco classes__. - Mas como? \framebreak - Observe cuidadosamente o conjunto de dados. - Ache o __valor mínimo__, o __valor máximo__ e a __amplitude__. ### - __Valor mínimo__ é o menor valor de um conjunto de dados. - __Valor máximo__ é o maior valor de um conjunto de dados. - __Amplitude__ é a diferença entre o valor máximo e o valor mínimo. ## Dados contínuos {.allowframebreaks} - Para os valores obtidos pelos 27 alunos no Teste de Desempenho Escolar, temos: - Valor mínimo $= 7$; - Valor máximo $= 117$; - Amplitude $= 117 - 7 = 110$. - Uma vez obtida a amplitude do conjunto de dados, é preciso calcular a \structure{amplitude das classes}. \framebreak - \structure{Amplitude de classe} é dada pela divisão da amplitude do conjunto de dados pelo número de classes. - Para os dados do TDE, a amplitude ($110$) deve ser dividida pelo número de classes que já foi calculado ($5$): $$ 110 \div 5 = 22. $$ \framebreak - A __amplitude de classe__ será, então, $22$. Isso significa que: - a primeira classe vai do valor mínimo, $7$ até $7 + 22 = 29$; - a segunda classe vai de $29$ a $29 + 22 = 51$; - a terceira classe vai de $51$ a $51 + 22 = 73$; - a quarta classe vai de $73$ a $73 + 22 = 95$; - a quinta classe vai de $95$ a $95 + 22 = 117$, inclusive. - Os valores que delimitam as classes são denominados \structure{extremos}. \framebreak - \structure{Extremos de classe} são os valores que delimitam as classes. - Uma questão importante é saber __como__ as classes devem ser escritas. Alguém pode pensar em escrever as classes como segue: \begin{eqnarray*} 7 &-& 28\\ 29 &-& 51, \mbox{etc.}\\ \end{eqnarray*} - No entanto, essa notação traz dúvidas. \framebreak - Como saber, por exemplo, para qual classe vai o valor $28,5$? - Esse tipo de dúvida é evitado indicando as classes como segue: \begin{eqnarray*} 7 &\vdash& 28\\ 29 &\vdash& 51, \mbox{etc.}\\ \end{eqnarray*} - Usando essa notação, fica claro que o intervalo é \structure{fechado} à esquerda e \structure{aberto} à direita. \framebreak - Então, na classe $7\vdash 29$ estão \structure{incluídos} os valores iguais ao extremo inferior da classe, que é $7$ (o intervalo é fechado à esquerda), mas \structure{não estão incluídos} os valores iguais ao extremo superior da classe, que é $29$ (o intervalo é aberto à direita). - A indicação de que o intervalo é fechado é dada pelo lado esquerdo do traço vertical do símbolo $\vdash$. - A indicação de intervalo aberto é dada pela ausência de traço vertical no lado direito do símbolo $\vdash$. - Uma alternativa a esta notação é dada por \structure{colchetes} e \structure{parênteses}. \framebreak - Considere \structure{$ei$} e \structure{$es$} os \structure{extremos inferior} e \structure{superio}r de uma classe qualquer, respectivamente. - "$(ei; es]$", ou "$\dashv$" é um intervalo aberto à esquerda e fechado à direita; - "$[ei; es)$", ou "$\vdash$" é um intervalo aberto à direita e fechado à esquerda; - "$(ei; es)$", ou "$]ei; es[$", ou "--" é um intervalo aberto; - "$[ei; es]$", ou "$\vdash\dashv$" é um intervalo fechado. \framebreak - Estabelecidas as classes, é preciso obter as \structure{frequências}. - Para isso, contam-se quantos alunos estão na classe de $7$ a $29$ \structure{(exclusive)}\footnote{Ou, seja, sem incluir o extremo direito do intervalo de classe; neste caso, o valor 29.}, quantos estão na classe de $29$ a $51$ \structure{(exclusive)}, e assim por diante. ### Apuração - Aqui uma abordagem poderia ser a criação de uma "nova variável" (transformada) de idade em classes na planilha de dados brutos, e então proceder com a apuração desta "nova variável" como no caso de uma variável qualitativa. - Afinal de contas, as classes de idade são categorias. + Neste caso, categorias de uma variável qualitativa ordinal. ## Dados contínuos {.allowframebreaks} - A distribuição de frequências pode então ser organizada como segue. ```{r, echo=FALSE, message=FALSE, warning=FALSE, purl=FALSE} tde.cat <- cut(x = tde, breaks = c(7, 29, 51, 73, 95, 117), labels = c("7 $\\vdash$ 29", "29 $\\vdash$ 51", "51 $\\vdash$ 73", "73 $\\vdash$ 95", "95 $\\vdash$ 117"), include.lowest = F, right = FALSE) tde.tab <- as.data.frame(na.omit(summarytools::freq(tde.cat)))["Freq"] tde.tab <- data.frame("tde"= row.names(tde.tab), "freq" = tde.tab$Freq) knitr::kable(tde.tab, col.names = c("Classe TDE", "Frequência ($n_i$)"), align = "lc") ``` ## Observações {.allowframebreaks} - Embora a __regra prática__ apresentada aqui para a determinação do número de classes seja útil, ela não é a única forma de determinar classes em uma tabela de frequências para dados contínuos. - O pesquisador pode especificar as classes de acordo com "convenções". - É comum vermos as frequências da variável idade serem apresentadas em classes de amplitude 5 ou 10 anos. - Ainda, podem ser especificadas classes com amplitudes distintas (Idade de 0 a 19 anos, 20 a 59 anos, 60 a 79 anos, 80 anos ou mais). \framebreak - Outro ponto importante é que nem sempre existe interesse em apresentar todas as classes possíveis. - Em aluns casos, a primeira classe pode incluir todos os elementos menores que determinado valor. - Diz-se, então, que o extremo inferior da primeira classe não está definido. - Como exemplo, veja a distribuição de frequências das pessoas conforme a altura, com as seguintes classes: \begin{eqnarray*} && \mbox{Menos de } 150 \mbox{ cm}\\ && 150\ \vdash 160 \mbox{cm}\\ && 160\ \vdash 170 \mbox{cm, etc.}\\ \end{eqnarray*} \framebreak - Do mesmo modo, todos os elementos iguais ou maiores que determinado valor podem ser agrupados na última classe. - Diz-se, então, que o extremo superior da última classe não está definido. - Muitos dados de idade publicados pelo __Instituto Brasileiro de Geografia e Estatística__ (__IBGE__) estão em tabelas de distribuição de frequências com intervalos de classes diferentes (em relação a amplitude) e não possuem extremo superior definido. - Veja o exemplo a seguir. \framebreak ```{r fig-censo, fig.align='center', fig.cap = "População residente, segundo grupos de idade no Brasil (Censo 2010; https://censo2010.ibge.gov.br/sinopse/index.php?dados=12).", cache=TRUE, echo=FALSE, out.height="70%", out.width='30%', purl=FALSE} knitr::include_graphics(here::here('images', 'ibge_idade_censo2010.png')) ``` ## Para casa 1. Resolver os exercícios 4, 5 e 6 do Capítulo 3.5 do livro __Fundamentos de Estatística__\footnote{Vieira, S. {\bf Fundamentos de Estatística}, Atlas, 2019, pg. 37-38.} (disponível no Sabi+). 2. Para os dados contínuos do seu levantamento estatístico, construa tabelas de frequências e compartilhe no Fórum Geral do Moodle. Discuta como você definiu as classes e suas amplitudes. ## Próxima aula - Distribuição de frequências: __frequências relativa, acumulada, relativa acumulada e porcentagem__. ## Por hoje é só! \begin{center} {\bf Bons estudos!} \end{center} ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='50%', out.height='50%', paged.print=FALSE} knitr::include_graphics(here::here('images', 'Statistically-Insignificant-errorbar.jpg')) ``` <file_sep>--- title: "MAT02018 - Estatística Descritiva" subtitle: "Organização dos dados" fontsize: 10pt author: | | <NAME> | `<EMAIL>` institute: | | \textsc{Universidade Federal do Rio Grande do Sul} | \textsc{Instituto de Matemática e Estatística} | \textsc{Departamento de Estatística} date: | | Porto Alegre, 2021 header-includes: - \titlegraphic{\hfill\includegraphics[height=1.5cm]{logos/Logo-40-anos-estatistica.png}} --- # Introdução ## Introdução - Agora que já discutimos alguns __conceitos básicos__ de estatística e as etapas gerais de um __levantamento estatístico__, vamos apresentar como é feito o __registro__ e a __organização de dados__ referentes a uma certa coleta de dados. - Começaremos com a __planilha__ para o registro dos dados e a __tabela de dados brutos__ resultante. - Logo em seguida, discutiremos como fazer a __apuração dos dados__. # Coleta de dados ## Coleta de dados {.allowframebreaks} ::: {.block} ### Lembrando A __estatística__ é a ciência que tem por objetivo orientar a _coleta_, o _resumo_, a _apresentação_, a _análise_ e a _interpretação_ de dados. ::: - Para __coletar dados__, o pesquisador necessitará armazenar os dados coletados em algum lugar. - Assim, se faz necessário organizar uma \structure{planilha}. ## Coleta de dados {.allowframebreaks} - Com o advento da computação, grande parte dos profissionais da área de estatística registram dados em uma __planilha eletrônica__\footnote{Softwares como \emph{Calc} (OpenOffice), \emph{Microsoft Excel} (Office) e \emph{Google Sheets} (Google) são exemplos de \emph{softwares} que trabalham com planilhas eletrônicas.}. - No entanto, os dados também podem ser registrados em meio físico como, por exemplo, fichas, cadernos ou cadernetas, ou seja, a chamada __planilha física__. ## Coleta de dados {.allowframebreaks} - As planilhas eletrônicas podem ser construídas a partir de planilhas físicas ou serem alimentadas por algum __instrumento de coleta__ em meio eletrônico (formulário ou questionário)\footnote{O \emph{Google Forms}, por exemplo, cria e alimenta uma planilha eletrônica a partir do formulário de coleta.}. - Vamos apresentar como se desenha uma planilha física para registro dos dados. - \structure{Se você tiver possibilidade, pode experimentar como organizar os dados em uma planilha eletrônica.} ## Planilha {.allowframebreaks} - __Planilha__ é o documento que armazena os dados coletados, distribuindo-os em linhas e colunas (ou seja, planilhas são "matrizes de dados"). - Em planilhas eletrônicas, geralmente, as linhas são numeradas e as colunas são indicadas por letras maiúsculas. ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='50%', out.height='50%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'planilha_eletro.png')) ``` ## Planilha {.allowframebreaks} __Exemplo:__ Um pesquisador está interessado em fazer um levantamento sobre alguns aspectos socioeconômicos dos empregados da seção de orçamentos da Companhia MB, um grupo de 15 pessoas\footnote{<NAME>. e <NAME>. {\bf Estatística Básica}, Saraiva, 2010.}. - Temos a seguinte planilha para registrar os dados do grupo. ## Planilha {.allowframebreaks} ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='70%', out.height='70%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'planilha_fisica.png')) ``` ## Tabela de dados brutos {.allowframebreaks} - __Dados brutos__ são os dados na forma em que foram coletados, sem qualquer tipo de tratamento. - Após a coleta de dados, o pesquisador tem em sua planilha o registro dos dados brutos. \framebreak ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='70%', out.height='70%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'dados_brutos.png')) ``` \framebreak - O que podemos falar sobre as variáveis coletadas? - Qual a informação podemos apresentar sobre os dados coletados? Para responder tais perguntadas, precisaremos __resumir__ os dados de alguma forma. # Apuração dos dados ## Apuração dos dados {.allowframebreaks} - __Apuração__ é o processo de retirar os dados da planilha e organizá-los, para apresentação. No exemplo apresentado anteriormente, foram coletadas as seguintes variáveis: estado civil, grau de instrução, número de filhos, salário, idade e região de procedência. Note que estas são variáveis de diferentes tipos. - __Exercício:__ classifique cada uma destas variáveis em __qualitativa nominal__, __qualitativa ordinal__, __quantitativa discreta__ e __quantitativa contínua__. ## Apuração de dados nominais {.allowframebreaks} - Se quisermos saber quantos solteiros e quantos casados trabalham na seção de orçamentos da Companhia MB devemos escrever os valores possíveis da variável __estado civil__\footnote{{\bf Pergunta:} a ordem de escrita dos valores possíveis da variável {\bf estado civil} importa? Por que?}. ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='70%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'apura_0.png')) ``` ## Apuração de dados nominais {.allowframebreaks} - Logo após, precisamos inspecionar cada registro da tabela de dados brutos e marcar um traço ao lado de __solteiro__, para cada indivíduo solteiro inspecionado, e um traço ao lado de __casado__ para cada indivíduo casado inspecionado. - A cada quatro traços, corta-se com um traço, e este conjunto representa uma contagem de cinco indivíduos\footnote{No inglês, \emph{tally marks} (marcas de registro).}. ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='70%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'apura_1.png')) ``` ## Apuração de dados nominais {.allowframebreaks} - Desta forma, verificamos que na seção de orçamentos da Companhia MB trabalham oito solteiros e sete casados. - Duas outras formas alternativas de se fazer a apuração dos dados são apresentadas a seguir. ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='70%', paged.print=FALSE, purl=FALSE} library(cowplot) library(ggplot2) p1 <- ggdraw() + draw_image(here::here('images', 'apura_2.png'), scale = 0.9) p2 <- ggdraw() + draw_image(here::here('images', 'apura_3.png'), scale = 0.9) plot_grid(p1, p2) ``` \framebreak ### Comentário É fácil apurar uma pequena massa de dados, como no caso do exemplo. Já uma grande massa de dados tornará a tarefa difícil e entediante. Além disso, com um grande volume de dados, a __probabilidade__ de incorrermos em erros aumenta! Necessitaremos do auxílio de __pacotes estatísticos__! ## Apuração de dados ordinais {.allowframebreaks} - Para apurar dados de grau de instrução (variável qualitativa ordinal), o procedimento é similar ao adotado para apurar dados nominais. - A diferença é que, para dados ordinais, __impõe-se uma ordem__. + Contudo, a apuração se faz por contagem. ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='70%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'apura_4.png')) ``` ## Apuração de dados discretos {.allowframebreaks} - Para apurar o número de filhos (variável quantitativa discreta), também devemos fazer uma contagem. - Escrevemos os resultados respeitando a ordem numérica. ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='70%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'apura_5.png')) ``` ## Apuração de dados contínuos {.allowframebreaks} - Em geral, os dados contínuos são apresentados na forma como foram coletados, porque assumem valores diferentes, mesmo em amostras pequenas. - É o caso da variável idade no exemplo considerado: os empregados da seção de orçamentos da Companhia MB tinham idades diferentes. - No entanto, é possível organizar as idades por __faixas__, como veremos nas aulas seguintes. ## Para casa 1. Construa a planilha para o registro do levantamento dos dados planejado nas aulas anteriores. 2. Faça uma pequena coleta de dados incluindo pelo menos uma variável de cada tipo (_qualitativa nominal_, _qualitativa ordinal_, _quantitativa discreta_ e _quantitativa contínua_). 1. Organize uma planilha (física ou eletrônica) para o registro dos dados coletados. 2. Faça a coleta e preencha a planilha para obter os dados brutos. 3. Faça a apuração dos dados e comente brevemente sobre os resultados encontrados. ## Próxima aula - Introdução ao `R`. ## Por hoje é só! \begin{center} {\bf Bons estudos!} \end{center} ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='50%', out.height='50%', paged.print=FALSE} knitr::include_graphics(here::here('images', 'Statistically-Insignificant-bolha.jpg')) ``` <file_sep>--- title: "MAT02018 - Estatística Descritiva" subtitle: "Fases do levantamento estatístico" fontsize: 10pt author: | | <NAME> | `<EMAIL>` institute: | | \textsc{Universidade Federal do Rio Grande do Sul} | \textsc{Instituto de Matemática e Estatística} | \textsc{Departamento de Estatística} date: | | Porto Alegre, 2020 header-includes: - \titlegraphic{\hfill\includegraphics[height=1.5cm]{logos/Logo-40-anos-estatistica.png}} --- ## Introdução O planejamento de um levantamento estatístico, em geral, abrange as seguintes fases: 1. Definição do Universo 2. Exame das informações disponíveis 3. Decisão sobre o tipo de levantamento 4. Obtenção das informações 5. Elaboração do questionário 6. Pesquisa de orientação 7. Coleta de dados 8. Apreciação ou crítica dos dados 9. Apuração 10. Análise de dados 11. Apresentação dos dados 12. Relatório final ## Definição do Universo - O Universo (População) a ser investigado deve ser definido precisamente sob pena de comprometer o resultado do levantamento. - Evitar expressões vagas como: municípios importantes, cidades populosas, municípios agrícolas, etc. - Precisar também a época do levantamento para evitar seleções tendenciosas de dias, semanas ou meses. ## Exame das informações disponíveis - Ao planejar uma pesquisa, deve-se como medida preliminar, reunir todo o material existente (mapas, apurações) relativo a levantamentos iguais ou assemelhados. - Se houver algum relatório disponível, as informações obtidas podem ser valiosas para evitar dificuldades ao estudo da dinâmica do fenômeno. ## Decisão sobre o tipo de levantamento - Os fatores __tempo__, __custo__ e __precisão__ determinam a realização de um levantamento censitário ou amostral. ## Obtenção das informações {.allowframebreaks} Há várias maneiras de se oberem informações. Dentre elas: ::: {.block} ### Por via postal __Potenciais desvantagens:__ * correios não atingem todas as localidades; * dificuldade de transporte no interior, levando demora para realizar o projeto; * extravio; * entrega atrasada; * incompreensão do informante sobre algum quesito do questionário; * demora no preenchimento do questionário; * falta de respostas; * inexistência de cadastros atualizados. ::: \framebreak ::: {.block} ### Por via postal __Potenciais vantagens:__ * economia: dispensa agentes e supervisores, o que significa imensa economia de tempo e dinheiro; * técnicas: o contato direto entre o órgão responsável pelo levantamento e o informante, evita a temível tendenciosidade de agentes mal instruídos; * sociais: o informante preenche o questionário no momento que lhe for mais propício. ::: \framebreak ::: {.block} ### Por telefone - Sob o aspecto econômico e de presteza, seria o ideal para obter informações. - Serve apenas para questões simples, de número reduzido de respostas imediatas. - __Desvantagens:__ pode atingir apenas uma parcela de indivíduos não representativa da população. ::: \framebreak ::: {.block} ### Entrevista direta Quando exercida com indispensável habilidade, é o meio mais eficiente para obter informações com as seguintes __vantagens:__ * maior porcentagem de questionários preenchidos; * garantia de melhor preenchimento; * obtém úteis informações suplementares; * orienta o informante sobre as questões. __Desvantagens:__ * maior tempo para cobertura de determinada área geográfica, pois nem sempre o informante atenderá o agente na primeira entrevista; * maior custo: treinamento do pessoal de campo e gasto com transporte. * tendenciosidade tanto do agente quanto do informante. ::: \framebreak ::: {.block} ### Entrevista direta O êxito da entrevista depende, em grande parte, do agente, que deve: * identificar-se, com documento hábil; * expor os objetivos da pesquisa; * explicar a importância da sua cooperação; * explicar que as informações são confidenciais; * usar linguagem comum; * não fazer ameaças de multas, nem prometer recompensas; * evitar perda de tempo; * comprometer-se a voltar noutra oportunidade, se necessário. ::: - __Pergunta:__ quais outras formas de obtenção de informações você conhece? ## Elaboração do questionário - É obra das mais delicadas, pois é o instrumento que conterá as informações necessárias para alcançar o objetivo da pesquisa. - Duas condições são indispensáveis: * ser especialista na matéria que vai constituir o objeto da pesquisa; * possuir a necessária experiência na técnica de investigação estatística. Os aspectos material e técnico do questionário são muito importantes. - Aspectos materiais: questionário em papel ou digital? - __Pergunta:__ quais os meios digitais que você conhece para elaboração de questionários e coleta de dados? ## Pesquisa de orientação Após termos os questionários prontos e os agentes habilitados, é conveniente realizar um levantamento experimental. Isto é importante, pois: * familiarizará o agente com a técnica de investigação; * testa o questionário; * verifica a reação do informante ao questionário; * obtém dados sobre o custo e o tempo de operação; * verifica a falta de respostas. ## Coleta de dados {.allowframebreaks} - A coleta de dados é aquela fase do trabalho estatístico que consiste na busca dos informes necessários à pesquisa que será desenvolvida. - Podemos considerar dois tipos de coleta: __direta__ e __indireta__. \framebreak ::: {.block} ### Coleta direta - Consiste no levantamento de __dados primários__ (ou __brutos__), isto é, dados que resultam da observação direta do fenômeno ou são obtidos mediante informações; não sofrem qualquer alteração. - O agente coletador ou investigador vai proceder à observação nas fontes originárias ou vale-se de informações relativas às mesmas. - Assim, os recenseamentos, os registros de nascimentos, casamentos, etc., constituem exemplos de coleta direta. ::: \framebreak ::: {.block} ### Coleta direta - A coleta direta pode ser: * __continua, espontânea ou automática:__ quando os dados são obtidos em virtude de determinados imperativos legais, de modo permanente. Tal tipo de coleta prescinde da presença do agente, pois os dados são fornecidos diretamente pelo informante. São exemplos: dados relativos a casamento, óbitos, etc. __Pergunta:__ nos dias de hoje quais outros exemplos temos de coleta automática? * __periódica ou reflexa:__ quando realizada em determinadas épocas. São exemplos: censos (demográficos, industriais e agrícolas); declarações de imposto de renda, etc. * __ocasional:__ quando os dados são coletados eventualmente, em virtude de uma circunstância especial. São exemplos: levantamento determinado por motivo de uma epidemia, de uma enchente, de uma crise econômica, etc. ::: \framebreak ::: {.block} ### Coleta indireta - Muitas vezes os dados primários são de difícil obtenção. - Em tais circunstâncias, a coleta passa a ser feita por dedução, baseada em dados coletados diretamente. - Outras vezes os dados são conseguidos mediante informações ou através de conhecimento de fatos relacionados com o que se pretende pesquisar. - Os dados assim obtidos são chamados de __dados elaborados__ (__secundários__), isto é, resultam da manipulação de dados primitivos. - Tal modalidade de obtenção de dados é a coleta indireta. - Exemplos: dados de casos de uma doença por município. + Através desta coleta, não sabemos quais indivíduos especificamente estão doentes, temos apenas a informação __agregada__ (__resumida__) por município. ::: ## Apreciação ou crítica dos dados - Após a coleta, os dados são submetidos a um exame chamado apreciação ou crítica, cuja a finalidade é a eliminação de possíveis erros cometidos, quer em decorrência de respostas incorretas, quer derivadas de deficiências dos próprios agentes. - Podemos considerar dois tipos de crítica: * __Externa__ ou __preliminar__, feita pelos próprios agentes coletadores, a fim de evitar devoluções de questionários mal preenchidos ou portadores de erros grosseiros. * __Interna__ ou __secundária __, executada pelo órgão responsável e corresponde a uma nova revisão mais minuciosa dos questionários. Se confirmada a existência de discrepâncias, caberá aos revisores decidir a respeito de uma possível devolução dos questionários para retificar. ## Apuração - Após liberados os boletins de possíveis erros, são os mesmos separados e classificados em grupos para a __codificação__, __contagem__ e __síntese__ dos resultados. - A tal estágio de trabalho estatístico dá-se o nome de __Apuração__ a qual, de acordo com o volume e natureza do levantamento efetuado, pode ser realizado de forma manual ou com o uso de computador. ## Análise dos dados - Um dos aspectos mais importantes é o da avaliação da precisão do levantamento, seja ele censitário ou amostral. + Confiabilidade do instrumento de medida (no caso, o questionário), dos agentes de coleta de dados, e das respostas dos entrevistados. - A referida avaliação para censos é efetuada através de amostragem. - Feita essa avaliação, é realizada a __análise de dados__ utilizando-se procedimentos estatísticos adequados. - Atualmente a maioria dos órgãos de pesquisa dispõe de equipamentos computacionais que facilitam a atuação do estatístico à medida em que pode se utilizar de _softwares_ estatísticos para efetivar a análise dos dados. ## Apresentação dos dados - Analisados os resultados e convenientemente sintetizados, os dados podem ser apresentados em __tabelas__ ou __representados graficamente__, interpretados por especialistas e divulgados sob várias maneiras (anuários, boletins, revistas, meio eletrônico, etc.). ## Relatório final - A cada pesquisa deve corresponder um relatório fazendo uma descrição geral da pesquisa: + região geográfica + natureza das informações coleadas + métodos de coleta de dados de amostragem + finalidade da pesquisa + custo + avaliação + planejamento + precisão ## Exercício - Com base na questão de pesquisa elaborada na última aula, especifique as fases de 1 a 6 do levantamento estatístico referente à sua pesquisa, e compartilhe com os colegas no \structure{Fórum do Moodle}. + Se possível, tente implementar a fase 7 __(coleta de dados)__, mesmo que com poucas unidades observacionais. + Ainda, se você conseguir implementar a fase 7, tente implementar as fases 8 e 9! ## Avisos \begin{columns}[c] \column{2.7in} \begin{figure}[!h] \begin{center} \includegraphics[width=0.9\columnwidth]{images/census_agent.jpg} \end{center} \end{figure} \column{1.6in} \begin{itemize}\setlength{\itemsep}{+2mm} \item \structure{Para casa:} \begin{itemize} \item Continuação do exercício. \item Ler os Cap. 3 de ``Estatística Descritiva I'' de Fernandez. \end{itemize} \end{itemize} \end{columns} \begin{itemize} \item \structure{Próxima aula:} \begin{itemize} \item Organização dos dados \end{itemize} \end{itemize} ## Por hoje é só! Bons estudos! ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='100%', out.height='80%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'lofi_02.jpg')) ``` <file_sep>## ----echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='100%', paged.print=FALSE---- plot(hp ~ mpg, data = mtcars, xlab = "Miles/(US) gallon", ylab = "Gross horsepower") ## ----echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='100%', paged.print=FALSE---- library(ggplot2) p <- ggplot(data = mtcars, mapping = aes(x = mpg, y = hp)) p + geom_point() + labs(x = "Miles/(US) gallon", y = "Gross horsepower") ## ----echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='100%', paged.print=FALSE---- plot(hp ~ mpg, data = mtcars, xlab = "Miles/(US) gallon", ylab = "Gross horsepower") ## ----echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='100%', paged.print=FALSE---- library(ggplot2) mtcars$am <- factor(mtcars$am, labels = c("Automatic", "Manual")) cbPalette <- c("#29BF12", "#FFBF00") p <- ggplot(data = mtcars, mapping = aes(x = mpg, y = hp, color = am)) p + geom_point(size = 2) + labs(x = "Miles/(US) gallon", y = "Gross horsepower", color = "Transmission") + theme_dark() + theme(legend.position = "top") + scale_colour_manual(values = cbPalette) ## ----echo=TRUE, eval=FALSE, message=FALSE, warning=FALSE----------------- ## install.packages("ggplot2") ## ----echo=TRUE, eval=FALSE, message=FALSE, warning=FALSE----------------- ## library(ggplot2) ## ----echo=TRUE, message=FALSE, warning=FALSE----------------------------- # install.packages("gapminder") library(gapminder) gapminder ## ----echo=TRUE, message=FALSE, warning=FALSE----------------------------- library(dplyr) gapminder <- gapminder %>% mutate(pop_m = pop/1e6) gapminder07 <- gapminder %>% filter(year == 2007) ## ----echo=TRUE, message=FALSE, warning=FALSE, fig.align='center', out.width="50%"---- p <- ggplot(data = gapminder07) p # print(p) ## ----echo=TRUE, message=FALSE, warning=FALSE, fig.align='center', out.width="50%"---- p <- ggplot(data = gapminder07, mapping = aes(x = gdpPercap, y = lifeExp)) p ## ----echo=TRUE, message=FALSE, warning=FALSE, fig.align='center', out.width="50%"---- p <- ggplot(data = gapminder07, mapping = aes(x = gdpPercap, y = lifeExp)) + geom_point() #<< p ## ----echo=TRUE, message=FALSE, warning=FALSE, fig.align='center', out.width="60%"---- # Histograma p <- ggplot(data = gapminder07, mapping = aes(x = lifeExp)) + geom_histogram() p ## ----echo=TRUE, message=FALSE, warning=FALSE, fig.align='center', out.width="60%"---- # Densidade estimada p <- ggplot(data = gapminder07, mapping = aes(x = lifeExp)) + geom_density() p ## ----echo=TRUE, message=FALSE, warning=FALSE, fig.align='center', out.width="60%"---- # Densidade estimada (grupos) p <- ggplot(data = gapminder07, mapping = aes(x = lifeExp, fill = continent)) + geom_density(alpha = 0.3) p ## ----echo=TRUE, message=FALSE, warning=FALSE, fig.align='center', out.width="60%"---- # Gráfico de barras p <- ggplot(data = gapminder07, mapping = aes(x = continent)) + geom_bar() p ## ----echo=TRUE, message=FALSE, warning=FALSE, fig.align='center', out.width="60%"---- # Boxplot p <- ggplot(data = gapminder07, mapping = aes(x = continent, y = pop_m)) + geom_boxplot() p ## ----echo=TRUE, message=FALSE, warning=FALSE, fig.align='center', out.width="60%"---- # Gráfico de violino p <- ggplot(data = gapminder07, mapping = aes(x = continent, y = pop_m)) + geom_violin() p ## ----echo=TRUE, message=FALSE, warning=FALSE, fig.align='center', out.width="60%"---- # Gráfico de linha p <- ggplot(data = gapminder[which(gapminder$country == "Brazil"),], mapping = aes(x = year, y = lifeExp)) + geom_line(size = 1) p ## ----echo=TRUE, message=FALSE, warning=FALSE, fig.align='center', out.width="62%"---- # Gráfico de linha p <- ggplot(data = gapminder[which(gapminder$continent == "Americas"),], mapping = aes(x = factor(year), y = lifeExp, group = country, color = country)) + geom_line(size = 1) + geom_point() p ## ----echo=FALSE, message=FALSE, warning=FALSE, fig.align='center', out.width="60%"---- p <- ggplot(data = gapminder07, mapping = aes(x = gdpPercap, y = lifeExp)) + geom_point() p ## ----echo=TRUE, message=FALSE, warning=FALSE, fig.align='center', out.width="65%"---- p <- ggplot(data = gapminder07, mapping = aes(x = gdpPercap, y = lifeExp, color = continent, size = pop_m)) + geom_point(alpha = 0.3) + geom_text(aes(label = country), color = "gray20") p ## ----echo=TRUE, message=FALSE, warning=FALSE, fig.align='center', out.width="65%"---- p + geom_smooth(method = "lm") ## ----echo=TRUE, message=FALSE, warning=FALSE, fig.align='center', out.width="65%"---- p + geom_smooth(mapping = aes(x = gdpPercap, y = lifeExp, color = NULL), method = "lm") ## ----echo=TRUE, message=FALSE, warning=FALSE, fig.align='center', out.width="65%"---- p + geom_smooth(mapping = aes(x = gdpPercap, y = lifeExp, color = NULL), method = "lm", formula = y ~ x + log(x), se = FALSE, color = "red") ## ----echo=TRUE, message=FALSE, warning=FALSE, fig.align='center', out.width="50%"---- p <- ggplot(data = gapminder, mapping = aes(x = gdpPercap, y = lifeExp)) + geom_point() + facet_grid(. ~ year) #<< p ## ----echo=TRUE, message=FALSE, warning=FALSE, fig.align='center', out.width="50%"---- p <- ggplot(data = gapminder, mapping = aes(x = gdpPercap, y = lifeExp, color = continent)) + geom_point() + facet_wrap(. ~ year) #<< p ## ----echo=TRUE, eval=FALSE, message=FALSE, warning=FALSE, fig.align='center', out.width="50%"---- ## gapminder$gdpPercap.cat <- cut(gapminder$gdpPercap, ## breaks = c(0, 1005, 3955, ## 12235, Inf), ## labels = c("Baixa-renda", ## "Renda média-baixa", ## "Renda média-alta", ## "Renda alta")) ## p <- ggplot(data = gapminder, ## mapping = aes(x = factor(year), ## y = lifeExp, fill = factor(year))) + ## geom_boxplot() + ## facet_grid(continent ~ gdpPercap.cat) #<< ## p ## ----echo=FALSE, eval=TRUE, message=FALSE, warning=FALSE, fig.align='center', out.width="70%"---- gapminder$gdpPercap.cat <- cut(gapminder$gdpPercap, breaks = c(0, 1005, 3955, 12235, Inf), labels = c("Baixa-renda", "Renda média-baixa", "Renda média-alta", "Renda alta")) p <- ggplot(data = gapminder, mapping = aes(x = factor(year), y = lifeExp, fill = factor(year))) + geom_boxplot() + facet_grid(continent ~ gdpPercap.cat) #<< p ## ----echo=TRUE, message=FALSE, warning=FALSE, fig.align='center', out.width="60%"---- p <- ggplot(data = gapminder07, mapping = aes(x = gdpPercap, y = lifeExp, color = continent, size = pop_m)) + geom_point(alpha = 0.3) p ## ----echo=TRUE, message=FALSE, warning=FALSE, fig.align='center', out.width="60%"---- p + labs(x = "Renda per capita (US$)", y = "Expectativa de vida (anos)", color = "Continente", size = "População/1 milhão") ## ----echo=FALSE, results='hide', fig.align='center', message=FALSE, warning=FALSE, out.width='100%', paged.print=FALSE---- p <- p + labs(x = "Renda per capita (US$)", y = "Expectativa de vida (anos)", color = "Continente", size = "População/1 milhão") ## ----echo=TRUE, message=FALSE, warning=FALSE, fig.align='center', out.width="100%"---- p + theme(legend.position = "none") ## ----echo=TRUE, message=FALSE, warning=FALSE, fig.align='center', out.width="100%"---- p + theme(legend.position = "top") ## ----echo=TRUE, eval=FALSE, message=FALSE, warning=FALSE, fig.align='center', out.width="50%"---- ## p + theme(text = element_text(color = "gray20"), ## legend.position = c("top"), # posição da legenda ## legend.direction = "horizontal", ## legend.justification = 0.1, # ponto de ancora para legend.position. ## legend.text = element_text(size = 11, color = "gray10"), ## axis.text = element_text(face = "italic"), ## axis.title.x = element_text(vjust = -1), ## axis.title.y = element_text(vjust = 2), ## axis.ticks.y = element_blank(), # element_blank() é como removemos elementos ## axis.line = element_line(color = "gray40", size = 0.5), ## axis.line.y = element_blank(), ## panel.grid.major = element_line(color = "gray50", size = 0.5), ## panel.grid.major.x = element_blank()) ## ----echo=FALSE, eval=TRUE, message=FALSE, warning=FALSE, fig.align='center', out.width="70%"---- p + theme(text = element_text(color = "gray20"), legend.position = c("top"), # posição da legenda legend.direction = "horizontal", legend.justification = 0.1, # ponto de ancora para legend.position. legend.text = element_text(size = 11, color = "gray10"), axis.text = element_text(face = "italic"), axis.title.x = element_text(vjust = -1), axis.title.y = element_text(vjust = 2), axis.ticks.y = element_blank(), # element_blank() é como removemos elementos axis.line = element_line(color = "gray40", size = 0.5), axis.line.y = element_blank(), panel.grid.major = element_line(color = "gray50", size = 0.5), panel.grid.major.x = element_blank()) ## ----echo=TRUE, eval=TRUE, message=FALSE, warning=FALSE, fig.align='center', out.width="60%"---- p + theme_bw() ## ----echo=TRUE, message=FALSE, warning=FALSE----------------------------- # install.packages("ggthemes") library(ggthemes) ## ----echo=TRUE, eval=TRUE, message=FALSE, warning=FALSE, fig.align='center', out.width="100%"---- # Wall Street Journal p + theme_wsj() ## ----echo=TRUE, eval=TRUE, message=FALSE, warning=FALSE, fig.align='center', out.width="100%"---- # The Economist p + theme_economist() ## ----echo=TRUE, eval=FALSE, message=FALSE, warning=FALSE----------------- ## ggsave("MeuPrimeiroGGPLOT.pdf") ## ggsave("MeuPrimeiroGGPLOT.png") ## ggsave("MeuPrimeiroGGPLOT.jpg", ## width = 4, height = 4) ## ----echo=TRUE, results='hide', fig.align='center', message=FALSE, warning=FALSE, out.width='100%', paged.print=FALSE---- # Considerações finais: exemplos # install.packages("jpeg") # install.packages("grid") library(jpeg) library(grid) img <- readJPEG("~/PintandoEBordando/ArquivosR/images/hans_rosling.jpg") # start plotting p <- ggplot(data = gapminder07, mapping = aes(x = gdpPercap, y = lifeExp, color = continent, size = pop_m)) + annotation_custom(rasterGrob(img, width = unit(1, "npc"), height = unit(1, "npc")), -Inf, Inf, -Inf, Inf) + scale_y_continuous(expand = c(0,0), limits = c(min(gapminder07$lifeExp) * 0.9, max(gapminder07$lifeExp) * 1.05)) + geom_point() + labs(x = "Renda per capita (US$)", y = "Expectativa de vida (anos)", color = "Continente", size = "População/1 milhão") + theme_bw() + theme(text = element_text(color = "gray20"), legend.position = c("top"), # posição da legenda legend.direction = "horizontal", legend.justification = 0.1, # ponto de ancora para legend.position. legend.text = element_text(size = 11, color = "gray10"), axis.text = element_text(face = "italic"), axis.title.x = element_text(vjust = -1), axis.title.y = element_text(vjust = 2), axis.ticks.y = element_blank(), # element_blank() é como removemos elementos axis.line = element_line(color = "gray40", size = 0.5), axis.line.y = element_blank(), panel.grid.major = element_line(color = "gray50", size = 0.5), panel.grid.major.x = element_blank() ) p ## ----echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='70%', paged.print=FALSE---- # Considerações finais: exemplos # install.packages("jpeg") # install.packages("grid") library(jpeg) library(grid) img <- readJPEG("~/PintandoEBordando/ArquivosR/images/hans_rosling.jpg") # start plotting p <- ggplot(data = gapminder07, mapping = aes(x = gdpPercap, y = lifeExp, color = continent, size = pop_m)) + annotation_custom(rasterGrob(img, width = unit(1, "npc"), height = unit(1, "npc")), -Inf, Inf, -Inf, Inf) + scale_y_continuous(expand = c(0,0), limits = c(min(gapminder07$lifeExp) * 0.9, max(gapminder07$lifeExp) * 1.05)) + geom_point() + labs(x = "Renda per capita (US$)", y = "Expectativa de vida (anos)", color = "Continente", size = "População/1 milhão") + theme_bw() + theme(text = element_text(color = "gray20"), legend.position = c("top"), # posição da legenda legend.direction = "horizontal", legend.justification = 0.1, # ponto de ancora para legend.position. legend.text = element_text(size = 11, color = "gray10"), axis.text = element_text(face = "italic"), axis.title.x = element_text(vjust = -1), axis.title.y = element_text(vjust = 2), axis.ticks.y = element_blank(), # element_blank() é como removemos elementos axis.line = element_line(color = "gray40", size = 0.5), axis.line.y = element_blank(), panel.grid.major = element_line(color = "gray50", size = 0.5), panel.grid.major.x = element_blank() ) p ## ----echo=TRUE, fig.align='center', message=FALSE, warning=FALSE, out.width='60%', paged.print=FALSE---- # Considerações finais: exemplos - interatividade p <- ggplot(data = gapminder07, mapping = aes(x = gdpPercap, y = lifeExp, color = continent, size = pop_m)) + geom_point() + labs(x = "Renda per capita (US$)", y = "Expectativa de vida (anos)", color = "Continente", size = "População/1 milhão") + theme_bw() p ## ----echo=TRUE, fig.align='center', message=FALSE, warning=FALSE, out.width='100%', paged.print=FALSE---- # Considerações finais: exemplos - interatividade # install.packages("plotly") library(plotly) ggplotly(p) ## ----echo=TRUE, eval=FALSE, message=FALSE, warning=FALSE----------------- ## install.packages("rmarkdown") ## ----echo=TRUE, eval=FALSE, message=FALSE, warning=FALSE----------------- ## library(rmarkdown) ## ---- message=FALSE------------------------------------------------------ summary(gapminder07$pop_m) ## ---- echo=FALSE--------------------------------------------------------- summary(gapminder07$pop_m) ## ---- eval=FALSE--------------------------------------------------------- ## summary(gapminder07$pop_m) ## ---- echo=FALSE, results='asis'----------------------------------------- library(knitr) mod1 <- lm(lifeExp ~ gdpPercap, data = gapminder07) kable(summary(mod1)$coef, format = "html") <file_sep># MAT02018 Material de aula da disciplina "ESTATÍSTICA DESCRITIVA" do curso de Bacharelado em Estatística da UFRGS. <file_sep>--- title: "MAT02018 - Estatística Descritiva" subtitle: "Distribuição de Frequências: `R`, construção de tabelas e um minuto de história" fontsize: 10pt author: | | <NAME> | `<EMAIL>` institute: | | \textsc{Universidade Federal do Rio Grande do Sul} | \textsc{Instituto de Matemática e Estatística} | \textsc{Departamento de Estatística} date: | | Porto Alegre, 2022 --- # Complementa`R` ## Complementa`R` {.allowframebreaks} - Nesta aula são apresentadas algumas poucas funções em `R` relacionadas a discussão das nossas aulas de \structure{Distribuição de Frequências}. - Para tal, vamos utilizar o exemplo original de __Bussab e Moretin (2010)__\footnote{Bussab, W. O e Morettin, P. A. {\bf Estatística Básica}, Saraiva, 2010.} sobre os dados dos empregados da seção de orçamentos da Companhia MB. ## Complementa`R` {.allowframebreaks} - A planilha eletrônica correspondente encontra-se no arquivo `companhia_mb.xlsx` \structure{(no Moodle)}. - Vamos começar __carregando os dados__ para o `R`. + Existem __várias formas__ de se carregar diferentes __arquivos de dados__ no `R`. + Como arquivo de interesse encontra-se no formato do __Excel (xlsx)__, vamos utilizar a função `read_excel` do pacote `readxl`. + Caso você não tenha o pacote, instale-o: `install.packages("readxl")`. ## Complementa`R` {.allowframebreaks} ```{r carrega-dados0, echo=TRUE, eval=FALSE, warning=FALSE, message=FALSE} # install.packages("readxl") library(readxl) dados <- read_excel(path = "companhia_mb.xlsx") ``` ```{r carrega-dados1, echo=FALSE, warning=FALSE, message=FALSE, purl=FALSE} # install.packages("readxl") library(readxl) dados <- read_excel(path = here::here("data", "companhia_mb.xlsx")) ``` ```{r carrega-dados2, warning=FALSE, message=FALSE} class(dados) # classe do objeto dados dim(dados) # dimensão do objeto dados ``` \framebreak - Note que o objeto `dados` é uma tabela de dados bruto. \footnotesize ```{r carrega-dados3, warning=FALSE, message=FALSE} head(dados) # apresenta as primeiras linhas do objeto dados ``` \framebreak \normalsize - A função `table` retorna contagens dos valores de cada variável, e portanto, podemos utilizar esta função para a apuração dos dados, bem como para computar as frequências. \footnotesize ```{r freqs, warning=FALSE, message=FALSE} table(dados$`Estado Civil`) table(dados$`Grau de Instrução`) table(dados$`N de Filhos`) ``` \framebreak \normalsize - A função `cut` pode ser utilizada para criar uma nova variável que expressa a antiga variável em classes. ```{r freqs2, warning=FALSE, message=FALSE} dados$Idade.classes <- cut(x = dados$Idade, breaks = c(20, 29, 39, 49), include.lowest = TRUE, right = FALSE) table(dados$Idade.classes) ``` - Para casa: especifique de diferentes formas os argumentos `breaks`, `include.lowest`, `right` da função `table` e a avalie os seus resultados. \framebreak - Uma forma de calcular as frequência relativas é dividindo o __vetor__ de frequências pelo tamanho da amostra (ou conjunto de dados). ```{r freqs3, warning=FALSE, message=FALSE} table(dados$`Estado Civil`) / 36 table( dados$`Grau de Instrução`)/length(dados$`Grau de Instrução` ) ``` \framebreak - Uma outra forma de se obter as frequências relativas é utilizando a função `prop.table`. ```{r freqs4, warning=FALSE, message=FALSE} prop.table(x = table(dados$`N de Filhos`)) ``` \framebreak - Para obter as porcentagens, basta multiplicar as frequências relativas por 100. ```{r porcentagem, warning=FALSE, message=FALSE} prop.table(x = table(dados$Idade.classes)) * 100 ``` - Se você quiser, pode arredondar os resultados com a função `round`. ```{r porcentagem2, warning=FALSE, message=FALSE} round(x = prop.table(x = table(dados$Idade.classes)) * 100, digits = 2) ``` \framebreak - As frequências acumuladas podem ser obtidas com uma função de somas cumulativas, a função `cumsum`. ```{r freqcum, warning=FALSE, message=FALSE} cumsum(x = table(dados$`Grau de Instrução`)) cumsum(x = prop.table(x = table(dados$`Grau de Instrução`))) ``` \framebreak ```{r freqcum2, warning=FALSE, message=FALSE} cumsum(x = prop.table(x = table(dados$`N de Filhos`)) * 100) cumsum( round( prop.table(x = table(dados$Idade.classes)) * 100, digits = 2)) ``` \framebreak - Você pode juntar as frequências absolutas, relativas, acumuladas e porcentagens em um `data.frame` para apresentar em forma de tabela. \footnotesize ```{r freqtab, warning=FALSE, message=FALSE} df.freq <- data.frame( Idade = unique(dados$Idade.classes), Freq = as.numeric(table(dados$Idade.classes)), FreqRel = as.numeric(prop.table(table(dados$Idade.classes))), Porcentagem = as.numeric(prop.table(table(dados$Idade.classes)) * 100), FreqAcumulada = as.numeric(cumsum(table(dados$Idade.classes))), FreqRelAcumulada = as.numeric(cumsum(prop.table(table(dados$Idade.classes))))) ``` \framebreak \footnotesize ```{r freqtabprint, warning=FALSE, message=FALSE} df.freq ``` \framebreak \normalsize - Existem outras formas de construir uma tabela de frequências. - Uma delas é utilizando a função `freq` do pacote `summarytools`. \scriptsize ```{r freqtab2, warning=FALSE, message=FALSE} # install.packages("summarytools") summarytools::freq(dados$`Grau de Instrução`) ``` # Construção de tabelas ## Construção de tabelas - Nesta seção são apresentadas as normas que devem ser seguidas na elaboração de tabelas. - Tais normas devem ser empregadas em relatórios, documentos acadêmicos, científicos, etc. - Estas normas são apresentadas na publicação \structure{Normas de apresentação tabular (IBGE, 1993)}, que encontra-se no Moodle. ## Tabelas - __Tabela__ é uma forma não discursiva de apresentar informações, das quais o dado numérico se destaca como informação central. ```{r fig-tabela, fig.align='center',cache=TRUE, message=FALSE, echo=FALSE, out.width="85%", purl=FALSE} knitr::include_graphics(here::here('images', 'tabelas_construcao', 'tabs_construcao_1.png')) ``` ## Principais elementos das tabelas {.allowframebreaks} - __Número__ é o identificador numérico da tabela, em um conjunto de tabelas. + Deve ser dado em algarismos arábicos e deve suceder a palavra __Tabela__. - __Título__ explica o tipo de dado que a tabela contém. + Deve ser colocado acima dos dados, sem ponto final. - __Cabeçalho__ especifica o conteúdo de cada coluna. - __Indicador de linha__ especifica o conteúdo de cada linha. - __Dado numérico__ é a quantificação do fato observado. - __Moldura__ é o conjunto de traços que dão estrutura aos dados numéricos e aos termos necessários à sua compreensão. \framebreak + Tabelas devem ser delimitadas, no alto e embaixo, por traços horizontais. + Tabelas __não__ devem ser delimitadas, à direita e à esquerda, por traços verticais. + O cabeçalho deve ser delimitado por traços horizontais. + Para maior clareza, podem ser feitos traços verticais no interior da tabela separando as colunas. + Podem ser feitos traços verticais no interior do cabeçalho para separar o que as colunas contém. \framebreak ```{r fig-moldura, fig.align='center', cache=TRUE, message=FALSE, echo=FALSE, out.width="100%", purl=FALSE} knitr::include_graphics(here::here('images', 'tabelas_construcao', 'tabs_construcao_3.png')) ``` \framebreak - __Célula__ é o espaço na tabela resultante do cruzamento de uma linha com uma coluna. + Nenhuma célula deveria ficar em branco. Quando, por algum motivo, a célula não apresenta um dado numérico, esta não deve ficar em branco. Neste caso, são recomendados os sinais convencionais propostos pelo IBGE, tais como: - ".." Nãos se aplica dado numérico. - "..." Dado numérico não disponível. - "x" Dado omitido a fim de evitar a individualização da informação. - "0"; "0,0"; "0,00" Dado numérico igual a zero resultante de arredondamento de um dado numérico originalmente positivo. \framebreak ```{r fig-elementos_tab, fig.align='center', cache=TRUE, echo=FALSE, out.width="100%", purl=FALSE} knitr::include_graphics(here::here('images', 'tabelas_construcao', 'tabs_construcao_2.png')) ``` ## Elementos eventuais {.allowframebreaks} - __Fonte__ identifica a pessoa física ou jurídica responsável pelos dados. - A fonte deve ser colocada na primeira linha do rodapé da tabela, precedida da palavra __Fonte__. - __Não__ se indica a fonte nos casos em que os dados foram obtidos pelo pesquisador, ou pelo grupo de pesquisadores, ou pela instituição que apresenta a tabela. - __Notas__ são informações de natureza geral que servem para esclarecer o conteúdo das tabelas ou para explicar o método utilizado no levantamento dos dados. - As notas devem ser colocadas no rodapé da tabela, logo após a fonte e numeradas, se for o caso. \framebreak ```{r fig-elementos_tab2, fig.align='center', cache=TRUE, echo=FALSE, out.width="100%", purl=FALSE} knitr::include_graphics(here::here('images', 'tabelas_construcao', 'tabs_construcao_4.png')) ``` # Um minuto de história {.allowframebreaks} - No livro __"The Seven Pillars of Statistical Wisdom"__, <NAME> apresenta __sete ideias básicas de estatística__ que foram revolucionárias quando introduzidas, e que permanecem como um avanço conceitual importante e profundo. + Segundo o autor, estas ideias básicas articulam o __núcleo intelectual central do raciocínio estatístico__. - A primeira das sete ideias básicas apresentada no livro é a __agregação__, ou seja, a __compactação__/__redução__ dos dados para gerar informação. O que o autor nos mostra é que este princípio (o resumo estatístico) é tão antigo quanto a escrita. \framebreak - A seguir são apresentadas uma __tabuleta de argila suméria datada de cerca de 3000 aC__, uma reconstrução de uma destas tabuletas com números modernos. + A tabuleta apresenta contagens (frequências) de dois tipos de mercadoria, possivelmente o rendimento de duas safras em três anos. \framebreak ```{r fig-sumerian, fig.align='center', cache=TRUE, echo=FALSE, out.width="100%", purl=FALSE} knitr::include_graphics(here::here('images', 'tabelas_construcao', 'Sumerian_tablet.png')) ``` \framebreak - Versão moderna da tabuleta de argila suméria. ```{r fig-sumerian2, fig.align='center', cache=TRUE, message=FALSE, echo=FALSE, out.width="100%", purl=FALSE} knitr::include_graphics(here::here('images', 'tabelas_construcao', 'sumerian_tablet_2.png')) ``` ## Para casa 1. Resolver os exercícios do Capítulo 4.6 do livro __Fundamentos de Estatística__\footnote{<NAME>. {\bf Fundamentos de Estatística}, Atlas, 2019, pg. 39-40.} (disponível no Sabi+). 2. Para o seu levantamento estatístico, monte um pequeno relatório de pesquisa apresentando tabelas de resultados. Utilize os passos de construção de tabelas apresentados nesta aula. Compartilhe no Fórum Geral do Moodle. ## Próxima aula - Avaliação I. ## Por hoje é só! \begin{center} {\bf Bons estudos!} \end{center} ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='50%', out.height='50%', paged.print=FALSE} knitr::include_graphics(here::here('images', 'Statistically-Insignificant-mickey.jpg')) ``` <file_sep>--- title: "MAT02018 - Estatística Descritiva" subtitle: "Medidas de forma" fontsize: 10pt author: | | <NAME> | `<EMAIL>` institute: | | \textsc{Universidade Federal do Rio Grande do Sul} | \textsc{Instituto de Matemática e Estatística} | \textsc{Departamento de Estatística} date: | | Porto Alegre, 2022 bibliography: estatistica-descritiva.bib csl: associacao-brasileira-de-normas-tecnicas-ufrgs-initials.csl link-citations: yes --- ```{r setup, include=FALSE, purl=FALSE} options(knitr.kable.NA = '-') library(dplyr) library(knitr) ``` # Introdução - Nas últimas semanas dedicamos a nossa atenção para resumir numericamente certas características da distribuição de frequências. - No entanto, as medidas de localização e variabilidade nem sempre dão conta de descrever todas as características de uma distribuição. - Nestas breves notas de aula, vamos discutir duas \structure{medidas de forma:} os coeficientes de \structure{assimetria} e \structure{curtose}. - Além disso, vamos apresentar propriedades da média e variância. # Assimetria {.allowframebreaks} - A medida denominada \structure{coeficiente de assimetria} mede o grau de assimetria exibido pela distribuição dos dados. - A figura abaixo apresenta uma \structure{distribuição assimétrica}. ```{r echo=FALSE, message=FALSE, warning=FALSE, results='asis', fig.align='center', out.width="70%"} library(fGarch) r <- rsnorm(1000, xi = 5) layout(mat = matrix(c(1, 2), 2, 1, byrow = TRUE), height = c(1, 8)) par(mar = c(0, 3.1, 1.1, 2.1)) boxplot(r, horizontal = TRUE, ylim = c(-2,5), xaxt = "n" , col = rgb(0.8,0.8,0,0.5) , frame = F) par(mar=c(4, 3.1, 1.1, 2.1)) hist(r, xlab = "x", ylab = "Frequência", col = rgb(0,0.25,0.25,0.5), border = "white", main = "", xlim = c(-2,5)) abline(v = mean(r), lty = 2, col = "red", lwd = 2) text(0.3, 200, "Média") ``` \framebreak - O histograma revela que há mais observações abaixo da média. - Veja que a mediana (apresentada no _boxplot_) está posicionada à esquerda da média (logo, mais de 50% dos valores da distribuição estão abaixo da média). - Também é possível notar que a classe modal (faixa de maior frequência; maior retângulo do histograma) está à esquerda da mediana (e portanto, à esquerda da média). - Este comportamento é conhecido como \structure{assimetria positiva}^[Quando $\bar{x} > Md > Mo$ dizemos que uma distribuição é assimétrica positiva.]. ## Assimetria {.allowframebreaks} - Já quando a média é menor que a mediana os dados apresentam \structure{assimetria negativa}^[Quando $\bar{x} < Md < Mo$ dizemos que uma distribuição é assimétrica negativa.], como na figura a seguir. ```{r echo=FALSE, message=FALSE, warning=FALSE, results='asis', fig.align='center', out.width="70%"} library(fGarch) set.seed(2010) r <- rsnorm(1000, xi = -5) layout(mat = matrix(c(1, 2), 2, 1, byrow = TRUE), height = c(1, 8)) par(mar = c(0, 3.1, 1.1, 2.1)) boxplot(r, horizontal = TRUE, ylim = c(-5,2), xaxt = "n" , col = rgb(0.8,0.8,0,0.5) , frame = F) par(mar=c(4, 3.1, 1.1, 2.1)) hist(r, xlab = "x", ylab = "Frequência", col = rgb(0,0.25,0.25,0.5), border = "white", main = "", xlim = c(-5,2)) abline(v = mean(r), lty = 2, col = "red", lwd = 2) text(-0.3, 200, "Média") ``` ## Assimetria {.allowframebreaks} - O \structure{coeficiente de assimetria}^[Existem outras propostas de mensuração da assimetria na literatura. Nestas notas vamos nos ater a apenas uma proposta.] é calculado primeiro somando o __cubo dos desvios da média__ e, então, dividindo pelo produto do __cubo do desvio padrão__ pelo número de observações: $$ b_1 = \frac{\sum_{i=1}^n{(x_i - \bar{x})^3}}{ns^3}. $$ - Quando \structure{$b_1 = 0$} os dados são simétricos em torno da média; - Quando \structure{$b_1 > 0$} os dados apresentam assimetria positiva; - Quando \structure{$b_1 < 0$} os dados apresentam assimetria negativa. ## Assimetria {.allowframebreaks} - \structure{Exemplo:} considere mais uma vez que \structure{$x$} representa a largura de pétala de 30 flores do tipo Íris. Observando os gráficos de boxplot e histograma, é notável que a distribuição é assimétrica positiva. ```{r echo=FALSE, message=FALSE, warning=FALSE, results='asis', fig.align='center', out.width="70%"} set.seed(1020) x <- sample(x = iris$Petal.Width[iris$Species == "setosa"], size = 30, replace = FALSE) layout(mat = matrix(c(1, 2), 2, 1, byrow = TRUE), height = c(1, 8)) par(mar = c(0, 3.1, 1.1, 2.1)) boxplot(x, horizontal = TRUE, ylim = c(0.1,0.6), xaxt = "n" , col = rgb(0.8,0.8,0,0.5) , frame = F) par(mar=c(4, 3.1, 1.1, 2.1)) hist(x, xlab = "x", ylab = "Frequência", col = rgb(0,0.25,0.25,0.5), border = "white", main = "", xlim = c(0.1,0.6)) abline(v = mean(x), lty = 2, col = "red", lwd = 2) text(0.3, 15, "Média") ``` ## Assimetria {.allowframebreaks} - Vamos utilizar uma planilha para auxiliar na organização das operações necessárias para o cálculo do coeficiente de assimetria \structure{$b_1$}. \footnotesize ```{r echo=FALSE, message=FALSE, warning=FALSE, purl=FALSE} mat <- as.data.frame(x) names(mat) <- c("$x_i$") mat$"$(x_i-\\bar{x})$" <- mat$"$x_i$" - mean(mat$"$x_i$") mat$"$(x_i-\\bar{x})^2$" <- mat$"$(x_i-\\bar{x})$"^2 mat$"$(x_i-\\bar{x})^3$" <- mat$"$(x_i-\\bar{x})$"^3 aux <- colSums(mat) mat <- rbind(mat, aux) aux <- c(rep(NA, 30), "Soma") mat <- cbind(aux, mat) names(mat)[1] <- "-" options(knitr.kable.NA = '') knitr::kable(mat, escape = FALSE, align = 'c', digits = c(0, 1, 3, 3, 4), format.args = list(decimal.mark = ","), format = "markdown") # kable_styling(font_size = 9) %>% # row_spec(6, bold = T) ``` \framebreak \normalsize Assim, temos + $\bar{x} = 7,8/30 = 0,26$; + $s^2 = \frac{\sum_{i=1}^n{(x_i - \bar{x})^2}}{n-1} = \frac{0,372}{29} = 0,0128$; + $s = \sqrt{s^2} = 0,1133$; + $b_1 = \frac{\sum_{i=1}^n{(x_i - \bar{x})^3}}{ns^3} = \frac{0,0406}{30\times (0,1133)^3} = 0,93 > 0$, confirmando a assimetria positiva que o gráfico já indicava. # Curtose {.allowframebreaks} - A \structure{curtose} mede o \structure{alongamento da distribuição}. - Sua definição é semelhante à da assimetria^[Mais uma vez, chamamos a atenção para o fato que existem outras propostas de medir a curtose, porém vamos discutir apenas uma delas.], com a ressalva de que a __quarta potência__ é usada em vez da terceira: $$ b_2 = \frac{\sum_{i=1}^n{(x_i - \bar{x})^4}}{ns^4}. $$ ## Curtose {.allowframebreaks} - Distribuições com um elevado grau de alongamento são chamadas de \structure{leptocúrticas} e têm valores de \structure{curtose acima de 3}. ```{r echo=FALSE, message=FALSE, warning=FALSE, results='asis', fig.align='center', out.width="70%"} library(rmutil) set.seed(2010) m <- rnorm(1000) p <- rt(1000, df = 8) l <- rlaplace(1000, s = 0.25) hist(l, xlab = "x", ylab = "Frequência", col = rgb(0,0.25,0.25,0.5), border = "white", main = "", breaks = 30, xlim = c(-3,3)) ``` \framebreak - Distribuições achatadas são chamadas \structure{platicúrticas} e têm valores para \structure{curtose inferiores a 3}. ```{r echo=FALSE, message=FALSE, warning=FALSE, results='asis', fig.align='center', out.width="70%"} hist(p, xlab = "x", ylab = "Frequência", col = rgb(0,0.25,0.25,0.5), border = "white", main = "", breaks = 30, xlim = c(-3,3)) ``` \framebreak - No caso em que a \structure{curtose é igual a 3}, a distribuição é chamada \structure{mesocúrtica}. ```{r echo=FALSE, message=FALSE, warning=FALSE, results='asis', fig.align='center', out.width="70%"} hist(m, xlab = "x", ylab = "Frequência", col = rgb(0,0.25,0.25,0.5), border = "white", main = "", breaks = 30, xlim = c(-3,3)) ``` ## Curtose {.allowframebreaks} ### Origem dos termos ```{r fig.align='center', cache=TRUE, message=FALSE, echo=FALSE, out.width="70%", purl=FALSE} knitr::include_graphics(here::here("images", "student_lepto_plati.png")) ``` \footnotesize _Student_ (em verdade, <NAME>) em seu artigo "_Errors of Routine Analysis_" de 1927, apresenta em uma nota de rodapé a explicação para os termos \structure{platicúrtica} e \structure{leptocúrtica}. - Livre tradução: _Eu mesmo tenho em mente o significado das palavras da __memoria technica__ acima, onde a primeira figura representa o ornitorrinco (__platypus__), e a segunda cangurus, conhecidos por "lebrar" ("__lepping__"), e portanto, talvez, com igual razão, devam ser lebres!_ ## Curtose {.allowframebreaks} \normalsize - \structure{Exemplo:} novamente considere os dados de 30 flores de iris. A variável \structure{$x$} agora representa o comprimento de pétala de 30 flores do tipo Íris. Observando o histograma de \structure{$x$}, a distribuição parece ser __leptocúrtica__. ```{r echo=FALSE, message=FALSE, warning=FALSE, results='asis', fig.align='center', out.width="70%"} set.seed(1020) x <- sample(x = iris$Petal.Length[iris$Species == "setosa"], size = 30, replace = FALSE) layout(mat = matrix(c(1, 2), 2, 1, byrow = TRUE), height = c(1, 8)) par(mar = c(0, 3.1, 1.1, 2.1)) boxplot(x, horizontal = TRUE, ylim = c(1,2), xaxt = "n" , col = rgb(0.8,0.8,0,0.5) , frame = F) par(mar=c(4, 3.1, 1.1, 2.1)) hist(x, xlab = "x", ylab = "Frequência", col = rgb(0,0.25,0.25,0.5), border = "white", main = "", xlim = c(1,2)) abline(v = mean(x), lty = 2, col = "red", lwd = 2) text(1.6, 12, "Média") ``` \framebreak - Vamos utilizar uma planilha para auxiliar na organização das operações necessárias para o cálculo do coeficiente de curtose \structure{$b_2$}. \footnotesize ```{r echo=FALSE, message=FALSE, warning=FALSE, purl=FALSE} mat <- as.data.frame(x) names(mat) <- c("$x_i$") mat$"$(x_i-\\bar{x})$" <- mat$"$x_i$" - mean(mat$"$x_i$") mat$"$(x_i-\\bar{x})^2$" <- mat$"$(x_i-\\bar{x})$"^2 mat$"$(x_i-\\bar{x})^4$" <- mat$"$(x_i-\\bar{x})$"^4 aux <- colSums(mat) mat <- rbind(mat, aux) aux <- c(rep(NA, 30), "Soma") mat <- cbind(aux, mat) names(mat)[1] <- "-" options(knitr.kable.NA = '') knitr::kable(mat, escape = FALSE, align = 'c', digits = c(0, 1, 3, 3, 4), format.args = list(decimal.mark = ","), format = "markdown") # kable_styling(font_size = 9) %>% # row_spec(6, bold = T) ``` \framebreak \normalsize Assim, temos + $\bar{x} = 44/30 = 1,47$; + $s^2 = \frac{\sum_{i=1}^n{(x_i - \bar{x})^2}}{n-1} = \frac{1,047}{29} = 0,0361$; + $s = \sqrt{s^2} = 0,19$; + $b_2 = \frac{\sum_{i=1}^n{(x_i - \bar{x})^4}}{ns^4} = \frac{0,1366}{30\times (0,19)^3} = 3,49 > 3$, confirmando o que o gráfico da distribuição já indicava (distribuição __leptocúrtica__). # Propriedades da média e variância {.allowframebreaks} - Sejam \structure{$x_1,x_2,\ldots,x_n$} valores observados da variável \structure{$x$}, tal que $$ \bar{x} = \frac{1}{n}\sum_{i=1}^n{x_i}, \quad s^2_x = \frac{1}{n-1}\sum_{i=1}^n{(x_i - \bar{x})^2} $$ são a média, e a variância da variável $x$. \framebreak \footnotesize - \structure{Exemplo (relembrando):} considere o peso em quilos de cinco ovelhas. ```{r echo=FALSE, message=FALSE, warning=FALSE} library(SemiPar) library(knitr) data(pig.weights) kable(t(pig.weights$weight[pig.weights$num.weeks == 1][1:5]), col.names = paste("Ovelha",1:5), format.args = list(decimal.mark = ","), format = "markdown") ``` - Temos que o peso médio e a variância são $$ \bar{peso} = 23,5; \quad s^2_{peso} = 0,875.s^2_{peso} = 0,875. $$ \normalsize \framebreak - Defina a transformação linear \structure{$y_i$} de \structure{$x_i$} $$ y_i = ax_i + b, i = 1, 2, \ldots, n, $$ em que \structure{$a$} e \structure{$b$} \structure{são constantes}. - Então, temos como \structure{propriedades da média e variância}: $$ \bar{y} = a\bar{x} + b,\quad \mbox{e}\quad s^2_y = a^2s^2_x. $$ \framebreak - Logo, $s_y = \sqrt{s^2_y} = \sqrt{a^2s^2_x} = as_x$. + Ou seja, temos que a média e variância da variável transformada pode ser expressa em função da média, variância e as constantes \structure{$a$} e \structure{$b$} da variável original. - Note também que a variância __não é influenciada pela constante__ \structure{$b$}. \framebreak - É fácil demonstrar tais propriedades, partindo da definição da média e variância e aplicando a transformação. \footnotesize \begin{eqnarray*} \bar{y} &=& \frac{1}{n}\sum_{i=1}^n{y_i} \\ &=& \frac{1}{n}\sum_{i=1}^n{(ax_i + b)} \\ &=& \frac{1}{n}\left(a\sum_{i=1}^n{x_i} + n\times b\right) \\ &=& a\frac{\sum_{i=1}^n{x_i}}{n} + n\times \frac{b}{n}\\ &=& a\bar{x} + b, \end{eqnarray*} e \framebreak \begin{eqnarray*} s^2_y &=& \frac{1}{n-1}\sum_{i=1}^n{(y_i - \bar{y})^2} \\ &=& \frac{1}{n-1}\sum_{i=1}^n{\left[ax_i + b - (a\bar{x} + b)\right]^2} \\ &=& \frac{1}{n-1}\sum_{i=1}^n{\left[ax_i - a\bar{x} + b - b)\right]^2} \\ &=& \frac{1}{n-1}\sum_{i=1}^n{\left[a(x_i - \bar{x})\right]^2} \\ &=& \frac{1}{n-1}\sum_{i=1}^n{\left[a^2(x_i - \bar{x})^2\right]} \\ &=& a^2\frac{\sum_{i=1}^n{(x_i - \bar{x})^2}}{n-1} \\ &=& a^2s^2_x. \end{eqnarray*} \normalsize \framebreak ```{r fig.margin = TRUE, message=FALSE, echo=FALSE, out.width="5%", purl=FALSE, fig.align='right'} knitr::include_graphics(here::here("images", "ovelha.jpeg")) ``` - \structure{Exemplos (1):} considere um conjunto de 48 ovelhas. A distribuição do peso deste grupo de animais é apresentada a seguir. ```{r echo=FALSE, message=FALSE, warning=FALSE, results='asis', fig.align='center', out.width="60%"} library(SemiPar) data(pig.weights) hist(pig.weights$weight[pig.weights$num.weeks == 1], xlab = "Peso de 48 ovelhas", ylab = "Frequência", col = rgb(0,0,1,0.5), border = "white", main = "") abline(v = mean(pig.weights$weight[pig.weights$num.weeks == 1]), lty = 2, col = "red", lwd = 2) text(28, 15, "Média = 25 kg\n s = 2,47 kg") ``` \framebreak ```{r message=FALSE, echo=FALSE, out.width="5%", purl=FALSE, fig.align='right'} knitr::include_graphics(here::here("images", "ovelha3.jpg")) ``` - Suponha agora, que após a tosa, cada ovelha "perde" \structure{exatamente} 8 kg. Após a tosa, a distribuição do peso é mais uma vez apresentada. ```{r echo=FALSE, message=FALSE, warning=FALSE, results='asis', fig.align='center', out.width="60%"} hist(pig.weights$weight[pig.weights$num.weeks == 1] - 8, xlab = "Peso de 48 ovelhas depois da tosa", ylab = "Frequência", col = rgb(1,0,0,0.5), border = "white", main = "") abline(v = mean(pig.weights$weight[pig.weights$num.weeks == 1] - 8), lty = 2, col = "red", lwd = 2) text(20, 15, "Média = 17 kg\n s = 2,47 kg") ``` \framebreak - Note que, se o peso antes da tosa é representado por $x$, então podemos escrever o peso após a tosa como $y = ax + b$, em que $a = 1$ e $b = - 8$. - Percebemos que a média diminui __exatamente__ 8 kg em relação a média do peso antes da tosa^[$\bar{y} = (1)\bar{x} - 8 = 25 - 8 = 17$.]. + Já a variância após a tosa é a mesma que a variância do peso antes da tosa^[$s^2_{y} = (1)^2s^2_{x} = (1)(2,47)^2 = (2,47)^2$.]. ## Propriedades da média e variância {.allowframebreaks} - Comparando as distribuições de $x$ (peso antes da tosa) e $y$ (peso após a tosa) percebemos que a forma da distribuição não muda, mas a distribuição é deslocada (em oito unidades) para a esquerda (constante $b$ negativa). ```{r echo=FALSE, message=FALSE, warning=FALSE, results='asis', fig.align='center', out.width="70%"} hist(pig.weights$weight[pig.weights$num.weeks == 1] - 8, xlab = "Peso de 48 ovelhas", ylab = "Frequência", col = rgb(1,0,0,0.5), border = "white", main = "", xlim = c(8, 34)) hist(pig.weights$weight[pig.weights$num.weeks == 1], col = rgb(0,0,1,0.5), border = "white", add = TRUE) abline(v = c(mean(pig.weights$weight[pig.weights$num.weeks == 1] - 8), mean(pig.weights$weight[pig.weights$num.weeks == 1])), lty = 2, col = "red", lwd = 2) legend("topright", fill = c(rgb(1,0,0,0.5), rgb(0,0,1,0.5)), border = "white", c("Depois da tosa", "Antes da tosa"), bty = "n") ``` \framebreak - \structure{Exemplos (2):} considere mais uma vez o conjunto de 48 ovelhas (com o seu peso original; antes da tosa). Suponha que quando as ovelhas estão em gestação^[Considere um certo momento da gestação das ovelhas (o final da gestação, por exemplo).], o seu peso é __exatamente__ 1,5 vezes o seu peso original. ```{r echo=FALSE, message=FALSE, warning=FALSE, results='asis', fig.align='center', out.width="60%"} hist(pig.weights$weight[pig.weights$num.weeks == 1]*1.5, xlab = "Peso de 48 ovelhas em gestação", ylab = "Frequência", col = rgb(0,1,0,0.5), border = "white", main = "") abline(v = mean(pig.weights$weight[pig.weights$num.weeks == 1]*1.5), lty = 2, col = "red", lwd = 2) text(40, 10, "Média = 37,5 kg\n s = 3,7 kg") ``` ## Propriedades da média e variância {.allowframebreaks} - Mais uma vez, representando o peso antes da tosa por $x$, podemos escrever o peso na gestação como $y = ax + b$, em que $a = 1,5$ e $b = 0$. - Percebemos que a média é __exatamente__ 1,5 a média do peso antes da gestação^[$\bar{y} = (1,5)\bar{x} - 0 = (1,5)25 = 37,5$.]. - A variância do peso na gestação é a variância do peso original multiplicado por $1,5^2$ ($a^2$)^[$s^2_{y} = (1,5)^2s^2_{x} = (1,5)^2(2,47)^2 = 13,73$.]. ## Propriedades da média e variância {.allowframebreaks} - Comparando as distribuições de $x$ (peso original) e $y$ (peso na gestação) percebemos que a distribuição do peso é deslocada para a direita ($a > 0$) e a dispersão aumenta ($|a| > 1$). ```{r echo=FALSE, message=FALSE, warning=FALSE, results='asis', fig.align='center', out.width="80%"} hist(pig.weights$weight[pig.weights$num.weeks == 1]*1.5, xlab = "Peso de 48 ovelhas", ylab = "Frequência", col = rgb(0,1,0,0.5), border = "white", main = "", xlim = c(18, 52)) hist(pig.weights$weight[pig.weights$num.weeks == 1], col = rgb(0,0,1,0.5), border = "white", add = TRUE) abline(v = c(mean(pig.weights$weight[pig.weights$num.weeks == 1]), mean(pig.weights$weight[pig.weights$num.weeks == 1]*1.5)), lty = 2, col = "red", lwd = 2) legend("topright", fill = c(rgb(0,0,1,0.5), rgb(0,1,0,0.5)), border = "white", c("Antes da gestação", "Na gestação"), bty = "n") ``` # Padronização {.allowframebreaks} - Uma transformação linear do tipo $y_i = ax_i + b$ merece destaque. + Se especificarmos $a = \frac{1}{s_x}$ e $b = - \frac{\bar{x}}{s_x}$ temos a seguinte transformação $$ z_i = \left(\frac{1}{s_x}\right)x_i + \left(- \frac{\bar{x}}{s_x}\right) = \frac{x_i - \bar{x}}{s_x}, i = 1, \ldots, n. $$ \framebreak - Como se compartam $\bar{z}$ e $s_z$? $$ \bar{z} = \frac{1}{s_x}\bar{x} - \frac{\bar{x}}{s_x} = 0,\quad\mbox{e}\quad s^2_z = \left(\frac{1}{s_x}\right)^2s^2_x = 1. $$ \framebreak - Esta transformação é também chamada de \structure{padronização} e a variável resultante $z$ é chamada de \structure{escore padronizado} de $x$. - Como visto, esta transformação tem como propriedades média zero e variância um. - O escore padronizado pode ser interpretado como o \structure{número de desvios padrões} que uma observação está da média. + Os dados abaixo da média (na escala original) têm escores $z$ padronizados negativos; + Os dados acima da média possuem $z$-escores positivos. \framebreak ### Observações 1. Uma __regra geral__ para detecção de observações atípicas em uma distribuição é, após padronizar a variável, avaliar valores $z$ acima de 1,96 e valores de $z$ abaixo de -1,96 ($|z| > 1,96$)^[Esta regra geral tem sua justificativa nas propriedades da distribuição de probabilidades __normal padrão__ (média zero e variância um). Uma regra mais prática é considerar valores atípicos como $|z| > 2$, pois $1,96 \approx 2$.]. 2. Com a padronização é possível produzir __uma escala comum__ para variáveis que foram medidas em escalas diferentes (por exemplo, peso em quilos e altura em metros). Isso permite que possamos combinar diversas variáveis, como é o caso de alguns indicadores. ## Padronização {.allowframebreaks} ```{r message=FALSE, echo=FALSE, out.height="85%", out.width="50%", purl=FALSE, fig.align='center'} knitr::include_graphics(here::here("images", "ESI0.png")) ``` ## Padronização {.allowframebreaks} - \structure{Exemplos (3):} veja como fica a distribuição do peso das 48 ovelhas quando padronizado. ```{r echo=FALSE, message=FALSE, warning=FALSE, results='asis', fig.align='center', out.width="70%", purl=FALSE} hist((pig.weights$weight[pig.weights$num.weeks == 1] - mean(pig.weights$weight[pig.weights$num.weeks == 1]))/sd(pig.weights$weight[pig.weights$num.weeks == 1]), xlab = "Peso padronizado de 48 ovelha", ylab = "Frequência", col = rgb(0.25,0,0.25,0.5), border = "white", main = "") abline(v = mean((pig.weights$weight[pig.weights$num.weeks == 1] - mean(pig.weights$weight[pig.weights$num.weeks == 1]))/sd(pig.weights$weight[pig.weights$num.weeks == 1])), lty = 2, col = "red", lwd = 2) text(1.5, 13, "Média = 0 kg\n s = 1 kg") ``` # Para casa {.allowframebreaks} A tabela a seguir apresenta as __frequências absolutas__ dos 48 valores observados da variável __peso de porcos__: ```{r fig-porcovelha, fig.margin=TRUE, fig.cap="Eram porcos, e não ovelhas!", fig.width=1, fig.height=1, cache=TRUE, message=FALSE, echo=FALSE, out.width="50%", purl=FALSE} knitr::include_graphics(here::here("images", "porcovelha.jpg")) ``` \footnotesize ```{r echo=FALSE, message=FALSE, warning=FALSE, purl=FALSE} library(SemiPar) library(knitr) data(pig.weights) library(kableExtra) pesodf <- data.frame(table(pig.weights$weight[pig.weights$num.weeks == 1])) names(pesodf)[1] <- "Peso" pesodf$Peso <- as.numeric(levels(pesodf$Peso)) kable(pesodf, escape = FALSE, align = 'c', col.names = c("Peso ($x_i$)", "Frequência ($n_i$)"), format.args = list(decimal.mark = ","), format = "markdown") ``` \normalsize ## Exercício - Quem são os valores de mínimo e máximo da variável peso? + Qual é a amplitude de variação? - Qual é a média da variável peso? - Qual é o desvio padrão da variável peso? - Quem é a mediana da variável peso? - Considerando que o porco é classificado como __baixo peso__ se este possui peso __menor ou igual a 23__, qual é o percentual de porcos com baixo peso? - Utilizando gráficos ou medidas resumo, avalie a assimetria e a curtose da distribuição do peso. # Complementa`R` ## Complementa`R` {.allowframebreaks} ```{r fig.align='right', message=FALSE, echo=FALSE, out.width="15%", purl=FALSE, warning=FALSE} knitr::include_graphics(here::here('images', 'teclado.png')) ``` ### Esta seção é complementar. São apresentadas algumas poucas funções em `R` relacionadas a discussão da aula. Para tal, vamos utilizar o exemplo original de [@bussab_estatistica_2017] sobre os dados dos empregados da seção de orçamentos da Companhia MB. A planilha eletrônica correspondente encontra-se no arquivo `companhia_mb.xlsx`. Vamos começar carregando os dados para o `R`. Existem várias formas de se carregar __arquivos de dados__ em diferentes no `R`. Como arquivo de interesse encontra-se no formato do Excel (xlsx), vamos utilizar a função `read_excel` do pacote `readxl`^[Caso você não tenha o pacote, instale-o:`install.packages("readxl")`.]. ## Complementa`R` {.allowframebreaks} \footnotesize ```{r carrega-dados0, echo=TRUE, eval=FALSE, warning=FALSE, message=FALSE} # install.packages("readxl") library(readxl) dados <- read_excel(path = "companhia_mb.xlsx") ``` ```{r carrega-dados1, echo=FALSE, warning=FALSE, message=FALSE, purl=FALSE} # install.packages("readxl") library(readxl) dados <- read_excel(path = here::here("data", "companhia_mb.xlsx")) ``` ```{r carrega-dados2, warning=FALSE, message=FALSE} class(dados) # classe do objeto dados dim(dados) # dimensão do objeto dados ``` \framebreak \normalsize - Note que o objeto `dados` é uma tabela de dados bruto. \footnotesize ```{r carrega-dados3, warning=FALSE, message=FALSE} head(dados) # apresenta as primeiras linhas do objeto dados ``` \framebreak \normalsize - As funções `skewness` e `kurtosis` do pacote `e1071` calcula, respectivamente, o coeficiente de assimetria e curtose, sendo que este último retorna $b_2 - 3$. - Assim, o ponto de referência para classificar uma distribuição como mesocúrtica ($b_2 - 3 = 0$), platicúrtica ($b_2 - 3 < 0$), ou leptocúrtica ($b_2 - 3 > 0$) é o zero. \footnotesize ```{r exetremos, warning=FALSE, message=FALSE} # install.packages("e1071") library(e1071) skewness(dados$Idade) kurtosis(dados$Idade) skewness(dados$`Salario (x Sal Min)`) kurtosis(dados$`Salario (x Sal Min)`) skewness(dados$`N de Filhos`, na.rm = TRUE) kurtosis(dados$`N de Filhos`, na.rm = TRUE) ``` \normalsize ## Próxima aula - Distribuições bivariadas. ## Por hoje é só! \begin{center} {\bf Bons estudos!} \end{center} ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='50%', out.height='50%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'Statistically-Insignificant-final01.jpg')) ``` <file_sep>## ----carrega-dados0, echo=TRUE, eval=FALSE, warning=FALSE, message=FALSE-------------------------------------------- ## # install.packages("readxl") library(readxl) dados <- read_excel(path = "data/companhia_mb.xlsx") ## ----carrega-dados2, warning=FALSE, message=FALSE------------------------------------------------------------------- class(dados) # classe do objeto dados dim(dados) # dimensão do objeto dados ## ----carrega-dados3, warning=FALSE, message=FALSE------------------------------------------------------------------- head(dados) # apresenta as primeiras linhas do objeto dados library(readxl) companhia_mb <- read_excel("data/companhia_mb.xlsx") View(companhia_mb) ## ----freqs, warning=FALSE, message=FALSE---------------------------------------------------------------------------- dados$`Grau de Instrução` # dados's # dados$escolaridade <- dados$`Grau de Instrução` # names(dados)[3] <- "escola" dados$Idade table(dados$`Estado Civil`) table(dados$`Grau de Instrução`) table(dados$`N de Filhos`) ## ----freqs2, warning=FALSE, message=FALSE--------------------------------------------------------------------------- dados$Idade.classes <- cut(x = dados$Idade, breaks = c(20, 29, 39, 49), labels = c("20 a 28 anos", "29 a 38 anos", "39 a 49 anos"), include.lowest = TRUE, right = FALSE) table(dados$Idade.classes) ## ----freqs3, warning=FALSE, message=FALSE--------------------------------------------------------------------------- table(dados$`Estado Civil`) / 36 table( dados$`Grau de Instrução`)/length(dados$`Grau de Instrução` ) ## ----freqs4, warning=FALSE, message=FALSE--------------------------------------------------------------------------- prop.table(x = table(dados$`N de Filhos`)) ## ----porcentagem, warning=FALSE, message=FALSE---------------------------------------------------------------------- prop.table(x = table(dados$Idade.classes)) * 100 ## ----porcentagem2, warning=FALSE, message=FALSE--------------------------------------------------------------------- round(x = prop.table(x = table(dados$Idade.classes)) * 100, digits = 2) ## ----freqcum, warning=FALSE, message=FALSE-------------------------------------------------------------------------- cumsum(x = table(dados$`Grau de Instrução`)) cumsum(x = prop.table(x = table(dados$`Grau de Instrução`))) ## ----freqcum2, warning=FALSE, message=FALSE------------------------------------------------------------------------- cumsum(x = prop.table(x = table(dados$`N de Filhos`)) * 100) cumsum( round( prop.table(x = table(dados$Idade.classes)) * 100, digits = 2)) ## ----freqtab, warning=FALSE, message=FALSE-------------------------------------------------------------------------- df.freq <- data.frame( Idade = unique(dados$Idade.classes), Freq = as.numeric(table(dados$Idade.classes)), FreqRel = as.numeric(prop.table(table(dados$Idade.classes))), Porcentagem = as.numeric(prop.table(table(dados$Idade.classes)) * 100), FreqAcumulada = as.numeric(cumsum(table(dados$Idade.classes))), FreqRelAcumulada = as.numeric(cumsum(prop.table(table(dados$Idade.classes))))) ## ----freqtabprint, warning=FALSE, message=FALSE--------------------------------------------------------------------- df.freq ## ----freqtab2, warning=FALSE, message=FALSE------------------------------------------------------------------------- # install.packages("summarytools") summarytools::freq(dados$`Grau de Instrução`) ## ----echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='50%', out.height='50%', paged.print=FALSE---- knitr::include_graphics(here::here('images', 'Statistically-Insignificant-mickey.jpg')) <file_sep>## ----carrega-dados0, echo=TRUE, eval=FALSE, warning=FALSE, message=FALSE-------------- ## # install.packages("readxl") library(readxl) dados <- read_excel(path = "companhia_mb.xlsx") ## ----carrega-dados2, warning=FALSE, message=FALSE------------------------------------- class(dados) # classe do objeto dados dim(dados) # dimensão do objeto dados ## ----carrega-dados3, warning=FALSE, message=FALSE------------------------------------- head(dados) # apresenta as primeiras linhas do objeto dados ## ----medias, warning=FALSE, message=FALSE--------------------------------------------- mean(dados$Idade) mean(dados$`Salario (x Sal Min)`) ## ----medias2, warning=FALSE, message=FALSE-------------------------------------------- mean(dados$`N de Filhos`, na.rm = TRUE) ## ----medianas, warning=FALSE, message=FALSE------------------------------------------- median(dados$Idade) median(dados$`Salario (x Sal Min)`) median(dados$`N de Filhos`, na.rm = TRUE) ## ----freqs, warning=FALSE, message=FALSE---------------------------------------------- table(dados$`Estado Civil`) ## ----modas, warning=FALSE, message=FALSE---------------------------------------------- which.max(table(dados$`Região de Procedência`)) which.max(table(dados$`N de Filhos`)) <file_sep>## ----serie_arroz, echo=FALSE, warning=FALSE, message=FALSE------------------------------------ library(dplyr) library(lubridate) library(readxl) library(knitr) library(kableExtra) arroz_df <- read_excel(path = here::here("data", "CEPEA_20201116161703.xls"), skip = 3) arroz_df$Data <- dmy(arroz_df$Data) arroz_res <- arroz_df %>% group_by(year(Data), month(Data)) %>% summarize(preco = mean(`À vista R$`)) %>% rename(Ano = `year(Data)`, Mes = `month(Data)`, Preco = preco) %>% filter(Ano %in% c(2020) & Mes %in% 3:6) %>% transform(Preco_kg = Preco/50, Quantidade = c(800, 1000, 900, 1050), Mes = paste("Mês", 0:3)) %>% transform(Valor_total = Quantidade * Preco_kg) %>% select(Mes, Quantidade, Preco_kg, Valor_total) arroz_res %>% kable(escape = F, format = "pandoc", align = 'c', digits = c(0, 0, 2, 2), caption = "Evolução das compras mensais de arroz", col.names = c("Período ($t$)", "Quantidade ($kg$)", "Preço ($u.m./kg$)", "Valor total ($u.m.$)"), format.args = list(decimal.mark = ",")) %>% footnote(general = "u.m. = unidade monetária.", general_title = "Nota: ", footnote_as_chunk = T, title_format = c("italic")) ## ----serie_relativos, echo=FALSE, warning=FALSE, message=FALSE-------------------------------- arroz_res %>% transform(Quantidade = Quantidade / Quantidade[1] * 100, Preco_kg = Preco_kg / Preco_kg[1] * 100, Valor_total = Valor_total / Valor_total[1] * 100) %>% kable(escape = F, format = "pandoc", align = 'c', digits = c(0, 1, 2, 2), format.args = list(decimal.mark = ","), caption = "Evolução das compras mensais de arroz (relativos ao mês 0)", col.names = c("Período ($t$)", "Quantidade", "Preço", "Valor total")) ## ----cinco_produtos, echo=FALSE, warning=FALSE, message=FALSE--------------------------------- prod <- c("Arroz (kg)", "Leite (L)", "Pão francês (u)", "Cigarro (maço)", "Cerveja (garrafa)") mes0 <- c(1.98, 1.99, 0.9, 7, 5.99) mes1 <- c(2.1, 2.08, 0.95, 7.50, 6.99) cinco_df <- data.frame(prod, mes0, mes1) cinco_df %>% kable(escape = F, format = "pandoc", align = 'c', digits = c(0, 2, 2), format.args = list(decimal.mark = ","), caption = "Preços vigentes de cinco produtos", col.names = c("Produtos", "Mês 0 ($u.m.$)", "Mês 1 ($u.m.$)")) ## ----cinco_relativos, echo=FALSE, warning=FALSE, message=FALSE-------------------------------- cinco_df <- cinco_df %>% transform(rel = mes1/mes0) cinco_df %>% kable(escape = F, format = "pandoc", align = 'c', digits = c(0, 2, 2, 3), format.args = list(decimal.mark = ","), caption = "Relativos de preços (cinco produtos)", col.names = c("Produtos", "Mês 0 ($u.m.$)", "Mês 1 ($u.m.$)", "$p_1^i/p_0^i$")) <file_sep>--- title: "Estatística Descritiva" subtitle: "Conceitos Básicos" author: "<NAME>, Dep. de Estatística - UFRGS" date: '`r paste(stringr::str_to_title(format(Sys.Date(), "%B")), format(Sys.Date(), "%Y"), sep = " de ")`' output: tufte::tufte_book: citation_package: natbib latex_engine: xelatex tufte::tufte_html: self_contained: true tufte::tufte_handout: citation_package: natbib latex_engine: xelatex bibliography: skeleton.bib link-citations: yes --- ```{r setup, include=FALSE} library(tufte) # invalidate cache when the tufte version changes knitr::opts_chunk$set(tidy = FALSE, cache.extra = packageVersion('tufte')) options(htmltools.dir.version = FALSE) ``` # Introdução ## Dados $\leadsto$ Conhecimento Em alguma fase de seu trabalho, o pesquisador depara-se com o problema de __analisar__ e __entender__ um __conjunto de dados__ relevante ao seu particular objeto de estudos. Ele necessitará trabalhar os dados para __transformá-los em informações__, para compará-los com outros resultados, ou ainda para __julgar sua adequação__ a __alguma teoria__. Uma representação ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='100%', out.height='80%', paged.print=FALSE, purl=FALSE} library(cowplot) library(ggplot2) p1 <- ggdraw() + draw_image(here::here('images', 'model.jpg'), scale = 0.9) p2 <- ggdraw() + draw_image(here::here('images', 'decisionloops2.jpg'), scale = 0.9) plot_grid(p1, p2) ``` Uma representação mais ousada! ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='100%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'Data-Wisdom.jpg')) ``` ## O Método Científico De modo bem geral, podemos dizer que a essência da Ciência é a __observação__ e que seu objetivo básico é a __inferência__. ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='70%', out.height='70%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'metodo.png')) ``` De modo bem geral, podemos dizer que a essência do Aprendizado (da Evolução). ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='50%', out.height='70%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'metodo_cientifico_bebes.png')) ``` # Conceitos básicos ## O que é a estatística? A __estatística__^[Do grego _statistós_, de _statízo_, __"estabelecer"__, __"verificar"__, acrescido do sufixo _ica_.] é a ciência que tem por objetivo orientar a coleta, o resumo, a apresentação, a análise e a interpretação de dados. Podem ser identificadas duas grandes áreas de atuação desta ciência: + a __estatística descritiva__, envolvida com o resumo e a apresentação dos dados. + a __estatística inferencial__, que ajuda a concluir sobre conjuntos maiores de dados (populações) quando apenas partes desses conjuntos (as amostras) foram estudadas. <!-- - Mais do que uma sequência de métodos, a estatística é uma forma de pensar ou de ver a realidade variável, já que seu conhecimento não apenas fornece um conjunto de técnicas de análise de dados, mas condiciona toda uma postura crítica sobre sua interpretação e a elaboração de conclusões sobre os dados. --> ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='100%', out.height='80%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'Descritiva_Inferencia.png')) ``` ## O que é a estatística descritiva? A __Estatística Descritiva__ corresponde aos procedimentos relacionados com a __coleta__, __elaboração__, __tabulação__, __análise__, __interpretação__ e __apresentação__ dos __dados__. Isto é, inclui as técnicas que dizem respeito à sintetização e à descrição de dados numéricos. Estas técnicas podem ser utilizadas em pelo menos dois contextos: + Análise da __consistência dos dados__. + __Análise Exploratória de Dados__ (_Exploratory Data Analysis_ - EDA)^[<NAME>. _Exploratory data analysis_, Reading:Addison-Wesley, 1977.]. Tais métodos tanto podem ser gráficos como envolver análise computacional. ## Estatística descritiva: alguns exemplos ```{r echo=FALSE, message=FALSE, warning=FALSE, purl=FALSE, results='asis'} library(summarytools) descr(tobacco, style = 'rmarkdown') ``` ```{r echo=FALSE, message=FALSE, warning=FALSE, purl=FALSE, results='asis'} freq(tobacco$gender, style = 'rmarkdown', headings = F) ``` ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='95%', paged.print=FALSE} # Considerações finais: exemplos # install.packages("jpeg") # install.packages("grid") library(jpeg) library(grid) library(gapminder) library(dplyr) gapminder <- gapminder %>% mutate(pop_m = pop/1e6) gapminder07 <- gapminder %>% filter(year == 2007) img <- readJPEG(here::here("images", "hans_rosling.jpg")) # start plotting p <- ggplot(data = gapminder07, mapping = aes(x = gdpPercap, y = lifeExp, color = continent, size = pop_m)) + annotation_custom(rasterGrob(img, width = unit(1, "npc"), height = unit(1, "npc")), -Inf, Inf, -Inf, Inf) + scale_y_continuous(expand = c(0,0), limits = c(min(gapminder07$lifeExp) * 0.9, max(gapminder07$lifeExp) * 1.05)) + geom_point() + labs(x = "Renda per capita (US$)", y = "Expectativa de vida (anos)", color = "Continente", size = "População/1 milhão") + theme_bw() + theme(text = element_text(color = "gray20"), legend.position = c("top"), # posição da legenda legend.direction = "horizontal", legend.justification = 0.1, # ponto de ancora para legend.position. legend.text = element_text(size = 11, color = "gray10"), axis.text = element_text(face = "italic"), axis.title.x = element_text(vjust = -1), axis.title.y = element_text(vjust = 2), axis.ticks.y = element_blank(), # element_blank() é como removemos elementos axis.line = element_line(color = "gray40", size = 0.5), axis.line.y = element_blank(), panel.grid.major = element_line(color = "gray50", size = 0.5), panel.grid.major.x = element_blank() ) p ``` ## Unidades experimentais e observacionais __Unidade experimental__ ou __unidade de observação__ é a menor unidade a fornecer informação. + __Ex:__ alunos, pacientes, animais, plantas, carros, hospitais, escolas, cidades, universidades, países, _tweets_, etc. ### Crash course de inferência causal - __Qual o melhor tratamento para o choque séptico?__ Dois tipos de estudo podem ser conduzidos para responder a esta questão de pesquisa: 1. Em um __experimento aleatorizado__ (_randomized trial_), uma moeda justa é lançada repetidamente para designar o tratamento de cada paciente. 2. Um __estudo observacional__ é uma investigação empírica em que o objetivo é elucidar relações de causa e efeito, em que não é factível o uso de experimentação controlada, no sentido de ser capaz de impor procedimentos ou tratamentos cujos os efeitos se deseja descobrir. ### Experimentos: exemplo - "O chá servido sobre o leite parecia ficar com gosto diferente do que apresentava ao receber o leite sobre ele"^[<NAME>. _Uma senhora toma chá ... como a estatística revolucionou a ciência no século XX_, Zahar, 2009.]. ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='70%', out.height='60%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'uma_senhora_toma_cha.jpg')) ``` ### Estudos observacionais: exemplo - "O __Ministério da Saúde__ adverte: __fumar pode causar câncer de pulmão__”. ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='70%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'smokingAndLungCancer2.jpg')) ``` ```{exercise} 1. Elabore uma questão de pesquisa de seu interesse (anote a sua questão em algum lugar). 2. Discuta a respeito da sua questão de pesquisa com os colegas. ``` ## Dados e variáveis ::: {.block} ### Dados São as informações obtidas de uma unidade experimental ou observacional. \ - __Ex:__ "Vitor tem 25 anos e é fumante". Os dados são "25 anos" e "fumante". ::: ::: {.block} ### Variável É toda característica que, observada em uma unidade (experimental ou observacional), pode variar de um indivíduo para outro. \ - __Ex:__ idade, sexo, altura, nível de hemoglobina no sangue, espaçamento entre plantas, doses de um medicamento, tipo de medicamento, cultivares, número de caracteres, velocidade da rede, tempo gasto na rede social, nível de monóxido de carbono em emissões do escape de automóveis, etc. ::: É importante __identificar que tipo de variável__ está sendo estudada, uma vez que são recomendados __procedimentos estatísticos diferentes__ em cada situação. ## Tipos de variáveis ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='90%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'classe_var.png')) ``` ## Variáveis quantitativas ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='100%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'var_quanti.png')) ``` ## Variáveis quantitativas discretas ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='60%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'var_discreta.jpg')) ``` ## Variáveis quantitativas contínuas ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='70%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'var_continua.jpg')) ``` ## Variáveis qualitativas ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='100%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'var_quali.png')) ``` ## Variáveis qualitativas ordinais ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='100%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'var_ordinal.jpg')) ``` ## Variáveis qualitativas nominais ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='70%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'var_nominal.jpg')) ``` ## Exemplos (1) ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='90%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'cor_predio2.jpg')) ``` ## Exemplos (1) ### Variáveis quantitativas - 3 andares - 14,85 metros de altura ### Variáveis qualitativas - Multicolorido - Cheira "bem" ## Exemplos (2) ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='90%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'rolling-stones.jpg')) ``` ## Exemplos (2) ### Variáveis quantitativas - 4 integrantes - 56 anos ### Variáveis qualitativas - Inglaterra - Rock ## Exercício 1. Com base na questão de pesquisa elaborada no exercício anterior, liste variáveis que você teria interesse em coletar e analisar para responder a sua questão de pesquisa. 2. Classifique as variáveis de acordo com a classificação discutida anteriormente. 3. Discuta a respeito das suas variáveis com os colegas. ## População - __População__ ou __universo__: esse termo é usado em estatística com um sentido bem mais amplo do que na linguagem coloquial. - É entendido aqui como o __conjunto de todos os elementos__ que apresentam uma ou mais características __em comum__. - __Exemplo 1:__ a população de colegiais de oito anos de Belo Horizonte. + Estes colegiais têm em comum a idade e o local onde vivem. - __Exemplo 2:__ a população de indústrias brasileiras. + Estas indústrias têm em comum o fato de que foram criadas no Brasil. - Este conjunto por vezes é denominado por $U$ (de __conjunto universo__). - O __tamanho da população__ é a sua quantidade de elementos, que anotamos por $N$. - Uma população pode ser __finita__ (limita em tamanho; $N < \infty$) ou __infinita__ ($N =\infty$). + __Exemplo de pop. finita:__ torcedores do São Raimundo de Santarém, residentes de Porto Alegre. + __Exemplo de pop. infinita:__ equipamentos (de um certo tipo) fabricados em série. ## Censo e amostra - Quando o estudo é realizado com toda a população de interesse, chamemos este estudo de __censo__. - Por motivos de tempo, custo, logística, entre outros, geralmente não é possível realizar um censo. + Nestes casos, estudamos apenas uma parcela da população, que chamamos de __amostra__. ### Censo vs. amostra À primeira vista, uma coleta de dados realizada em toda a população é preferível a uma realizada apenas numa parte da população. Na prática, entretanto, o oposto é frequentemente verdadeiro porque: 1. Um censo é impossível quando a população é infinita. 2. Os ensaios (testes) podem ser destrutivos \structure{(como nos testes de segurança dos carros)}. 3. Rapidez: estudar toda a população pode despender de muito tempo, não sendo compatível com a urgência do estudo \structure{(como quando estudamos os casos de um surto de uma nova doença)}. Para uma consideração mais completa ver Vargas (2000)\footnote{<NAME>. \emph{Estatística: uma linguagem para dialogar com a incerteza}, Cadernos de matemática e estatística. Série B, 2000.}. ## Amostra - __Amostra__ é qualquer fração de uma população. + Como sua finalidade é representar a população, deseja-se que a amostra escolhida apresente as mesmas características da população de origem, isto é, que seja uma amostra __"representativa"__ ou __"não-tendenciosa"__. - Tanto o número de indivíduos selecionados para a amostra quanto a técnica de seleção são extremamente importantes para que os resultados obtidos no estudo sejam generalizados para a população. ## Amostra representativa ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='65%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'Gato_caindo.jpg')) ``` - Ver a discussão sobre __representatividade da amostra__ na [apresentação](https://www.youtube.com/watch?v=TGGGDpb04Yc&t=592s) do __Prof. <NAME>__. ## Amostragem - A seleção da amostra pode ser feita de várias maneiras. - Esta dependerá: + Do grau de conhecimento que temos da população. + Da quantidade de recursos disponíveis. - A seleção da amostra tenta fornecer um subconjunto de valores o __mais parecido possível__ com a população que lhe dá origem. + __Amostra representativa__ da população. ## Amostra aleatória simples - A amostragem mais usada é a __amostra casual simples__ (ou aleatória simples). + Os indivíduos (unidades) da amostra são selecionados ao acaso, __com__ ou __sem reposição__. ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='60%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'simpleSample.png')) ``` ## Amostra estratificada - Eventualmente, se tivermos informações adicionais a respeito da população de interesse, podemos utilizar outros esquemas de amostragem mais sofisticados. + __Amostragem estratificada__ ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='95%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'estratificada.png')) ``` ## Amostra sistemática - Em outros casos, pode existir uma relação numerada dos itens da população que nos permitiria utilizar a chamada __amostragem sistemática__ em que selecionamos os indivíduos de forma pré-determinada. ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='80%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'SystematicSampling.jpg')) ``` ## Amostragem - Outros esquemas de amostragem poderiam ser citados e todos fazem parte da chamada __teoria da amostragem__, cujos detalhes não serão aprofundados. ## Parâmetros, estatísticas e estimativas - __Parâmetro__ é um valor que resume, na população, a informação relativa a uma variável. + __Ex:__ média populacional, prevalência populacional, coeficiente de variação populacional, taxa de mortalidade populacional, etc. - __Estatística__ (além de ser o nome da ciência/área do conhecimento) é a denominação dada a uma quantidade, calculada com base nos elementos de uma amostra, que descreve a informação contida nesse conjunto de dados. + __Ex:__ A média, a porcentagem, o desvio padrão, o coeficiente de correlação, calculados em uma amostra, são estatísticas. ## Parâmetros, estatísticas e estimativas - Os parâmetros são difíceis de se obter, pois implicam o estudo de toda a população e costumam ser substituídos por valores calculados em amostras representativas da população-alvo. + Se tivesse sido examinada uma amostra de 10 estudantes matriculados na disciplina MAT02218, e 40% fossem do torcedores do América Mineiro, esse valor constituiria uma estimativa do parâmetro "percentual de torcedores do América Mineiro matriculados naquela disciplina". - A __estimativa__ é um valor numérico de uma estatística, usado para realizar inferências sobre o parâmetro. + Da mesma forma, o valor numérico da média para a estatura desses 10 alunos, digamos 173 cm, é uma estimativa para a média de altura populacional. - __P:__ neste exemplo, quem é a população (alvo)? ## Próxima aula - Organização dos dados <!-- - Distribuição de frequências --> ## Para casa \begin{columns}[c] \column{2.3in} \begin{figure}[!h] \begin{center} \includegraphics[width=0.9\columnwidth]{images/stats_cats.jpg} \end{center} \end{figure} \column{2.3in} \begin{itemize}\setlength{\itemsep}{+2mm} \item Conhecer o Moodle da disciplina. \item Ler os Cap. 1 e 2 de "Estatística Descritiva I" de Fernandez. \end{itemize} \end{columns} ## Por hoje é só! Bons estudos! ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='100%', out.height='80%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'lofi_01.jpg')) ``` <!-- # Introduction --> <!-- The Tufte handout style is a style that <NAME> uses in his books and handouts. Tufte's style is known for its extensive use of sidenotes, tight integration of graphics with text, and well-set typography. This style has been implemented in LaTeX and HTML/CSS^[See Github repositories [tufte-latex](https://github.com/tufte-latex/tufte-latex) and [tufte-css](https://github.com/edwardtufte/tufte-css)], respectively. We have ported both implementations into the [**tufte** package](https://github.com/rstudio/tufte). If you want LaTeX/PDF output, you may use the `tufte_handout` format for handouts, and `tufte_book` for books. For HTML output, use `tufte_html`. These formats can be either specified in the YAML metadata at the beginning of an R Markdown document (see an example below), or passed to the `rmarkdown::render()` function. See @R-rmarkdown for more information about **rmarkdown**. --> <!-- ```yaml --> <!-- --- --> <!-- title: "An Example Using the Tufte Style" --> <!-- author: "<NAME>" --> <!-- output: --> <!-- tufte::tufte_handout: default --> <!-- tufte::tufte_html: default --> <!-- --- --> <!-- ``` --> <!-- There are two goals of this package: --> <!-- 1. To produce both PDF and HTML output with similar styles from the same R Markdown document; --> <!-- 1. To provide simple syntax to write elements of the Tufte style such as side notes and margin figures, e.g. when you want a margin figure, all you need to do is the chunk option `fig.margin = TRUE`, and we will take care of the details for you, so you never need to think about `\begin{marginfigure} \end{marginfigure}` or `<span class="marginfigure"> </span>`; the LaTeX and HTML code under the hood may be complicated, but you never need to learn or write such code. --> <!-- If you have any feature requests or find bugs in **tufte**, please do not hesitate to file them to https://github.com/rstudio/tufte/issues. For general questions, you may ask them on StackOverflow: http://stackoverflow.com/tags/rmarkdown. --> <!-- # Headings --> <!-- This style provides first and second-level headings (that is, `#` and `##`), demonstrated in the next section. You may get unexpected output if you try to use `###` and smaller headings. --> <!-- `r newthought('In his later books')`^[[Beautiful Evidence](http://www.edwardtufte.com/tufte/books_be)], Tufte starts each section with a bit of vertical space, a non-indented paragraph, and sets the first few words of the sentence in small caps. To accomplish this using this style, call the `newthought()` function in **tufte** in an _inline R expression_ `` `r ` `` as demonstrated at the beginning of this paragraph.^[Note you should not assume **tufte** has been attached to your R session. You should either `library(tufte)` in your R Markdown document before you call `newthought()`, or use `tufte::newthought()`.] --> <!-- # Figures --> <!-- ## Margin Figures --> <!-- Images and graphics play an integral role in Tufte's work. To place figures in the margin you can use the **knitr** chunk option `fig.margin = TRUE`. For example: --> <!-- ```{r fig-margin, fig.margin = TRUE, fig.cap = "MPG vs horsepower, colored by transmission.", fig.width=3.5, fig.height=3.5, cache=TRUE, message=FALSE} --> <!-- library(ggplot2) --> <!-- mtcars2 <- mtcars --> <!-- mtcars2$am <- factor( --> <!-- mtcars$am, labels = c('automatic', 'manual') --> <!-- ) --> <!-- ggplot(mtcars2, aes(hp, mpg, color = am)) + --> <!-- geom_point() + geom_smooth() + --> <!-- theme(legend.position = 'bottom') --> <!-- ``` --> <!-- Note the use of the `fig.cap` chunk option to provide a figure caption. You can adjust the proportions of figures using the `fig.width` and `fig.height` chunk options. These are specified in inches, and will be automatically scaled down to fit within the handout margin. --> <!-- ## Arbitrary Margin Content --> <!-- In fact, you can include anything in the margin using the **knitr** engine named `marginfigure`. Unlike R code chunks ```` ```{r} ````, you write a chunk starting with ```` ```{marginfigure} ```` instead, then put the content in the chunk. See an example on the right about the first fundamental theorem of calculus. --> <!-- ```{marginfigure} --> <!-- We know from _the first fundamental theorem of calculus_ that for $x$ in $[a, b]$: --> <!-- $$\frac{d}{dx}\left( \int_{a}^{x} f(u)\,du\right)=f(x).$$ --> <!-- ``` --> <!-- For the sake of portability between LaTeX and HTML, you should keep the margin content as simple as possible (syntax-wise) in the `marginefigure` blocks. You may use simple Markdown syntax like `**bold**` and `_italic_` text, but please refrain from using footnotes, citations, or block-level elements (e.g. blockquotes and lists) there. --> <!-- Note: if you set `echo = FALSE` in your global chunk options, you will have to add `echo = TRUE` to the chunk to display a margin figure, for example ```` ```{marginfigure, echo = TRUE} ````. --> <!-- ## Full Width Figures --> <!-- You can arrange for figures to span across the entire page by using the chunk option `fig.fullwidth = TRUE`. --> <!-- ```{r fig-fullwidth, fig.width = 10, fig.height = 2, fig.fullwidth = TRUE, fig.cap = "A full width figure.", warning=FALSE, message=FALSE, cache=TRUE} --> <!-- ggplot(diamonds, aes(carat, price)) + geom_smooth() + --> <!-- facet_grid(~ cut) --> <!-- ``` --> <!-- Other chunk options related to figures can still be used, such as `fig.width`, `fig.cap`, `out.width`, and so on. For full width figures, usually `fig.width` is large and `fig.height` is small. In the above example, the plot size is $10 \times 2$. --> <!-- ## Arbitrary Full Width Content --> <!-- Any content can span to the full width of the page. This feature requires Pandoc 2.0 or above. All you need is to put your content in a fenced `Div` with the class `fullwidth`, e.g., --> <!-- ```md --> <!-- ::: {.fullwidth} --> <!-- Any _full width_ content here. --> <!-- ::: --> <!-- ``` --> <!-- Below is an example: --> <!-- ::: {.fullwidth} --> <!-- _R is free software and comes with ABSOLUTELY NO WARRANTY._ You are welcome to redistribute it under the terms of the GNU General Public License versions 2 or 3. For more information about these matters see http://www.gnu.org/licenses/. --> <!-- ::: --> <!-- ## Main Column Figures --> <!-- Besides margin and full width figures, you can of course also include figures constrained to the main column. This is the default type of figures in the LaTeX/HTML output. --> <!-- ```{r fig-main, fig.cap = "A figure in the main column.", cache=TRUE} --> <!-- ggplot(diamonds, aes(cut, price)) + geom_boxplot() --> <!-- ``` --> <!-- # Sidenotes --> <!-- One of the most prominent and distinctive features of this style is the extensive use of sidenotes. There is a wide margin to provide ample room for sidenotes and small figures. Any use of a footnote will automatically be converted to a sidenote. ^[This is a sidenote that was entered using a footnote.] --> <!-- If you'd like to place ancillary information in the margin without the sidenote mark (the superscript number), you can use the `margin_note()` function from **tufte** in an inline R expression. `r margin_note("This is a margin note. Notice that there is no number preceding the note.")` This function does not process the text with Pandoc, so Markdown syntax will not work here. If you need to write anything in Markdown syntax, please use the `marginfigure` block described previously. --> <!-- # References --> <!-- References can be displayed as margin notes for HTML output. For example, we can cite R here [@R-base]. To enable this feature, you must set `link-citations: yes` in the YAML metadata, and the version of `pandoc-citeproc` should be at least 0.7.2. You can always install your own version of Pandoc from http://pandoc.org/installing.html if the version is not sufficient. To check the version of `pandoc-citeproc` in your system, you may run this in R: --> <!-- ```{r eval=FALSE} --> <!-- system2('pandoc-citeproc', '--version') --> <!-- ``` --> <!-- If your version of `pandoc-citeproc` is too low, or you did not set `link-citations: yes` in YAML, references in the HTML output will be placed at the end of the output document. --> <!-- # Tables --> <!-- You can use the `kable()` function from the **knitr** package to format tables that integrate well with the rest of the Tufte handout style. The table captions are placed in the margin like figures in the HTML output. --> <!-- ```{r} --> <!-- knitr::kable( --> <!-- mtcars[1:6, 1:6], caption = 'A subset of mtcars.' --> <!-- ) --> <!-- ``` --> <!-- # Block Quotes --> <!-- We know from the Markdown syntax that paragraphs that start with `>` are converted to block quotes. If you want to add a right-aligned footer for the quote, you may use the function `quote_footer()` from **tufte** in an inline R expression. Here is an example: --> <!-- > "If it weren't for my lawyer, I'd still be in prison. It went a lot faster with two people digging." --> <!-- > --> <!-- > `r tufte::quote_footer('--- <NAME>')` --> <!-- Without using `quote_footer()`, it looks like this (the second line is just a normal paragraph): --> <!-- > "Great people talk about ideas, average people talk about things, and small people talk about wine." --> <!-- > --> <!-- > --- <NAME> --> <!-- # Responsiveness --> <!-- The HTML page is responsive in the sense that when the page width is smaller than 760px, sidenotes and margin notes will be hidden by default. For sidenotes, you can click their numbers (the superscripts) to toggle their visibility. For margin notes, you may click the circled plus signs to toggle visibility. --> <!-- # More Examples --> <!-- The rest of this document consists of a few test cases to make sure everything still works well in slightly more complicated scenarios. First we generate two plots in one figure environment with the chunk option `fig.show = 'hold'`: --> <!-- ```{r fig-two-together, fig.cap="Two plots in one figure environment.", fig.show='hold', cache=TRUE, message=FALSE} --> <!-- p <- ggplot(mtcars2, aes(hp, mpg, color = am)) + --> <!-- geom_point() --> <!-- p --> <!-- p + geom_smooth() --> <!-- ``` --> <!-- Then two plots in separate figure environments (the code is identical to the previous code chunk, but the chunk option is the default `fig.show = 'asis'` now): --> <!-- ```{r fig-two-separate, ref.label='fig-two-together', fig.cap=sprintf("Two plots in separate figure environments (the %s plot).", c("first", "second")), cache=TRUE, message=FALSE} --> <!-- ``` --> <!-- You may have noticed that the two figures have different captions, and that is because we used a character vector of length 2 for the chunk option `fig.cap` (something like `fig.cap = c('first plot', 'second plot')`). --> <!-- Next we show multiple plots in margin figures. Similarly, two plots in the same figure environment in the margin: --> <!-- ```{r fig-margin-together, fig.margin=TRUE, fig.show='hold', fig.cap="Two plots in one figure environment in the margin.", fig.width=3.5, fig.height=2.5, cache=TRUE} --> <!-- p --> <!-- p + geom_smooth(method = 'lm') --> <!-- ``` --> <!-- Then two plots from the same code chunk placed in different figure environments: --> <!-- ```{r fig-margin-separate, fig.margin=TRUE, fig.cap=sprintf("Two plots in separate figure environments in the margin (the %s plot).", c("first", "second")), fig.width=3.5, fig.height=2.5, cache=TRUE} --> <!-- knitr::kable(head(iris, 15)) --> <!-- p --> <!-- knitr::kable(head(iris, 12)) --> <!-- p + geom_smooth(method = 'lm') --> <!-- knitr::kable(head(iris, 5)) --> <!-- ``` --> <!-- We blended some tables in the above code chunk only as _placeholders_ to make sure there is enough vertical space among the margin figures, otherwise they will be stacked tightly together. For a practical document, you should not insert too many margin figures consecutively and make the margin crowded. --> <!-- You do not have to assign captions to figures. We show three figures with no captions below in the margin, in the main column, and in full width, respectively. --> <!-- ```{r fig-nocap-margin, fig.margin=TRUE, fig.width=3.5, fig.height=2, cache=TRUE} --> <!-- # a boxplot of weight vs transmission; this figure --> <!-- # will be placed in the margin --> <!-- ggplot(mtcars2, aes(am, wt)) + geom_boxplot() + --> <!-- coord_flip() --> <!-- ``` --> <!-- ```{r fig-nocap-main, cache=TRUE} --> <!-- # a figure in the main column --> <!-- p <- ggplot(mtcars, aes(wt, hp)) + geom_point() --> <!-- p --> <!-- ``` --> <!-- ```{r fig-nocap-fullwidth, fig.fullwidth=TRUE, fig.width=10, fig.height=3, cache=TRUE} --> <!-- # a fullwidth figure --> <!-- p + geom_smooth(method = 'lm') + facet_grid(~ gear) --> <!-- ``` --> <!-- # Some Notes on Tufte CSS --> <!-- There are a few other things in Tufte CSS that we have not mentioned so far. If you prefer `r sans_serif('sans-serif fonts')`, use the function `sans_serif()` in **tufte**. For epigraphs, you may use a pair of underscores to make the paragraph italic in a block quote, e.g. --> <!-- > _I can win an argument on any topic, against any opponent. People know this, and steer clear of me at parties. Often, as a sign of their great respect, they don't even invite me._ --> <!-- > --> <!-- > `r quote_footer('--- <NAME>')` --> <!-- We hope you will enjoy the simplicity of R Markdown and this R package, and we sincerely thank the authors of the Tufte-CSS and Tufte-LaTeX projects for developing the beautiful CSS and LaTeX classes. Our **tufte** package would not have been possible without their heavy lifting. --> <!-- You can turn on/off some features of the Tufte style in HTML output. The default features enabled are: --> <!-- ```yaml --> <!-- output: --> <!-- tufte::tufte_html: --> <!-- tufte_features: ["fonts", "background", "italics"] --> <!-- ``` --> <!-- If you do not want the page background to be lightyellow, you can remove `background` from `tufte_features`. You can also customize the style of the HTML page via a CSS file. For example, if you do not want the subtitle to be italic, you can define --> <!-- ```css --> <!-- h3.subtitle em { --> <!-- font-style: normal; --> <!-- } --> <!-- ``` --> <!-- in, say, a CSS file `my_style.css` (under the same directory of your Rmd document), and apply it to your HTML output via the `css` option, e.g., --> <!-- ```yaml --> <!-- output: --> <!-- tufte::tufte_html: --> <!-- tufte_features: ["fonts", "background"] --> <!-- css: "my_style.css" --> <!-- ``` --> <!-- There is also a variant of the Tufte style in HTML/CSS named "[Envisoned CSS](http://nogginfuel.com/envisioned-css/)". This style can be used by specifying the argument `tufte_variant = 'envisioned'` in `tufte_html()`^[The actual Envisioned CSS was not used in the **tufte** package. We only changed the fonts, background color, and text color based on the default Tufte style.], e.g. --> <!-- ```yaml --> <!-- output: --> <!-- tufte::tufte_html: --> <!-- tufte_variant: "envisioned" --> <!-- ``` --> <!-- To see the R Markdown source of this example document, you may follow [this link to Github](https://github.com/rstudio/tufte/raw/master/inst/rmarkdown/templates/tufte_html/skeleton/skeleton.Rmd), use the wizard in RStudio IDE (`File -> New File -> R Markdown -> From Template`), or open the Rmd file in the package: --> <!-- ```{r eval=FALSE} --> <!-- file.edit( --> <!-- tufte:::template_resources( --> <!-- 'tufte_html', '..', 'skeleton', 'skeleton.Rmd' --> <!-- ) --> <!-- ) --> <!-- ``` --> <!-- This document is also available in [Chinese](http://rstudio.github.io/tufte/cn/), and its `envisioned` style can be found [here](http://rstudio.github.io/tufte/envisioned/). --> <!-- ```{r bib, include=FALSE} --> <!-- # create a bib file for the R packages used in this document --> <!-- knitr::write_bib(c('base', 'rmarkdown'), file = 'skeleton.bib') --> <!-- ``` --> <file_sep>--- title: "MAT02018 - Estatística Descritiva" subtitle: "Medidas de variabilidade" fontsize: 10pt author: | | <NAME> | `<EMAIL>` institute: | | \textsc{Universidade Federal do Rio Grande do Sul} | \textsc{Instituto de Matemática e Estatística} | \textsc{Departamento de Estatística} date: | | Porto Alegre, 2022 bibliography: estatistica-descritiva.bib csl: associacao-brasileira-de-normas-tecnicas-ufrgs-initials.csl link-citations: yes --- ```{r setup, include=FALSE, purl=FALSE} options(knitr.kable.NA = '-') library(dplyr) library(knitr) ``` # Estatísticas de ordem - A \structure{média} e o \structure{desvio padrão} são bastante conhecidos e muito usados para descrever um conjunto de dados. - No entanto, não são as únicas. - Também podem ser adotadas as medidas de posição relativa, mais conhecidas como \structure{estatísticas de ordem}. - Uma destas medidas é a \structure{mediana}. - Falaremos também dos \structure{quartis}, \structure{decis} e \structure{percentis}. - Os quartis serão utilizados também para calcularmos a \structure{amplitude entre quartis}, que pode ser utilizada como uma medida de dispersão. ## Quartis {.allowframebreaks} - \structure{Quartis} são pontos que dividem um \structure{conjunto de dados ordenado} em \structure{quatro partes} iguais (quatro quartos). - Denotamos os quartis por $Q_1$, $Q_2$ e $Q_3$: - $Q_1$ é o \structure{primeiro quartil}. É o valor que tem 25% dos dados iguais ou menores do que ele. - $Q_2$ é o \structure{segundo quartil}. É o valor que tem 50% dos dados iguais ou menores do que ele^[Note que o segundo quartil é também a mediana de um conjunto de dados.]. - $Q_3$ é o \structure{terceiro quartil}. É o valor que tem 75% dos dados iguais ou menores do que ele. ## Quartis {.allowframebreaks} Uma forma de encontrar as posições de $Q_1$ e $Q_3$^[Já aprendemos a encontrar a posição de $Q_2$, a mediana.] na __série ordenada de dados__, como foi visto para o caso da mediana ($Q_2$). + posição de $Q_1$: $\frac{n+1}{4}$ + posição de $Q_3$: $\frac{3(n+1)}{4}$ No caso do conjunto de dados conter um número par de elementos, $Q_1$ e $Q_3$ são obtidos tomando-se a média dos valores vizinhos as suas posições. ## Separatrizes {.allowframebreaks} - Da mesma forma que obtemos valores que dividem o conjunto de dados em quatro, podemos generalizar esta ideia para mais grupos. - \structure{Decis} dividem o conjunto de dados em dez partes iguais. + Para obter os decis, organizamos os dados em ordem crescente e depois dividimos o conjunto em dez subconjuntos com igual número de elementos. + Os decis são os valores que separam esses subconjuntos. - \structure{Percentis} dividem o conjunto de dados em cem partes iguais. + Para obter os percentis, organizamos os dados em ordem crescente e depois dividimos o conjunto em cem subconjuntos com igual número de elementos. + Os percentis são os valores que separam esses subconjuntos. \framebreak ### Comentários - Os quartis, decis e percentis são conhecidos como as \structure{separatrizes}. - Se divimos o conjunto de dados ordenado em três partes iguais, temos os \structure{tercis}. - Se divimos o conjunto de dados ordenado em cinco partes iguais, temos os \structure{quintis}. - O cálculo dos decis e percentis é mais adequado quando o tamanho da amostra (ou população) é grande. # Amplitude entre quartis {.allowframebreaks} - A \structure{amplitude entre quartis} (ou \structure{distância interquartílica}) é definida como a __diferença entre o terceiro e o primeiro quartil__: $$ DIQ = Q_3 - Q_1. $$ - Note que entre $Q_1$ e $Q_3$ estão 50% dos valores mais centrais da distribuição. \framebreak - \structure{Exemplo:} ```{r fig.align='center', echo=FALSE, out.width="70%", purl=FALSE} knitr::include_graphics(here::here('images', 'quartis.png')) ``` - Temos que $Q_1 = 4,9$, $Q_3 = 5,25$, e portanto, a amplitude entre quartis é $$ Q_3 - Q_1 = 5,25 - 4,9 = 0,35. $$ ## Diagrama de caixa {.allowframebreaks} - Existe uma forma de apresentar graficamente uma distribuição de uma variável contínua através de algumas medidas resumo, tais como: o mínimo, o máximo e os quartis. - Tal gráfico é conhecido como \structure{diagrama de caixa}^[Também chamado pelo nome em inglês, o _boxplot_.]. ## Diagrama de caixa {.allowframebreaks} Para construir o diagrama de caixa, siga os seguintes passos: 1. Desenhe um retângulo (caixa, ou _box_) com comprimento igual a amplitude entre quartis (distância interquartílica). 2. Trace uma linha para representar a mediana, na posição (medida pela distância) que ela ocupa entre o primeiro e o terceiro quartil. 3. Trace linhas perpendiculares à mediana, saindo do meio do retângulo; a linha abaixo da caixa terá comprimento igual à distância entre o primeiro quartil e o valor mínimo; a linha acima da caixa, comprimento igual à distância entre o terceiro quartil e o valor máximo^[Existem variações na construção destas linhas do diagrama de caixa, também conhecidas por cerquilhas. Esta forma apresentada não é a mais usual. É comum traçar a linha abaixo da caixa partindo de $Q_1 - 1,5\times DIQ$ e chegando em $Q_1$, e a linha acima da caixa partindo de $Q_3$ e chegando em $Q_3 + 1,5\times DIQ$. Quando o diagrama de caixas é construído desta forma, alguns autores sugerem que os valores fora destas cerquilhas sejam consideradas discrepantes (_outliers_). É claro que este é apenas um critério prático, e classificar uma observação como discrepante, ou anômala, depende do contexto.]. ## Diagrama de caixa {.allowframebreaks} ```{r fig.align='center', echo=FALSE, out.width="70%", out.height='70%', purl=FALSE} knitr::include_graphics(here::here('images', 'resumo-cinco-numeros-box-plot.jpg')) ``` \framebreak - O diagrama de caixa é bastante utilizado para comparar a distribuição de uma certa variável em diferentes grupos. ```{r echo=FALSE, message=FALSE, warning=FALSE, purl=FALSE, fig.align='center', out.width='70%'} plot(Sepal.Length ~ Species, data = iris, col = "lightsalmon", xlab = "Espécies", ylab = "Comprimento de sépala") ``` \framebreak - \structure{Sua vez:} para cada gráfico a seguir (cada gráfico apresenta o diagrama de caixa de uma certa variável para três espécies de íris), aponte o grupo de maior e menor variabilidade. + Como você chegou nestas conclusões? ```{r echo=FALSE, message=FALSE, warning=FALSE, purl=FALSE, fig.align='center', out.width='100%'} par(mfrow = c(2,2)) plot(Sepal.Length ~ Species, data = iris, col = "lightsalmon", xlab = "Espécies", ylab = "Comprimento de sépala") plot(Sepal.Width ~ Species, data = iris, col = "lightsalmon", xlab = "Espécies", ylab = "Largura de sépala") plot(Petal.Length ~ Species, data = iris, col = "lightsalmon", xlab = "Espécies", ylab = "Comprimento de pétala") plot(Petal.Width ~ Species, data = iris, col = "lightsalmon", xlab = "Espécies", ylab = "Largura de pétala") par(mfrow = c(1,1)) ``` # Complementa`R` ## Complementa`R` {.allowframebreaks} ```{r fig.align='right', message=FALSE, echo=FALSE, out.width="15%", purl=FALSE, warning=FALSE} knitr::include_graphics(here::here('images', 'teclado.png')) ``` ### Esta seção é complementar. São apresentadas algumas poucas funções em `R` relacionadas a discussão da aula. Para tal, vamos utilizar o exemplo original de [@bussab_estatistica_2017] sobre os dados dos empregados da seção de orçamentos da Companhia MB. A planilha eletrônica correspondente encontra-se no arquivo `companhia_mb.xlsx`. Vamos começar carregando os dados para o `R`. Existem várias formas de se carregar __arquivos de dados__ em diferentes no `R`. Como arquivo de interesse encontra-se no formato do Excel (xlsx), vamos utilizar a função `read_excel` do pacote `readxl`^[Caso você não tenha o pacote, instale-o:`install.packages("readxl")`.]. ## Complementa`R` {.allowframebreaks} \footnotesize ```{r carrega-dados0, echo=TRUE, eval=FALSE, warning=FALSE, message=FALSE} # install.packages("readxl") library(readxl) dados <- read_excel(path = "companhia_mb.xlsx") ``` ```{r carrega-dados1, echo=FALSE, warning=FALSE, message=FALSE, purl=FALSE} # install.packages("readxl") library(readxl) dados <- read_excel(path = here::here("data", "companhia_mb.xlsx")) ``` ```{r carrega-dados2, warning=FALSE, message=FALSE} class(dados) # classe do objeto dados dim(dados) # dimensão do objeto dados ``` \framebreak \normalsize - Note que o objeto `dados` é uma tabela de dados bruto. \footnotesize ```{r carrega-dados3, warning=FALSE, message=FALSE} head(dados) # apresenta as primeiras linhas do objeto dados ``` \framebreak \normalsize - As funções `min`, `max` e `range` retornam, respectivamente, o mínimo, o máximo e a variação de um conjunto de dados. \footnotesize ```{r exetremos, warning=FALSE, message=FALSE} min(dados$Idade) max(dados$Idade) range(dados$Idade) ``` \framebreak \normalsize - Utilizando a função `diff` podemos computar a amplitude de variação do conjunto de dados. \footnotesize ```{r amplitude, warning=FALSE, message=FALSE} diff(range(dados$Idade)) ``` \normalsize - O argumento `na.rm = TRUE` para remover os dados ausentes do conjunto antes de calcular os extremos. \footnotesize ```{r extremos2, warning=FALSE, message=FALSE} min(dados$`N de Filhos`, na.rm = TRUE) max(dados$`N de Filhos`, na.rm = TRUE) ``` \framebreak \normalsize - A variância de um conjunto de dados pode ser obtida utilizando a função `var`. O desvio padrão pode ser computado de duas formas (pelo menos): através da função `sd`, ou computando a raiz quadrada da variância utilizando a função `sqrt`. \footnotesize ```{r var, warning=FALSE, message=FALSE} var(dados$Idade) sd(dados$Idade) sqrt(var(dados$Idade)) ``` \framebreak \normalsize - O coeficiente de variação pode ser computado dividindo o desvio padrão pela média \footnotesize ```{r cv, warning=FALSE, message=FALSE} sd(dados$Idade)/mean(dados$Idade) ``` \framebreak \normalsize - Os quartis (e demais separatrizes) podem ser obtidos pela função `quantile` da seguinte forma. \footnotesize ```{r quantis, warning=FALSE, message=FALSE} quantile(dados$Idade, probs = c(0.25, 0.5, 0.75)) ``` \framebreak \normalsize - O diagrama de caixa (boxplot) pode ser obtido pela função `boxplot` \footnotesize ```{r boxplot, warning=FALSE, message=FALSE, out.width='70%', fig.align='center'} boxplot(dados$Idade, ylab = "Idade", col = "gold", border = "purple") ``` \framebreak \normalsize - Se quisermos comparar as idades de solteiros e casados utilizando o boxplot, podemos utilizar a seguinte sintaxe: \footnotesize ```{r boxplot2, warning=FALSE, message=FALSE, out.width='70%', fig.align='center'} boxplot(Idade ~ `Estado Civil`, data = dados, ylab = "Idade", col = "gold", border = "purple") ``` \normalsize ## Para casa 1. Resolver os exercícios 5, 9 e 10 do Capítulo 9.7 do livro __Fundamentos de Estatística__\footnote{Vieira, S. {\bf Fundamentos de Estatística}, Atlas, 2019, p. 153-154.} (disponível no Sabi+). 2. Para o seu levantamento estatístico, calcule os quartis, a amplitude entre quartis e construa um diagrama de caixa, de acordo com a classificação das variáveis. Compartilhe no Fórum Geral do Moodle. ## Próxima aula - Medidas de forma; - Propriedades de média e variância; - Valores padronizados ($z$-escores). ## Por hoje é só! \begin{center} {\bf Bons estudos!} \end{center} ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='50%', out.height='50%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'Statistically-Insignificant-barras01.jpg')) ``` <file_sep>--- title: "MAT02018 - Estatística Descritiva" subtitle: "Distribuições bidimensionais" fontsize: 10pt author: | | <NAME> | `<EMAIL>` institute: | | \textsc{Universidade Federal do Rio Grande do Sul} | \textsc{Instituto de Matemática e Estatística} | \textsc{Departamento de Estatística} date: | | Porto Alegre, 2022 bibliography: estatistica-descritiva.bib csl: associacao-brasileira-de-normas-tecnicas-ufrgs-initials.csl link-citations: yes --- ```{r setup, include=FALSE, purl=FALSE} options(knitr.kable.NA = '-') library(dplyr) library(knitr) ``` # Variáveis quantitativas {.allowframebreaks} - Quando as variáveis envolvidas são ambas quantitativas, podemos "categorizá-las". - Ou seja, agrupar as observações em __intervalos de classe__ para cada uma das variáveis^[Da mesma forma que foi apresentado e discutido nas notas de aula de _Distribuição de Frequências_.] e assim, analisá-las como variáveis qualitativas, apresentando a distribuição conjunta em tabelas de dupla entrada^[Se as variáveis de interesse não apresentam um número muito grande de valores distintos, uma alternativa seria não agrupar em intervalos de classe, e simplesmente utilizar uma tabela de dupla entrada considerando os próprios valores da variável.]. - Mas, além desse tipo de análise, as variáveis quantitativas são passíveis de procedimentos analíticos e gráficos mais refinados. - O __gráfico de dispersão__ é provavelmente o mais comum destes procedimentos . ## Variáveis quantitativas {.allowframebreaks} - __Exemplo:__ suponha que vinte e cinco pacientes são atendidos em uma clínica oftalmológica e os seguintes valores são registrados para __pressão intraocular__ (PIO) e __idade__. \footnotesize ```{r pio, echo=FALSE, warning=FALSE, message=FALSE} idade <- c(35, 40, 41, 44, 45, 48, 50, 50, 50, 52, 54, 55, 55, 55, 57, 58, 59, 60, 60, 61, 63, 65, 67, 71, 77) pio <- c(15, 17, 16, 18, 15, 19, 19, 18, 17, 16, 19, 18, 21, 20, 19, 20, 19, 23, 19, 22, 23, 24, 23, 24, 22) pio_df <- data.frame(id = 1:length(pio), idade, pio) kable(x = pio_df, caption = "Tabela de dados brutos.", col.names = c("ID", "Idade", "PIO"), align = 'c', format = "pandoc") ``` \framebreak \normalsize - A figura abaixo apresenta a distribuição conjunta das variáveis idade e pressão intraocular por meio de um gráfico de dispersão. ```{r pontos, echo=FALSE, warning=FALSE, message=FALSE, fig.align='center', out.width="80%"} p <- ggplot(data = pio_df, mapping = aes(x = idade, y = pio)) + geom_point(colour = I("purple4"), size = 2) + labs(x = "Idade (anos)", y = "PIO") + theme_bw() p ``` \framebreak - O gráfico de dispersão é construído pelo conjunto de pontos \alert{$\{(x_i, y_i); i = 1, 2, \ldots, n\}$} em que $x$ representa a variável do eixo horizontal (no exemplo, a variável idade) e $y$ representa a variável do eixo vertical (no exemplo, a variável pressão intraocular). - Note que cada ponto corresponde aos valores observados para um indivíduo específico. - Através do diagrama de dispersão é possível observar que, em geral, valores de idade mais altos são associados com valores de pressão intraocular mais altos (as variáveis parecem relacionadas). \framebreak - __Perguntas:__ + Qual o tipo da relação entre as variáveis Idade e PIO? + Qual a força desta relação? ## Tipos de relação {.allowframebreaks} - A relação entre duas variáveis quantitativas pode ser descrito como __positivo (direta)__ ou __negativo (inversa)__, e __linear__ ou __não-linear__. ```{r pos_neg, echo=FALSE, warning=FALSE, message=FALSE, fig.align='center', out.width="80%"} library(MASS) set.seed(1000) rho <- cbind(c(1, .9), c(.9, 1)) x <- as.data.frame(mvrnorm(n = 1000, mu = c(0,0), Sigma = rho)) names(x) <- c("X", "Y") p1 <- ggplot(data = x, mapping = aes(x = X, y = Y)) + geom_point(alpha = 0.5) + geom_vline(xintercept = 0, linetype = "dashed", col = "blue") + geom_hline(yintercept = 0, linetype = "dashed", col = "blue") + stat_ellipse(type = "norm", col = "red") + labs(title = "Relação direta") + theme_bw() rho <- cbind(c(1, -.9), c(-.9, 1)) x <- as.data.frame(mvrnorm(n = 1000, mu = c(0,0), Sigma = rho)) names(x) <- c("X", "Y") p2 <- ggplot(data = x, mapping = aes(x = X, y = Y)) + geom_point(alpha = 0.5) + geom_vline(xintercept = 0, linetype = "dashed", col = "blue") + geom_hline(yintercept = 0, linetype = "dashed", col = "blue") + stat_ellipse(type = "norm", col = "red") + labs(title = "Relação inversa") + theme_bw() library(cowplot) plot_grid(p1, p2, labels = c('', ''), label_size = 5, ncol = 2) ``` \framebreak - O gráfico de dispersão da esquerda mostra uma relação direta ou positiva entre as variáveis $X$ e $Y$, tendência destacada pela declividade positiva da elipse tracejada. - Perceba também, que o gráfico foi dividido em quatro __"quadrantes"__. - A grande maioria dos pontos está situada no primeiro e terceiro quadrantes. - Nesses quadrantes as __coordenadas dos pontos têm o mesmo sinal__, e, portanto, o __produto__ delas será sempre __positivo__. - __Somando-se o produto das coordenadas dos pontos__, o resultado será um __número positivo__, pois existem mais produtos positivos do que negativos. \framebreak - De forma análoga, o gráfico de dispersão da direita mostra uma relação inversa ou negativa, tendência também destacada pela declividade negativa da elipse tracejada, e procedendo-se como anteriormente, a __soma dos produtos das coordenadas__ será __negativa__. \framebreak \footnotesize - A gráfico a seguir apresenta um exemplo de __ausência de associação__ entre as variáveis. - A soma dos produtos das coordenadas será zero, pois cada resultado positivo tem um resultado negativo simétrico, anulando-se na soma^[Note que a soma dos produtos das coordenadas depende, e muito, do número de pontos. Além disso, a unidade de medida também pode influenciar. E é por isso, que logo em seguida, vamos considerar uma medida de correlação __padronizada__.]. ```{r cor_nula, echo=FALSE, warning=FALSE, message=FALSE, fig.align='center', out.height="60%", out.width="60%"} rho <- cbind(c(1, 0), c(0, 1)) x <- as.data.frame(mvrnorm(n = 1000, mu = c(0,0), Sigma = rho)) names(x) <- c("X", "Y") p <- ggplot(data = x, mapping = aes(x = X, y = Y)) + geom_point(alpha = 0.5) + geom_vline(xintercept = 0, linetype = "dashed", col = "blue") + geom_hline(yintercept = 0, linetype = "dashed", col = "blue") + stat_ellipse(type = "norm", col = "red") + labs(title = "Ausência de relação") + theme_bw() p ``` \normalsize ## Tipos de relação {.allowframebreaks} - A __"força" da relação__ se refere à proximidade dos pontos na nuvem. - Se pudéssemos traçar uma curva ou uma reta subjacente, teríamos a força da relação associada a proximidade dos pontos com respeito a esta curva. \framebreak ```{r linear, echo=FALSE, warning=FALSE, message=FALSE, fig.align='center', out.width="100%"} library(MASS) set.seed(1000) rho <- cbind(c(1, .9), c(.9, 1)) x <- as.data.frame(mvrnorm(n = 1000, mu = c(0,0), Sigma = rho)) names(x) <- c("X", "Y") p1 <- ggplot(data = x, mapping = aes(x = X, y = Y)) + geom_point(alpha = 0.5) + geom_smooth(method = "lm", se = FALSE, color = "red") + labs(caption = "Relação linear positiva forte") + theme_bw() rho <- cbind(c(1, .5), c(.5, 1)) x <- as.data.frame(mvrnorm(n = 1000, mu = c(0,0), Sigma = rho)) names(x) <- c("X", "Y") p2 <- ggplot(data = x, mapping = aes(x = X, y = Y)) + geom_point(alpha = 0.5) + geom_smooth(method = "lm", se = FALSE, color = "red") + labs(caption = "Relação linear positiva fraca") + theme_bw() x <- data.frame(X = runif(n = 1000, min = 0.1, max = 2)) x$Y <- 1/x$X^2 + rnorm(1000, sd = 1) p3 <- ggplot(data = x, mapping = aes(x = X, y = Y)) + geom_point(alpha = 0.5) + geom_smooth(method = "lm", formula = y ~ I(1/x^2), se = FALSE, color = "red") + labs(caption = "Relação não-linear negativa forte") + theme_bw() plot_grid(p1, p2, p3, labels = c('', '', ''), label_size = 1, ncol = 3) ``` # Coeficiente de correlação linear {.allowframebreaks} - A __força de uma associação__ entre duas variáveis quantitativas pode ser medida por um __coeficiente de correlação__. - O __coeficiente de correlação produto-momento__ é uma medida da intensidade de __associação linear__ existente entre duas variáveis quantitativas. - Também é conhecido como __coeficiente de correlação de Pearson__, pois sua fórmula de cálculo foi proposta por \structure{Karl Pearson} em \structure{1896}. - O coeficiente de correlação de Pearson é denominado por $\rho$ na população e $r$ na amostra. ## Definição {.allowframebreaks} - Dados $n$ pares __(na amostra)__ de valores \alert{$(x_1, y_1), (x_2, y_2), \ldots, (x_n, y_n)$}, chamaremos de coeficiente de correlação entre as duas variáveis $X$ e $Y$ a $$ r = \frac{1}{n-1}\sum_{i=1}^n{\left(\frac{x_i - \bar{x}}{s_x}\right)\left(\frac{y_i - \bar{y}}{s_y}\right)}, $$ em que $\bar{x}$ e $\bar{y}$ são as médias de $X$ e $Y$, e $s_x$ e $s_y$ são os desvios padrões de $X$ e $Y$. - Ou seja, o coeficiente de correlação é __a média dos produtos dos valores padronizados das variáveis__. ## Propriedades {.allowframebreaks} - O coeficiente de correlação pode variar entre $-1$ e $1$. - __Valores negativos__ de $r$ indicam uma __correlação__ do tipo __inversa (_negativa_)__; + __Interpretação:__ quando $x$ aumenta, $y$ em média diminui (ou vice-versa). - __Valores positivos__ para $r$ ocorrem quando a __correlação__ é __direta (_positiva_)__; + __Interpretação:__ $x$ e $y$ variam no mesmo sentido. \framebreak - O valor máximo (tanto $r = 1$ como $r = -1$) é obtido quando todos os pontos do diagrama de dispersão estão em uma linha reta inclinada (__correlação perfeita__). - Quando não existe correlação ($r = 0$) entre $x$ e $y$, os pontos se distribuem em nuvens circulares. - Quando os pontos formam uma nuvem cujo eixo principal é uma curva (__relação não-linear__), o valor de $r$ __não mede corretamente a associação__ entre as variáveis. \framebreak - Da definição do coeficiente de correlação obtemos a seguinte formulação alternativa^[E dependendo da situação, mais prática.]: $$ r = \frac{1}{n - 1}\sum_{i=1}^n{\left(\frac{x_i - \bar{x}}{s_x}\right)\left(\frac{y_i - \bar{y}}{s_y}\right)} = \frac{\sum_{i=1}^n{x_iy_i} - n\bar{x}\bar{y}}{\sqrt{\left(\sum_{i=1}^n{x_i^2 - n\bar{x}^2}\right)\left(\sum_{i=1}^n{y_i^2 - n\bar{y}^2}\right)}}. $$ - O numerador da expressão acima, que mede o total da concentração dos pontos pelos quatro quadrantes, dá origem a uma medida bastante usada e que definimos a seguir. ## Propriedades {.allowframebreaks} Dado $n$ pares (na amostra) de valores \alert{$(x_1, y_1), (x_2, y_2), \ldots, (x_n, y_n)$}, chamaremos de \structure{covariância} entre as duas variáveis $X$ e $Y$ a $$ cov_{xy} = \frac{\sum_{i=1}^n{(x_i-\bar{x})(y_i-\bar{y})}}{n-1}, $$ ou seja, a média ("estimada") dos produtos dos valores centrados das variáveis. - Com essa definição, obtemos a seguinte relação $$ r = \frac{cov_{xy}}{s_x\times s_y}. $$ ## Exemplos {.allowframebreaks} ```{r exemplos, echo=FALSE, warning=FALSE, message=FALSE, fig.align='center', out.height="80%", out.width="80%"} library(MASS) set.seed(1000) rho <- cbind(c(1, 0), c(0, 1)) x <- as.data.frame(mvrnorm(n = 100, mu = c(0,0), Sigma = rho)) names(x) <- c("X", "Y") p1 <- ggplot(data = x, mapping = aes(x = X, y = Y)) + geom_point(alpha = 0.5) + ylim(-3,3) + xlim(-3,3) + labs(title = "r = 0") + theme_bw() rho <- cbind(c(1, .5), c(.5, 1)) x <- as.data.frame(mvrnorm(n = 100, mu = c(0,0), Sigma = rho)) names(x) <- c("X", "Y") p2 <- ggplot(data = x, mapping = aes(x = X, y = Y)) + geom_point(alpha = 0.5) + ylim(-3,3) + xlim(-3,3) + labs(title = "r = 0,5") + theme_bw() rho <- cbind(c(1, .8), c(.8, 1)) x <- as.data.frame(mvrnorm(n = 100, mu = c(0,0), Sigma = rho)) names(x) <- c("X", "Y") p3 <- ggplot(data = x, mapping = aes(x = X, y = Y)) + geom_point(alpha = 0.5) + ylim(-3,3) + xlim(-3,3) + labs(title = "r = 0,8") + theme_bw() rho <- cbind(c(1, 1), c(1, 1)) x <- as.data.frame(mvrnorm(n = 100, mu = c(0,0), Sigma = rho)) names(x) <- c("X", "Y") p4 <- ggplot(data = x, mapping = aes(x = X, y = Y)) + geom_point(alpha = 0.5) + ylim(-3,3) + xlim(-3,3) + labs(title = "r = 1") + theme_bw() x <- data.frame(X = rnorm(n = 100)) x$Y <- 0.5* x$X p5 <- ggplot(data = x, mapping = aes(x = X, y = Y)) + geom_point(alpha = 0.5) + ylim(-3,3) + xlim(-3,3) + labs(title = "r = 1") + theme_bw() x <- data.frame(X = rnorm(n = 100)) x$Y <- 2* x$X p6 <- ggplot(data = x, mapping = aes(x = X, y = Y)) + geom_point(alpha = 0.5) + ylim(-3,3) + xlim(-3,3) + labs(title = "r = 1") + theme_bw() rho <- cbind(c(1, -1), c(-1, 1)) x <- as.data.frame(mvrnorm(n = 100, mu = c(0,0), Sigma = rho)) names(x) <- c("X", "Y") p7 <- ggplot(data = x, mapping = aes(x = X, y = Y)) + geom_point(alpha = 0.5) + ylim(-3,3) + xlim(-3,3) + labs(title = "r = -1") + theme_bw() rho <- cbind(c(1, -.7), c(-.7, 1)) x <- as.data.frame(mvrnorm(n = 100, mu = c(0,0), Sigma = rho)) names(x) <- c("X", "Y") p8 <- ggplot(data = x, mapping = aes(x = X, y = Y)) + geom_point(alpha = 0.5) + ylim(-3,3) + xlim(-3,3) + labs(title = "r = -0,7") + theme_bw() rho <- cbind(c(1, -.3), c(-.3, 1)) x <- as.data.frame(mvrnorm(n = 100, mu = c(0,0), Sigma = rho)) names(x) <- c("X", "Y") p9 <- ggplot(data = x, mapping = aes(x = X, y = Y)) + geom_point(alpha = 0.5) + ylim(-3,3) + xlim(-3,3) + labs(title = "r = -0,3") + theme_bw() plot_grid(p1, p2, p3, p4, p5, p6, p7, p8, p9, labels = rep('', 9), label_size = 5, ncol = 3) ``` \framebreak - Retomando o exemplo da pressão intraocular (PIO) e idade de 25 pacientes atendidos em uma clínica oftalmológica, podemos organizar a seguinte tabela para calcularmos o coeficiente de correlação entre estas duas variáveis. \scriptsize ```{r pio_coef, echo=FALSE, warning=FALSE, message=FALSE} idade <- c(35, 40, 41, 44, 45, 48, 50, 50, 50, 52, 54, 55, 55, 55, 57, 58, 59, 60, 60, 61, 63, 65, 67, 71, 77) pio <- c(15, 17, 16, 18, 15, 19, 19, 18, 17, 16, 19, 18, 21, 20, 19, 20, 19, 23, 19, 22, 23, 24, 23, 24, 22) pio_df <- data.frame(id = 1:length(pio), idade, pio) pio_df$idade_centrada <- pio_df$idade - mean(pio_df$idade) pio_df$pio_centrada <- pio_df$pio - mean(pio_df$pio) pio_df$idade_z <- (pio_df$idade - mean(pio_df$idade))/sd(pio_df$idade) pio_df$pio_z <- (pio_df$pio - mean(pio_df$pio))/sd(pio_df$pio) pio_df$zi_zp <- pio_df$idade_z * pio_df$pio_z aux <- colSums(pio_df) pio_df <- rbind(pio_df, aux) aux <- c(rep(NA, 25), "Soma") pio_df <- cbind(aux, pio_df) pio_df$idade_z[26] <- NA pio_df$pio_z[26] <- NA options(knitr.kable.NA = '') kable(x = pio_df, escape = FALSE, caption = "Cálculo do coeficiente de correlação.", col.names = c(" " ,"ID", "Idade ($x$)", "PIO ($y$)", "$x- \\bar{x}$", "$y- \\bar{y}$", "$\\frac{x- \\bar{x}}{s_x} = z_x$", "$\\frac{y- \\bar{y}}{s_y} = z_y$", "$z_x\\cdot z_y$"), align = 'c', digits = c(0, 0, 0, 0, 2, 2, 2, 2, 2), format.args = list(decimal.mark = ","), format = "pandoc") ``` \framebreak \normalsize E assim, temos que: - $\bar{x} = 1372/25 = 54,88$ anos e $s_x = 9,87$ anos. - $\bar{y} = 486/25 = 19,44$ mmHg e $s_y = 2,73$ mmHg. - O __coeficiente de correlação__ é $r = 20,28/25 = 0,81$, uma __relação direta (positiva)__^[Maior a idade $\Rightarrow$ Maior a pressão intraocular.] e __relativamente forte__. ## Próxima aula - Distribuições bivariadas: uma variável qualitativa e uma variável quantitativa. - Complementa`R`. ## Por hoje é só! \begin{center} {\bf Bons estudos!} \end{center} ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='50%', out.height='50%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'Statistically-Insignificant-final03.jpg')) ``` <file_sep>## ----mb, echo=FALSE, warning=FALSE, message=FALSE--------------------------------------------------------------- library(dplyr) library(readxl) library(knitr) mb_df <- read_excel(path = here::here("data", "companhia_mb.xlsx")) mb_df %>% select(N ,`Região de Procedência`, `Grau de Instrução`) %>% rename("ID" = "N") %>% # slice_head(n = 10) %>% kable(caption = "Tabela de dados brutos.", format = "pandoc") ## ----tab_dupla, echo=FALSE, warning=FALSE, message=FALSE-------------------------------------------------------- library(kableExtra) tab <- mb_df %>% select(`Região de Procedência`, `Grau de Instrução`) %>% table() %>% addmargins() row.names(tab)[4] <- "Total" colnames(tab)[4] <- "Total" kable(tab, caption = "Distribuição conjunta das frequências das variáveis grau de instrução e região de procedência.") %>% add_header_above(c("Região de Procedência", "Grau de Instrução" = 3, " ")) ## ----percent_tot_geral, echo=FALSE, warning=FALSE, message=FALSE------------------------------------------------ prop.tab <- mb_df %>% select(`Região de Procedência`, `Grau de Instrução`) %>% table() %>% prop.table() %>% addmargins() * 100 row.names(prop.tab)[4] <- "Total" colnames(prop.tab)[4] <- "Total" kable(prop.tab, digits = 0, caption = "Distribuição conjunta das frequências relativas (em porcentagem) em relação ao total geral das variáveis grau de instrução e região de procedência.") %>% add_header_above(c("Região de Procedência", "Grau de Instrução" = 3, " ")) ## ----percent_tot_coluna, echo=FALSE, warning=FALSE, message=FALSE----------------------------------------------- prop.tab <- mb_df %>% select(`Região de Procedência`, `Grau de Instrução`) %>% table() %>% prop.table(margin = 2) %>% addmargins() * 100 row.names(prop.tab)[4] <- "Total" colnames(prop.tab)[4] <- "Total" kable(prop.tab, digits = 0, caption = "Distribuição conjunta das frequências relativas (em porcentagem) em relação aos totais de colunas das variáveis grau de instrução e região de procedência.") %>% add_header_above(c("Região de Procedência", "Grau de Instrução" = 3, " ")) ## ----barras, echo=FALSE, warning=FALSE, message=FALSE, fig.align='center', out.width="100%"--------------------- library(ggplot2) library(viridis) library(reshape2) mb_gg <- mb_df %>% select(`Região de Procedência`, `Grau de Instrução`) %>% table() %>% prop.table(margin = 2) %>% melt() p <- ggplot(data = mb_gg, mapping = aes(x = `Grau de Instrução`, fill = `Região de Procedência`, y = value)) + geom_bar(position = "fill", stat = "identity") + scale_fill_viridis(discrete = T) + scale_y_continuous(labels = scales::percent) + theme_bw() + ylab("Frequências relativas") + theme(legend.position = "bottom") p ## ----gremio, echo=FALSE, warning=FALSE, message=FALSE----------------------------------------------------------- tab <- matrix(c(10, 9, 4, 17, 7, 5), byrow = T, ncol = 3, dimnames = list(c("Sem Maicon", "Com Maicon"), c("Vitórias", "Empates", "Derrotas"))) prop.tab <- addmargins(prop.table(addmargins(tab, margin = 1), margin = 1), margin = 2) * 100 row.names(prop.tab)[3] <- "Total" colnames(prop.tab)[4] <- "Total" kable(prop.tab, digits = 2, caption = "Resultados dos jogos do Grêmio em 2019.") <file_sep>--- title: "MAT02018 - Estatística Descritiva" subtitle: "Apresentações" fontsize: 10pt author: | | <NAME> | `<EMAIL>` institute: | | \textsc{Universidade Federal do Rio Grande do Sul} | \textsc{Instituto de Matemática e Estatística} | \textsc{Departamento de Estatística} date: | | Porto Alegre, 2022 # header-includes: # - \titlegraphic{\hfill\includegraphics[height=1.5cm]{logos/Logo-40-anos-estatistica.png}} --- # O professor ## Olá! ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='80%', out.height='80%', paged.print=FALSE} knitr::include_graphics(here::here('images', 'hi_my_name_is.png')) ``` ## Olá! {.allowframebreaks} \ttfamily - Desde __outubro de 2017__ eu sou Professor do __Departamento de Estatística__ e faço parte do Corpo Docente do __Programa de Pós Graduação em Epidemiologia__ da __Universidade Federal do Rio Grande do sul__ (UFRGS). Além disso, eu atuo como pesquisador no __Estudo Longitudinal de Saúde do Adulto (ELSA-Brasil)__. - Eu me formei __Bacharel em Estatística__ pelo Departamento de Estatística da UFRGS em __2007__, e __Mestre__ (__2010__) e __Doutor__ (__2014__) __em Estatística__ pelo __Programa de Pós Graduação em Estatística__ da __Universidade Federal de Minas Gerais__. - A minha dissertação de mestrado, intitulada _Técnicas estatísticas para avaliação de novos marcadores de risco: aplicações envolvendo o Modelo de Cox_, foi orientada pelos Professores <NAME> e <NAME>. - A minha tese de doutorado, intitulada _Análise hierárquica de múltiplos sistemas reparáveis_, foi orientada pelos Professores <NAME> e <NAME>. - Os meus interesses de pesquisa são __Inferência causal em epidemiologia__, __Análise de mediação__, __Modelos de predição de risco__ e __Análise de sobrevivência__. - Em estatística aplicada eu tenho interesse na __epidemiologia do Diabetes Mellitus__. # A disciplina ## Objetivos - Trabalhar o instrumental da __Estatística Descritiva__ evidenciando sua importância como primeira abordagem na análise de dados, explorando sua potencialidade no campo da aplicação às demais ciências. - Aprofundar os conceitos fundamentais da __Estatística Descritiva__, estabelecendo, via \structure{procedimentos computacionais}, o vínculo do aluno com a \structure{linguagem estatística}. - Iniciar o estudante nas técnicas da construção de __indicador__ de preços e de indicador de concentração, bem como nos procedimentos clássicos de __análise de séries temporais__. - Desenvolver a __análise exploratória de dados__ enfatizando sua importância como ferramenta inicial na interpretação de dados. ## Organização - __Disciplina:__ Estatística Descritiva - __Turma:__ U - __Modalidade:__ Ensino presencial - __Professor:__ <NAME> + e-mail: `<EMAIL>` ou `<EMAIL>` + Sala: B215 do Instituto de Matemática e Estatística ## Aulas e material didático - __Aulas__ (teóricas e práticas) + Exposição e __discussão__ dos conteúdos - __Faremos leituras semanais de artigos e capítulos de livros__ + Exemplos - __Notas de aula__ + Slides + Arquivos de rotinas em `R` - __Exercícios__ + Listas de exercícios + Para casa - __Canais de comunicação:__ + Durante as aulas + Moodle: aulas, materiais, listas de exercícios e __fórum geral__ + Sala de aula virtual: notas das avaliações + e-mail do professor ## Aulas e material didático - __Aulas:__ terças e quintas, das 10hs 30min às 12hs 10min, na Sala F115 do Instituto de Química - Campus do Vale + _10hs 30min:_ chegada + _10hs 40min:_ início + _12hs:_ fim/dúvidas + _12hs 10min:_ saída ## Aulas e material didático ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='100%', paged.print=FALSE} knitr::include_graphics(here::here('images','covid-recomendacoes.jpg')) ``` ## Aulas e material didático ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='10%', paged.print=FALSE} knitr::include_graphics(here::here('images','Rlogo.png')) ``` - Exemplos e exercícios com o apoio do computador: + `R` e `RStudio` ```{r, echo=FALSE, eval=TRUE} x <- rnorm(n = 100, mean = 10, sd = 1) ``` ```{r, echo=TRUE, eval=TRUE, fig.align='center', out.width='50%'} hist(x, col = 'black', border = 'white') ``` ## Conteúdo programático {.allowframebreaks} - __Área 1__ + Introdução/Conceitos básicos + Variáveis e medidas + Tabelas de distribuição de frequências + Análise gráfica de dados - __Área 2__ + Medidas de tendência central + Medidas de variabilidade + Medidas de forma + Distribuições bidimensionais - __Área 3__ + Números índices + Taxas de crescimento populacional + Séries temporais __(introdução)__ ## Avaliação - Serão realizadas quatro atividades de avaliação (pelo menos uma em de cada área): + duas provas ($P_1$ e $P_2$) presenciais e individuais; + dois trabalhos em grupo ($T_1$ e $T_2$). - Cada atividade de avaliação vale 10 pontos - Será realizada uma prova presencial e individual como atividade de recuperação ($PR$) + Para os alunos que não atingirem o conceito mínimo + __Esta prova abrange todo o conteúdo da disciplina__ ## Avaliação $$ MF = \frac{P_1 + P_2 + T_1 + T_2}{4} $$ + __A:__ $9 \leq MF \leq 10$ + __B:__ $7,5 \leq MF < 9$ + __C:__ $6 \leq MF < 7,5$ + __D:__ $MF < 6$ + __FF:__ se o aluno tiver frequência inferior a 75% da carga horária prevista no plano da disciplina ## Avaliação + Se $MF < 6$ e frequência mínima de 75% o aluno poderá realizar a prova de recuperação e neste caso $$ MF' = MF \times 0,4 + PR \times 0,6 $$ - __C:__ $MF' \geq 6$ - __D:__ $MF' < 6$ ## Referências bibliográficas ```{r echo=FALSE, fig.align='right', message=FALSE, warning=FALSE, out.width='15%', paged.print=FALSE} knitr::include_graphics(here('images','ctanlion.png')) ``` ### Principais \footnotesize <NAME>. __Fundamentos de Estatística__, Atlas, 2019. <NAME>. e <NAME>. __Estatística Básica__, Saraiva, 2010. <NAME>. __Noções de Probabilidade e Estatística__, Edusp, 2008. ### Complementares \footnotesize <NAME>. __Estatística Básica__, Cengage, 2018. <NAME>. __Bioestatística: princípios e aplicações__, Artmed, 2003. <NAME>. __Estatística descritiva II__, Cadernos de matemática e estatística. Série B, 1994. <NAME>. __Estatística descritiva I__, Cadernos de matemática e estatística. Série B, 1994. <NAME>. __Números índices__, Cadernos de matemática e estatística. <NAME>, 1992. # A Estatística ## Estatística em toda parte {.allowframebreaks} ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='100%', out.height='80%', paged.print=FALSE} knitr::include_graphics(here::here('images', 'estat1.jpg')) ``` ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='100%', out.height='80%', paged.print=FALSE} knitr::include_graphics(here::here('images', 'estat2.jpg')) ``` ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='100%', out.height='80%', paged.print=FALSE} knitr::include_graphics(here::here('images', 'estat3.png')) ``` ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='100%', out.height='80%', paged.print=FALSE} knitr::include_graphics(here::here('images', 'estat4.jpg')) ``` ## O que é Estatística? - Essa pergunta já vem sendo feita (e diversas vezes) há muito tempo. - A persistência da pergunta e a variedade das respostas durante os anos sugerem que a Estatística não se caracteriza como um objeto singular. - Ainda, a Estatística apresenta diferentes faces para diferentes áreas da ciência. # A Estatística Descritiva ## Estatística descritiva ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='100%', out.height='80%', paged.print=FALSE} knitr::include_graphics(here::here('images', 'Descritiva_Inferencia.png')) ``` ## Estatística descritiva - A __Estatística Descritiva__ corresponde aos procedimentos relacionados com a __coleta__, __elaboração__, __tabulação__, __análise__, __interpretação__ e __apresentação dos dados__. - Isto é, inclui as técnicas que dizem respeito à sintetização e à descrição de dados numéricos. - Tais métodos tanto podem ser gráficos como envolver análise computacional. ## Próxima aula - Introdução e conceitos básicos de Estatística. ## Por hoje é só! \begin{center} {\bf Sejam tod@s bem-vind@s!} \end{center} ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='50%', out.height='50%', paged.print=FALSE} knitr::include_graphics(here::here('images', 'Statistically-Insignificant-8.jpg')) ``` <file_sep>--- title: "MAT02018 - Estatística Descritiva" subtitle: "Medidas de variabilidade" fontsize: 10pt author: | | <NAME> | `<EMAIL>` institute: | | \textsc{Universidade Federal do Rio Grande do Sul} | \textsc{Instituto de Matemática e Estatística} | \textsc{Departamento de Estatística} date: | | Porto Alegre, 2022 bibliography: estatistica-descritiva.bib csl: associacao-brasileira-de-normas-tecnicas-ufrgs-initials.csl link-citations: yes --- ```{r setup, include=FALSE, purl=FALSE} options(knitr.kable.NA = '-') library(dplyr) library(knitr) ``` # Introdução ## Introdução {.allowframebreaks} - As medidas de tendência central são insuficientes para representar adequadamente conjuntos de dados, pois nada revelam sobre sua \structure{variabilidade}. - Tome como exemplo as notas de 5 avaliações realizadas por 2 alun@s. + \structure{Alun@ A:} 6, 6, 6, 6, 6. - __Total de pontos:__ 30; __Média:__ 6. + \alert{Alun@ B:} 7, 5, 6, 4, 8. - __Total de pontos:__ 30; __Média:__ 6. \framebreak - Para mostrar a diversidade de desempenho de ambos, necessita-se de um valor que meça a \structure{dispersão} ou a \structure{variabilidade} dos valores nos dois casos. - Nestas notas de aula vamos apresentar algumas das medidas mais utilizadas para descrever a variabilidade de um conjunto de dados. # Amplitude de variação ## Amplitude de variação {.allowframebreaks} - A medida mais simples de dispersão é a \structure{amplitude de variação ($a$)}, que é a diferença entre os valores extremos do conjunto de dados. $$ a = Max(x) - Min(x), $$ em que $Min(x)$ e $Max(x)$ representam os valores de \structure{mínimo} e \structure{máximo} de um conjunto de dados, respectivamente. \framebreak - \structure{Exemplo:} suponha que observamos a __largura da pétala__ (em centímetros) de 10 flores ```{r echo=FALSE, message=FALSE, warning=FALSE, purl=FALSE} set.seed(1309) petal.width.sample <- sample(iris$Petal.Width, 10, replace = F) knitr::kable(matrix(petal.width.sample, ncol = 5), format = "pandoc") ``` - Note que, + $Min(x) =$ `r min(petal.width.sample)`; + $Max(x) =$ `r max(petal.width.sample)`; - Logo, a amplitude é $a =$ `r max(petal.width.sample)` - `r min(petal.width.sample)` $=$ `r max(petal.width.sample) - min(petal.width.sample)` \framebreak ::: {.block} ### Comentário - Os valores de mínimo e máximo de um conjunto de dados podem ser utilizados para a __verificação de inconsistências nos dados__ com respeito a variável de interesse. - \alert{Exemplos:} + $Max(\mbox{idade}) = 170$ (anos). + $Min(\mbox{temperatura}) = -20^{\circ}$ (na série histórica de temperaturas na cidade de Porto Alegre). ::: \framebreak ::: {.block} ### Duas limitações 1. A amplitude de variação só utiliza os valores extremos do conjunto de dados. 2. Quando avaliada em amostras, frequentemente _subestima_ a amplitude populacional. ::: # Variância ## Variância {.allowframebreaks} - As principais medidas de dispersão envolvem os \structure{desvios em relação a média:} $x_1 - \bar{x}, x_2 - \bar{x}, \ldots, x_n - \bar{x}$. - Ou seja, os desvios da média são obtidos pela subtração de $\bar{x}$ de cada uma das $n$ observações da amostra, conforme mostra a figura a seguir. ```{r fig.align='center', cache=TRUE, echo=FALSE, out.width="60%", purl=FALSE} knitr::include_graphics(here::here('images', 'media_centro_gravidade.png')) ``` \framebreak - Um desvio será positivo se a observação for maior que a média (à direita da média no eixo das medidas) e negativo se a observação for menor que a média. - Se todos os desvios forem pequenos em magnitude, todos os $x_i$ estarão próximos à média e haverá pouca dispersão. - Por outro lado, se alguns desvios forem grandes, alguns $x_i$ estarão distantes de $\bar{x}$, indicando maior dispersão. \framebreak - Uma forma simples de combinar os desvios em uma única quantidade é calcular a sua média. - No entanto, temos que a soma dos desvios é igual a zero, conforme mostramos a seguir \begin{align*} \sum_{i=1}^n{(x_i - \bar{x})} &= \sum_{i=1}^n{x_i} - \sum_{i=1}^n{\bar{x}}\\ &= \sum_{i=1}^n{x_i} - n\bar{x} \\ &= \sum_{i=1}^n{x_i} - n\left(\frac{1}{n}\sum_{i=1}^n{x_i}\right) = 0. \end{align*} \framebreak - Como podemos evitar desvios negativos e positivos ao neutralizar um ao outro quando eles são combinados? - Uma possibilidade é trabalhar com os \alert{valores absolutos} e calcular o \structure{desvio médio absoluto $\frac{1}{n}\sum_{i=1}^n{|x_i - \bar{x}|}$. - Porém, a operação em valor absoluto conduz a dificuldades teóricas, e uma alternativa é considerar o \structure{quadrado dos desvios $(x_i - \bar{x})^2$ (também conhecidos como desvios quadráticos). - E dessa forma temos a definição da \structure{variância}. \framebreak - A \structure{variância} é a média dos desvios quadráticos com respeito a média. - É representada pelo símbolo $\sigma^2$ __na população__ e por $s^2$ __na amostra__. ::: {.block} ### Observação Note que, por definição \alert{(a média de dos quadrados dos desvios)}, \structure{a variância é uma medida não negativa}. ::: \framebreak - Na população calculamos a variância da seguinte forma: $$ \sigma^2 = \frac{\sum_{i=1}^N{(x_i - \mu)^2}}{N}. $$ - Na amostra, calculamos a variância da seguinte forma: $$ s^2 = \frac{\sum_{i=1}^n{(x_i - \bar{x})^2}}{n - 1}. $$ \framebreak - \structure{Exemplo:} considere mais uma vez valores observados da largura da pétala em centímetros (de 4 flores) ```{r echo=FALSE, message=FALSE, warning=FALSE, purl=FALSE} set.seed(1309) petal.width.sample <- sample(iris$Petal.Width, 4, replace = F) knitr::kable(x = matrix(petal.width.sample, ncol = 4, byrow = T), escape = FALSE, align = "c", format = "pandoc") ``` \framebreak - Note que $\bar{x} = 1.15$, e assim a variância da largura da pétala é \begin{eqnarray*} s^2 &=& \frac{(1.3 - 1.15)^2 + (1.3 - 1.15)^2 + (0.2 - 1.15)^2 + (1.8 - 1.15)^2}{4-1}\\ &=& \frac{(0.15)^2 + (0.15)^2 + (-0.95)^2 + (0.65)^2}{3}\\ &=& \frac{1.37}{3}\approx 0.46 cm^2. \end{eqnarray*} \framebreak ::: {.block} ### Observações 1. Note que unidade de medida da variável em questão fica expressa ao quadrado na variância. 2. A variância é uma medida de variabilidade em torno da média. + Se todas as observações são iguais, não há variabilidade nos dados e $s^2 = 0$. + Se os dados são muito dispersos com respeito a média, então a variabilidade é grande e $s^2$ assume um valor alto. + Se os dados são pouco dispersos em torno da média, então a variabilidade é pequena e $s^2$ assume um valor baixo. ::: \framebreak - Uma forma alternativa de calcularmos a variância é dada pela expressão^[__Sua vez:__ demonstre o resultado da expressão alternativa. Dica: desenvolva o quadrado da soma, reescreva o somatório e perceba que $\sum_{i=1}^n{x_i} = n\bar{x}$ e $n\bar{x}^2 = (\sum_{i=1}^n{x_i})^2/n$]. $$ s^2 = \frac{\sum_{i=1}^n{x_i^2} - \frac{\left(\sum_{i=1}^n{x_i}\right)^2}{n}}{n - 1}. $$ ## Variância {.allowframebreaks} - Esta expressão nos auxilia no cálculo de $s^2$ quando estamos usando uma planilha eletrônica que comporta fórmulas, ou um software como `R` que realiza operações vetoriais. ```{r echo=FALSE, message=FALSE, warning=FALSE, purl=FALSE} mat <- as.data.frame(c(7, 5, 6, 4, 8)) names(mat) <- c("$x_i$") mat$"$(x_i-\\bar{x})$" <- mat$"$x_i$" - mean(mat$"$x_i$") mat$"$(x_i-\\bar{x})^2$" <- mat$"$(x_i-\\bar{x})$"^2 mat$"$x_i^2$" <- mat$"$x_i$"^2 aux <- colSums(mat) mat <- rbind(mat, aux) aux <- c(rep(NA, 5), "Soma") mat <- cbind(aux, mat) names(mat)[1] <- "-" options(knitr.kable.NA = '') knitr::kable(mat, escape = FALSE, align = 'c') # kable_styling(font_size = 9) %>% # row_spec(6, bold = T) ``` \framebreak - Assim, temos + $\bar{x} = 30/5 = 6$; + $s^2 = \frac{\sum_{i=1}^n{(x_i - \bar{x})^2}}{n-1} = \frac{10}{4} = 2,5$. - Ou, pela fórmula alternativa, + $s^2 = \frac{\sum_{i=1}^n{x_i^2} - \frac{\left(\sum_{i=1}^n{x_i}\right)^2}{n}}{n-1} = \frac{190 - \frac{30^2}{5}}{4} = 2,5$. # Desvio padrão ## Desvio padrão {.allowframebreaks} - Uma dificuldade com a variância, como medida descritiva da dispersão, é o fato de não poder ser apresentada com a __mesma unidade__ com que a variável foi medida. - A solução é extrair a raiz quadrada positiva da variância, já que, com isso, se volta à unidade original da variável. - Essa nova medida de variabilidade é denominada \structure{desvio padrão}. \framebreak - O desvio padrão populacional é definido como $$ \sigma= \sqrt{\sigma^2}. $$ - E o desvio padrão amostral^[Também é denotado por $DP$ (de desvio padrão) ou $SD$ (do inglês _standard deviation_).] é definido como $$ s = \sqrt{s^2}. $$ - \structure{Sua vez:} calcule o desvio padrão para os exemplos anteriores. # Coeficiente de variação ## Coeficiente de variação {.allowframebreaks} - Quando se analisa a mesma variável em duas amostras, pode-se comparar os desvios padrão observados e verificar onde a variação (variabilidade) é maior. ::: {.block} ### Exemplo (espessura das sementes) + Amostra 1 apresenta desvio padrão igual 1,29mm; + Amostra 2 apresenta desvio padrão igual 0,51mm; - Logo a Amostra 2 apresenta uma menor variabilidade da espessura das sementes em relação a Amostra 1. ::: \framebreak - No entanto, o mesmo não pode ser feito em se tratando de variáveis que foram mensuradas em diferentes unidades de medida. - Se as sementes do exemplo anterior foram também pesadas, e o desvio padrão foi 0,009g para a Amostra 1, __não se pode afirmar__ que o peso das sementes é uma característica com __menor dispersão__ ("menos variável") do que a sua espessura. \framebreak - Para comparar variabilidades, neste caso, deve-se usar o \structure{coeficiente de variação ($CV$)}, que é uma medida de dispersão __independente da unidade de mensuração__ da variável. - O coeficiente de variação é definido como a razão entre o desvio padrão e a média da variável $$ CV = \frac{s}{\bar{x}}\quad \mbox{ou}\quad CV = 100\%\times \frac{s}{\bar{x}}. $$ \framebreak ::: {.block} ### Exemplo (continuação) - Suponha que a média da espessura das sementes tenha sido observada em 5 e a média do peso das sementes tenha sido 0,05. - Para a espessura, temos que $CV_{esp} = \frac{1,29}{5} = 0,258$, e para o peso, temos que $CV_{peso} = \frac{0,009}{0,05} = 0,18$. - Concluímos que o peso possui menor variabilidade que a espessura neste conjunto de dados. ::: ## Para casa 1. Resolver os exercícios 1 a 4, 6 a 8 do Capítulo 9.7 do livro __Fundamentos de Estatística__\footnote{Vieira, S. {\bf Fundamentos de Estatística}, Atlas, 2019, p. 135-136.} (disponível no Sabi+). 2. Para o seu levantamento estatístico, calcule a amplitude de variação, a variância, o desvio padrão e coeficiente de variação, de acordo com a classificação das variáveis. Compartilhe no Fórum Geral do Moodle. ## Próxima aula - Medidas de variabilidade (continuação): + Amplitude entre quartis; - Separatrizes: quantis, quartis, decis, percentis; + Gráfico de _boxplot_. + Complementa`R`. ## Por hoje é só! \begin{center} {\bf Bons estudos!} \end{center} ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='50%', out.height='50%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'Statistically-Insignificant-barras02.jpg')) ``` <file_sep>## ----echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='95%', paged.print=FALSE---- # Considerações finais: exemplos # install.packages("jpeg") # install.packages("grid") library(jpeg) library(grid) library(gapminder) library(dplyr) gapminder <- gapminder %>% mutate(pop_m = pop/1e6) gapminder07 <- gapminder %>% filter(year == 2007) img <- readJPEG(here::here("images", "hans_rosling.jpg")) # start plotting p <- ggplot(data = gapminder07, mapping = aes(x = gdpPercap, y = lifeExp, color = continent, size = pop_m)) + annotation_custom(rasterGrob(img, width = unit(1, "npc"), height = unit(1, "npc")), -Inf, Inf, -Inf, Inf) + scale_y_continuous(expand = c(0,0), limits = c(min(gapminder07$lifeExp) * 0.9, max(gapminder07$lifeExp) * 1.05)) + geom_point() + labs(x = "Renda per capita (US$)", y = "Expectativa de vida (anos)", color = "Continente", size = "População/1 milhão") + theme_bw() + theme(text = element_text(color = "gray20"), legend.position = c("top"), # posição da legenda legend.direction = "horizontal", legend.justification = 0.1, # ponto de ancora para legend.position. legend.text = element_text(size = 11, color = "gray10"), axis.text = element_text(face = "italic"), axis.title.x = element_text(vjust = -1), axis.title.y = element_text(vjust = 2), axis.ticks.y = element_blank(), # element_blank() é como removemos elementos axis.line = element_line(color = "gray40", size = 0.5), axis.line.y = element_blank(), panel.grid.major = element_line(color = "gray50", size = 0.5), panel.grid.major.x = element_blank() ) p <file_sep>## ----carrega-dados1, echo=FALSE, warning=FALSE, message=FALSE-------------------------------------------- # install.packages("readxl") library(readxl) library(stringr) library(janitor) library(dplyr) library(ggplot2) dados <- read_excel(path = here::here("data", "companhia_mb.xlsx")) set.seed(123) dados$`Grau de Instrução`[dados$`Grau de Instrução` == "ensino fundamental"] <- sample(x = c("fundamental incompleto", "fundamental completo"), size = length(dados$`Grau de Instrução`[dados$`Grau de Instrução` == "ensino fundamental"]), replace = T) dados$`Grau de Instrução`[dados$`Grau de Instrução` == "ensino médio"] <- sample(x = c("médio incompleto", "médio completo"), size = length(dados$`Grau de Instrução`[dados$`Grau de Instrução` == "ensino médio"]), replace = T) dados$`Grau de Instrução`[dados$`Grau de Instrução` == "superior"] <- sample(x = c("superior incompleto", "superior completo"), size = length(dados$`Grau de Instrução`[dados$`Grau de Instrução` == "superior"]), replace = T) dados$`Estado Civil` <- str_to_title(dados$`Estado Civil`) dados$`Grau de Instrução` <- str_to_title(dados$`Grau de Instrução`) dados$`Região de Procedência` <- str_to_title(dados$`Região de Procedência`) dados$`Grau de Instrução` <- factor(dados$`Grau de Instrução`, levels = c("Fundamental Incompleto", "Fundamental Completo", "Médio Incompleto", "Médio Completo", "Superior Incompleto", "Superior Completo")) ## ----fig-stripchart, echo=FALSE, warning=FALSE, message=FALSE, fig.align='center', out.width='90%'------- p <- ggplot(dados, aes(x = `N de Filhos`)) + geom_dotplot(fill = "steelblue") + labs(x = "Número de filhos", caption = "Fonte: Companhia MB.") + theme_classic() + theme(axis.title.y = element_blank(), axis.ticks.y = element_blank(), axis.line.y = element_blank(), axis.text.y = element_blank()) p ## ----fig-hist, echo=FALSE, warning=FALSE, message=FALSE, fig.align='center', out.width='90%'------------- p <- ggplot(data = dados) + geom_histogram(mapping = aes(x = `Salario (x Sal Min)`, y = ..density..), breaks = seq(4, 24, by = 4), fill = "steelblue", color = "white") + labs(x = "Salário (x. sal. mínimo)", y = "Densidade de frequência", title = "Distribuição salarial da seção de orçamentos", caption = "Fonte: Companhia MB.") + theme_bw() p ## ----fig-hist2, echo=FALSE, warning=FALSE, message=FALSE, fig.align='center', out.width='60%'------------ p <- ggplot(data = dados) + geom_histogram(mapping = aes(x = `Salario (x Sal Min)`, y = I(36 * ..density..)), breaks = seq(4, 24, by = 4), fill = "steelblue", color = "white") + labs(x = "Salário (x. sal. mínimo)", y = "Densidade de frequência", title = "Distribuição salarial da seção de orçamentos", caption = "Fonte: Companhia MB.") + theme_bw() p ## ----fig-freqpoly, echo=FALSE, warning=FALSE, message=FALSE, fig.align='center', out.width='90%'--------- p <- ggplot(data = dados) + geom_freqpoly(mapping = aes(x = `Salario (x Sal Min)`), breaks = seq(4, 24, by = 4), color = I("#DA70D6"), size = 1) + scale_x_continuous(breaks = seq(4, 24, by = 4)) + labs(x = "Salário (x. sal. mínimo)", y = "Frequência", title = "Distribuição salarial da seção de orçamentos", caption = "Fonte: Companhia MB.") + theme_bw() p ## ----echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='50%', out.height='50%', paged.print=FALSE---- knitr::include_graphics(here::here('images', 'Statistically-Insignificant-girafa.jpg')) <file_sep>## ----echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='80%', out.height='80%', paged.print=FALSE---- knitr::include_graphics(here::here('images', 'hi_my_name_is.png')) ## ----echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='100%', paged.print=FALSE---- knitr::include_graphics(here::here('images','covid-recomendacoes.jpg')) ## ----echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='10%', paged.print=FALSE---- knitr::include_graphics(here::here('images','Rlogo.png')) ## ---- echo=FALSE, eval=TRUE------------------------------------------------------------------- x <- rnorm(n = 100, mean = 10, sd = 1) ## ---- echo=TRUE, eval=TRUE, fig.align='center', out.width='50%'------------------------------- hist(x, col = 'black', border = 'white') ## ----echo=FALSE, fig.align='right', message=FALSE, warning=FALSE, out.width='15%', paged.print=FALSE---- knitr::include_graphics(here('images','ctanlion.png')) ## ----echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='100%', out.height='80%', paged.print=FALSE---- knitr::include_graphics(here::here('images', 'estat1.jpg')) ## ----echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='100%', out.height='80%', paged.print=FALSE---- knitr::include_graphics(here::here('images', 'estat2.jpg')) ## ----echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='100%', out.height='80%', paged.print=FALSE---- knitr::include_graphics(here::here('images', 'estat3.png')) ## ----echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='100%', out.height='80%', paged.print=FALSE---- knitr::include_graphics(here::here('images', 'estat4.jpg')) ## ----echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='100%', out.height='80%', paged.print=FALSE---- knitr::include_graphics(here::here('images', 'Descritiva_Inferencia.png')) ## ----echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='50%', out.height='50%', paged.print=FALSE---- knitr::include_graphics(here::here('images', 'Statistically-Insignificant-8.jpg')) <file_sep>--- title: "MAT02018 - Estatística Descritiva" subtitle: "Distribuição de Frequências: frequências relativa, acumulada, relativa acumulada e porcentagem" fontsize: 10pt author: | | <NAME> | `<EMAIL>` institute: | | \textsc{Universidade Federal do Rio Grande do Sul} | \textsc{Instituto de Matemática e Estatística} | \textsc{Departamento de Estatística} date: | | Porto Alegre, 2022 --- # Frequências relativa, acumulada, relativa acumulada e porcentagem ## Frequência relativa {.allowframebreaks} - É fácil entender as informações apresentadas em distribuições de frequências\footnote{A distribuição de frequências nos apresenta quantos indivíduos apresentaram determinada característica (valor da variável) no conjunto de dados que estamos observando.}. - Entretanto, as frequências dependem do \structure{tamanho da amostra}: + um em dez, é mais importante que um em um milhão. - Para ter a visão do tamanho de uma categoria \structure{em relação} ao tamanho da amostra, calculamos a frequência relativa. ## Frequência relativa {.allowframebreaks} - A \structure{frequência relativa} de uma categoria é o resultado da divisão da frequência dessa categoria pelo número de dados __(tamanho)__ da amostra. $$ \mbox{Frequência relativa} = \frac{\mbox{Frequência da categoria}}{\mbox{Tamanho da amostra}}. $$ ## Frequência relativa {.allowframebreaks} ### Observações 1. Usaremos a \structure{notação $f_i = \frac{n_i}{n}$} para indicar a __frequência relativa__ de cada classe, ou categoria, da variável. 2. A soma das frequências relativas em uma distribuição de frequências é, obrigatoriamente, igual a 1. + É fácil ver que $\sum_i{f_i} = \sum_i{\frac{n_i}{n}} = \frac{1}{n}\sum_i{n_i} = \frac{1}{n}n = 1$, em que $\sum_i{}$ representa a soma (somatório). 3. Se a tabela de frequências absolutas estiver em uma planilha eletrônica é possível utilizar o recurso da fórmula para dividir os valores de uma coluna (as frequências) por uma constante (o tamanho da amostra) para obter as frequências relativas. No `R` a ideia é semelhante (veremos na próxima aula). ## Porcentagem {.allowframebreaks} - A \structure{porcentagem} da categoria é a frequência relativa dessa categoria multiplicada por 100. $$ \mbox{Porcentagem} = \mbox{Frequência relativa} \times 100. $$ - Ou seja, \structure{$\mbox{Porcentagem}_i = f_i \times 100$} é a porcentagem da $i$-ésima categoria. \framebreak ### Observações - A __porcentagem__ é a razão expressa como fração de 100. - Você não deve confundir __porcentagem__ com __por cento__. - __Porcentagem__ significa uma parcela ou uma porção; não é, portanto, acompanhada de número. - Por exemplo: a porcentagem de alunos reprovados em matemática foi pequena. - __Por cento__ é a expressão que acompanha um número específico e é indicado com o símbolo \structure{\%}. - Por exemplo: só 2% dos alunos foram reprovados em matemática. ## Exemplo {.allowframebreaks} - Vamos ver como calcular as frequências relativas e a porcentagem para o exemplo dos empregados da seção de orçamentos da Companhia MB. \footnotesize ```{r, echo=FALSE, message=FALSE, warning=FALSE, purl=FALSE} civil <- c(rep("Solteiro", 8), rep("Casado", 7)) civil.tab <- as.data.frame(na.omit(summarytools::freq(civil, order = "freq")))["Freq"] civil.tab <- data.frame("estado_civil"= row.names(civil.tab), "freq" = civil.tab$Freq) civil.tab$freqrel <- c("$\\frac{8}{15} = 0,533$", "$\\frac{7}{15} = 0,467$", "1,000") civil.tab$porc <- c("$0,533 \\times 100 = 53,3\\%$", "$0,467 \\times 100 = 46,7\\%$", "100,0\\%") knitr::kable(civil.tab, col.names = c("Estado civil", "Frequência ($n_i$)", "Frequência relativa ($f_i$)", "Porcentagem"), align = c('l', 'c', 'c', 'c')) ``` \framebreak ### Observação - As frequências relativas, e as porcentagens, de forma mais convencional, nos permitem fazer comparações entre grupos. - Por exemplo, 30% dos alunos da Turma A preferem consultar o arquivo das notas de aula no formato PDF, enquanto que 50% dos alunos da Turma B preferem consultar o as notas de aula no formato PDF. - Ou seja, não foi necessário expressarmos o tamanho de cada turma. ## Frequência acumulada {.allowframebreaks} - A \structure{frequência acumulada} da categoria é a frequência dessa categoria somada às frequências de todas as anteriores. - Assim, temos que $$ n_{AC_i} = \sum_{k=1}^i{n_k}, $$ em que \structure{$n_{AC_i}$} é a frequência acumulada até a $i$-ésima categoria. \framebreak - Mais uma vez retomamos o exemplo da Companhia MB para apresentarmos como é calculada a frequência acumulada. ```{r, echo=FALSE, message=FALSE, warning=FALSE, purl=FALSE} filhos <- c(rep(0, 6), rep(1, 4), rep(2, 4), 3) filhos.tab <- as.data.frame(na.omit(summarytools::freq(filhos)))["Freq"] filhos.tab <- data.frame("filhos"= row.names(filhos.tab), "freq" = filhos.tab$Freq) filhos.tab$freqcum <- c("6", "$6 + 4 = 10$", "$6 + 4 + 4 = 14$", "$6 + 4 + 4 + 1= 15$", "-") knitr::kable(filhos.tab, col.names = c("Nº de filhos", "Frequência ($n_i$)", "Frequência acumulada"), align = c('l', 'c', 'c')) ``` - Assim, é possível concluir que 14 empregados da seção de orçamento tem __2 filhos ou menos__ (até dois filhos). \framebreak ### Observações 1. A __frequência acumulada__ é __apropriada__ para __variáveis__ qualitativas __ordinais__, quantitativas __discretas__ e __contínuas__. + No entanto, __não faz sentido__ apresentar a frequência acumulada de uma __variável__ qualitativa __nominal__. 2. A frequência acumulada da primeira classe é sempre igual à frequência dessa classe, por não existirem classes anteriores à primeira. 3. A última classe tem frequência acumulada igual ao total porque, para obter a frequência acumulada da última classe, somam-se as frequências de todas as outras classes. 4. Se a tabela de frequências absolutas estiver em uma planilha eletrônica é possível utilizar o recurso da fórmula para somar recursivamente os valores de uma coluna (as frequências) para obter as frequências acumuladas. No `R` a ideia é semelhante (como veremos na próxima aula). ## Frequência relativa acumulada {.allowframebreaks} - A \structure{frequência relativa acumulada} da categoria é a frequência relativa dessa categoria somada às frequências relativas de todas as anteriores. - Assim, temos que $$ f_{AC_i} = \sum_{k=1}^i{f_k} = \sum_{k=1}^i{n_k/n} = \frac{\sum_{k=1}^i{n_k}}{n} = \frac{n_{AC_i}}{n}, $$ em que \structure{$f_{AC_i}$} é a frequência relativa acumulada até a $i$-ésima categoria. \framebreak - No exemplo da Companhia MB, temos: ```{r, echo=FALSE, message=FALSE, warning=FALSE, purl=FALSE} options(knitr.kable.NA = '-') filhos <- c(rep(0, 6), rep(1, 4), rep(2, 4), 3) filhos.tab <- as.data.frame(na.omit(summarytools::freq(filhos)))["Freq"] filhos.tab <- data.frame("filhos"= row.names(filhos.tab), "freq" = filhos.tab$Freq) filhos.tab$freqrel <- filhos.tab$freq/15 filhos.tab$freqrelcum <- c(cumsum(filhos.tab$freqrel[-length(filhos.tab$freqrel)]), NA) knitr::kable(filhos.tab, col.names = c("Nº de filhos", "Frequência ($n_i$)", "Freq. relativa ($f_i$)", "Freq. relativa acumulada"), align = c('l', 'c', 'c', 'c'), digits = 3, format.args = list(decimal.mark = ',')) ``` - E assim, é possível concluir que 93% dos empregados da seção de orçamento tem __2 filhos ou menos__ (até dois filhos)\footnote{{\bf Exercício:} qual a porcentagem de empregados da seção de orçamentos com mais de um filho?}. ## Para casa 1. Resolver os exercícios 7, 8 e 9 do Capítulo 3.5 do livro __Fundamentos de Estatística__\footnote{Vieira, S. {\bf Fundamentos de Estatística}, Atlas, 2019, pg. 39-40.} (disponível no Sabi+). Utilize frequências relativas, acumuladas e percentuais, quando considerar adequado. 2. Para as variáveis do seu levantamento estatístico, construa tabelas de frequências (agora com frequências relativas, acumuladas e percentuais, quando considerar adequado) e compartilhe no Fórum Geral do Moodle. Discuta como você definiu as classes e suas amplitudes. ## Próxima aula - Introdução ao `R`. <!-- - Complementa`R`: --> <!-- + Distribuição de frequências no `R` --> <!-- + Construção de tabelas (para publicação e apresentação) --> <!-- + Um minuto de história (da estatística) --> <!-- - Atividade de Avaliação I (apresentação e instruções) --> ## Por hoje é só! \begin{center} {\bf Bons estudos!} \end{center} ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='50%', out.height='50%', paged.print=FALSE} knitr::include_graphics(here::here('images', 'Statistically-Insignificant-corda-bamba.jpg')) ``` <file_sep>--- title: "MAT02018 - Estatística Descritiva" subtitle: "Construção de gráficos (continuação)" fontsize: 10pt author: | | <NAME> | `<EMAIL>` institute: | | \textsc{Universidade Federal do Rio Grande do Sul} | \textsc{Instituto de Matemática e Estatística} | \textsc{Departamento de Estatística} date: | | Porto Alegre, 2021 bibliography: estatistica-descritiva.bib csl: associacao-brasileira-de-normas-tecnicas-ufrgs-initials.csl link-citations: yes header-includes: - \titlegraphic{\hfill\includegraphics[height=1.5cm]{logos/Logo-40-anos-estatistica.png}} --- # Apresentação gráfica de dados quantitativos ## Diagrama de pontos - O \structure{diagrama de pontos} é usado para comparar as frequências de dados discretos, desde que \structure{em pequeno número}\footnote{Também pode ser usado para comparar frequências de categorias de dados qualitativos.}. - Utilizaremos os dados da variável \structure{``Número de filhos''} dos 36 empregados da seção de orçamentos da Companhia MB para exemplificarmos a construção do diagrama de pontos. A tabela de frequências é apresentada a seguir. ```{r, echo=FALSE, message=FALSE, warning=FALSE, purl=FALSE} dados$`N de Filhos`[is.na(dados$`N de Filhos`)] <- sample(x = 0:5, size = sum(is.na(dados$`N de Filhos`)), replace = T) df_filho <- dados %>% group_by(`N de Filhos`) %>% summarise(n = n()) %>% # mutate(freq = round(100 * (n / sum(n)), 0)) %>% adorn_totals("row") knitr::kable(df_filho, col.names = c("Número de filhos", "Frequência ($n_i$)"), align = c('l', 'c')) ``` ## Diagrama de pontos {.allowframebreaks} Para construir o diagrama de pontos seguimos os seguintes passos: 1. Trace o eixo das abscissas; 2. Faça a escala, de maneira a cobrir todo o intervalo de observações; 3. Desenhe um ponto para cada uma das observações; 4. Escreva a escala e o título. \framebreak ```{r fig-stripchart, echo=FALSE, warning=FALSE, message=FALSE, fig.align='center', out.width='90%'} p <- ggplot(dados, aes(x = `N de Filhos`)) + geom_dotplot(fill = "steelblue") + labs(x = "Número de filhos", caption = "Fonte: Companhia MB.") + theme_classic() + theme(axis.title.y = element_blank(), axis.ticks.y = element_blank(), axis.line.y = element_blank(), axis.text.y = element_blank()) p ``` \framebreak ### Observação - O diagrama de pontos pode ser substituído pelo gráfico de barras, ou ainda, pelo histograma (caso da variável idade, que pode ser considerada discreta). - O \structure{histograma} será apresentado a seguir. ## Histograma {.allowframebreaks} - Dados contínuos, desde que já estejam em uma tabela de distribuição de frequências\footnote{Mais uma vez lembramos que estamos apresentando os passos para a construção de gráficos sem que seja necessário o conhecimento de recursos computacionais. Os \emph{softwares} estatísticos possuem funções próprias para a construção de gráficos, sem que seja necessário a realização destes passos.}, podem ser apresentados em um \structure{histograma}. - O \structure{histograma} é um gráfico de \structure{barras contíguas} as bases proporcionais aos intervalos de classe e a área de cada retângulo proporcional à respectiva frequência. - Pode-se usar tanto a frequência absoluta, \structure{$n_i$}, como a relativa, \structure{$f_i$}. - Indiquemos a \structure{amplitude} do \structure{$i$}-ésimo intervalo\footnote{Estamos utilizando o \emph{índice} $i$ para indexar os intervalos de classe ($C_1, C_2, \ldots, C_i, \ldots, C_I$).} por \structure{$\Delta_i$}. ## Histograma {.allowframebreaks} - Para que a \structure{área do retângulo} respectivo seja proporcional a $f_i$, a sua \structure{altura} deve ser proporcional a \structure{$f_i/\Delta_i$} (ou \structure{$n_i/\Delta_i$}), que é chamada \structure{densidade de frequência} da $i$-ésima classe. - Quanto mais dados tivermos em cada classe, mais alto deve ser o retângulo. - Com essa convenção, a __área total__ do histograma será __igual a 1__\footnote{Considere $a_i$ a área do $i$-ésimo retângulo do histograma. Então a área total é $\sum_i{a_i} = \sum_i{\Delta_i\times f_i/\Delta_i} = \sum_i{f_i} = 1$ (por que?).}. ## Histograma {.allowframebreaks} - Quando os intervalos das classes forem todos iguais a \structure{$\Delta$}, a densidade de frequência da $i$-ésima classe passa a ser \structure{$f_i/\Delta$} (ou \structure{$n_i/\Delta$}). - Vamos ver como fica o histograma para a variável \structure{``salário''} (x sal. mínimo) dos 36 empregados da seção de orçamentos da Companhia MB. - As frequências absolutas e relativas das classes são apresentadas a seguir, considerando amplitude de classe \structure{$\Delta = 4$}. ```{r, echo=FALSE, message=FALSE, warning=FALSE, purl=FALSE} options(knitr.kable.NA = '-') dados$salario <- cut(x = dados$`Salario (x Sal Min)`, breaks = c(4, 8, 12, 16, 20, 24), include.lowest = T, right = FALSE) df_salario <- dados %>% group_by(salario) %>% summarise(n = n()) %>% mutate(freq = round((n / sum(n)), 2)) %>% mutate(freq_delta = freq/4) %>% mutate(n_delta = n/4) %>% adorn_totals("row") df_salario[dim(df_salario)[1], 4:5] <- NA knitr::kable(df_salario, col.names = c("Faixa salarial", "Frequência ($n_i$)", "Freq. relativa ($f_i$)", "$f_i/\\Delta$ ($\\Delta = 4$)", "$n_i/\\Delta$ ($\\Delta = 4$)"), align = c('l', 'c', 'c', 'c', 'c')) ``` \framebreak - Note que as colunas $f_i/\Delta$ e $n_i/\Delta$ são o resultado da divisão dos valores das colunas $f_i$ e $n_i$, respectivamente, por 4, o valor da amplitude de classe ($\Delta$). - Estas colunas (separadamente) serão utilizadas para marcarmos as alturas das barras do histograma. - A seguir é apresentado o histograma para $f_i/\Delta$. \framebreak ```{r fig-hist, echo=FALSE, warning=FALSE, message=FALSE, fig.align='center', out.width='90%'} p <- ggplot(data = dados) + geom_histogram(mapping = aes(x = `Salario (x Sal Min)`, y = ..density..), breaks = seq(4, 24, by = 4), fill = "steelblue", color = "white") + labs(x = "Salário (x. sal. mínimo)", y = "Densidade de frequência", title = "Distribuição salarial da seção de orçamentos", caption = "Fonte: Companhia MB.") + theme_bw() p ``` \framebreak - Veja que salários mais altos são pouco frequentes na seção de orçamentos, e a maior parte dos empregados recebe até doze salários mínimos. A seguir apresentamos o histograma utilizando $n_i/\Delta$ como altura das barras. ```{r fig-hist2, echo=FALSE, warning=FALSE, message=FALSE, fig.align='center', out.width='60%'} p <- ggplot(data = dados) + geom_histogram(mapping = aes(x = `Salario (x Sal Min)`, y = I(36 * ..density..)), breaks = seq(4, 24, by = 4), fill = "steelblue", color = "white") + labs(x = "Salário (x. sal. mínimo)", y = "Densidade de frequência", title = "Distribuição salarial da seção de orçamentos", caption = "Fonte: Companhia MB.") + theme_bw() p ``` - É fácil ver que as duas versões do histograma possuem a \structure{mesma forma} (__mesma distribuição__), e portanto devemos obter as mesmas conclusões. \framebreak Passos para a construção do histograma: 1. Trace o sistema de eixos cartesianos. 2. Marque os extremos de classes no eixo das abscissas. 3. No eixo das ordenadas, escreva os valores das razões das frequências relativas (ou absolutas) divididas pelas amplitudes de classes ($f_i/\Delta_i$ ou $n_i/\Delta_i$). 4. Para cada classe da distribuição de frequências, trace um retângulo com base igual ao intervalo de classe e altura igual a $f_i/\Delta_i$ ou $n_i/\Delta_i$ relativa a classe. 5. Coloque título e fonte, se houver. \framebreak - __Exercício:__ construa o histograma da variável __Salário__ do exemplo __adaptado__ de [@bussab_estatistica_2017] (15 empregados da seção de orçamentos) que encontra-se na planilha física das __notas de aula "Organização dos dados"__ utilizando como extremos das classes os seguintes valores: $4; 5; 6; 7,5$ e $9,5$. ```{r, message=FALSE, echo=FALSE, out.width="100%", purl=FALSE, fig.align='center'} knitr::include_graphics(here::here('images', 'quadro_preto.jpg')) ``` ## Polígono de frequências {.allowframebreaks} - O \structure{polígono de frequências} é constituído por segmentos de retas que unem os pontos cujas coordenadas são o \structure{ponto médio} (ou ponto central) e a frequência de cada classe. - Para fechá-lo toma-se uma \structure{classe anterior a primeira} e uma \structure{posterior a última}, uma vez que ambas possuem frequência zero. \framebreak - Se considerarmos o exemplo anterior, temos a seguinte tabela de frequências. ```{r, echo=FALSE, message=FALSE, warning=FALSE, purl=FALSE} dados$salario <- cut(x = dados$`Salario (x Sal Min)`, breaks = c(0, 4, 8, 12, 16, 20, 24, 28), include.lowest = T, right = FALSE) df_salario <- dados %>% count(salario, .drop = FALSE) %>% adorn_totals("row") extremos <- seq(0, 28, by = 4) df_salario$pm <- c((extremos[-length(extremos)] + extremos[-length(extremos)] + 4) / 2, NA) knitr::kable(df_salario, col.names = c("Faixa salarial", "Frequência ($n_i$)", "Ponto central da classe"), align = c('l', 'c', 'c')) ``` \framebreak - Veja que criamos duas classes mais extremas que apresentam frequência zero. - Além disso, computamos uma coluna com o ponto central de cada classe. + \structure{Ponto central de classe} é a __média aritmética__ dos dois extremos de classe. - Assim, se a classe tem como extremos \structure{$4$} e \structure{$8$}, então o ponto central é $$ \textcolor{blue}{\frac{4 + 8}{2} = 6.} $$ \framebreak Os passos para a construção do polígono de frequências são apresentados a seguir: 1. Trace o sistema de eixos cartesianos. 2. Marque os pontos centrais de cada classe no eixo das abscissas. 3. No eixo das ordenadas, coloque as frequências. 4. Faça um ponto (pode ser apresentado em destaque ou apenas para auxiliar na costrução) para representar cada classe. Esses pontos terão abscissa igual ao ponto central de classe. A ordenada será igual à frequência da classe. 5. Marque, no eixo das abscissas, um ponto que corresponda ao ponto central de uma classe anterior à primeira. 6. Marque, no eixo das abscissas, um ponto que corresponda ao ponto central de uma classe posterior à última. 7. Una todos os pontos por segmentos de reta. 8. Coloque o título. \framebreak ```{r fig-freqpoly, echo=FALSE, warning=FALSE, message=FALSE, fig.align='center', out.width='90%'} p <- ggplot(data = dados) + geom_freqpoly(mapping = aes(x = `Salario (x Sal Min)`), breaks = seq(4, 24, by = 4), color = I("#DA70D6"), size = 1) + scale_x_continuous(breaks = seq(4, 24, by = 4)) + labs(x = "Salário (x. sal. mínimo)", y = "Frequência", title = "Distribuição salarial da seção de orçamentos", caption = "Fonte: Companhia MB.") + theme_bw() p ``` \framebreak ### Observações - Quando construímos o polígono de frequências de uma variável contínua, assim como no caso do histograma, estamos interessados na forma da distribuição. ## Para casa 1. Resolver os exercícios 3 a 6 do Capítulo 5.4 do livro __Fundamentos de Estatística__\footnote{Vieira, S. {\bf Fundamentos de Estatística}, Atlas, 2019, p. 75-76.} (disponível no Sabi+). 2. Para o seu levantamento estatístico, construa gráficos para os dados quantitativos. Compartilhe no Fórum Geral do Moodle. ## Próxima aula - Construção de gráficos com o `ggplot2`. ## Por hoje é só! \begin{center} {\bf Bons estudos!} \end{center} ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='50%', out.height='50%', paged.print=FALSE} knitr::include_graphics(here::here('images', 'Statistically-Insignificant-girafa.jpg')) ``` <file_sep>--- title: "MAT02018 - Estatística Descritiva" subtitle: "Medidas de tendência central (continuação)" fontsize: 10pt author: | | <NAME> | `<EMAIL>` institute: | | \textsc{Universidade Federal do Rio Grande do Sul} | \textsc{Instituto de Matemática e Estatística} | \textsc{Departamento de Estatística} date: | | Porto Alegre, 2021 bibliography: estatistica-descritiva.bib csl: associacao-brasileira-de-normas-tecnicas-ufrgs-initials.csl link-citations: yes header-includes: - \titlegraphic{\hfill\includegraphics[height=1.5cm]{logos/Logo-40-anos-estatistica.png}} --- ```{r setup, include=FALSE, purl=FALSE} options(knitr.kable.NA = '-') library(dplyr) library(knitr) ``` # Introdução - Nestas notas de aula, vamos apresentar outros tipos de \structure{médias}: - A \structure{média ponderada}; - A \structure{média Geométrica}; - A \structure{média harmônica}. - Tais conceitos/métodos serão apresentados em um contexto muito simples e pouco realista. - Estes métodos serão retomados em um contexto mais apropriado quando discutirmos as questões associadas ao tópico de __Números Índices__. # Média ponderada ## Média ponderada {.allowframebreaks} - A \structure{média (aritmética) ponderada} é a soma dos produtos dos dados (\structure{$x$}) pelos respectivos \structure{pesos} (\structure{$p$}), dividida pela soma dos pesos. - A \structure{média ponderada} é muito usada para notas escolares e de concursos quando se dá maior peso (o que corresponde maior importância) a determinada(s) prova(s). \framebreak - Para entender como se calcula a média ponderada, imagine que a avaliação referente a uma disciplina de Estatística será realizada de acordo com o nível de exigência de cada atividade (tabela a seguir). ```{r fig.align='center', echo=FALSE, out.width="70%", purl=FALSE} knitr::include_graphics(here::here('images', 'media_ponderada1.png')) ``` - De certa forma, uma boa nota na prova é mais importante do que participar das discussões fórum do Moodle desta disciplina. \framebreak - Assim, um aluno qualquer tem o seguinte desempenho no semestre. ```{r fig.align='center', echo=FALSE, out.width="50%", purl=FALSE} knitr::include_graphics(here::here('images', 'media_ponderada3.png')) ``` - O desempenho deste aluno na prova não foi tão bom. + O que poderíamos falar a respeito da sua aprovação? - Como vimos anteriormente, a média aritmética nos fornece uma medida resumo do desempenho deste aluno. - Porém, neste caso a soma simples das notas das avaliações não é possível, pois a prova vale três vezes a nota da discussão no fórum. - É preciso pesar (ponderar) os valores das notas. \framebreak - Utilizando \structure{$p_i$} para denotar o peso referente a cada valor \structure{$x_i$}, a média aritmética é definida por $$ \bar{x}_p = \frac{\sum_i{x_ip_i}}{\sum_i{p_i}}. $$ \framebreak - Retomando o nosso exemplo, teríamos que a média ponderada das atividades de avaliação seria \begin{eqnarray*} \bar{x}_p &=& \frac{(\mbox{Nota}_1)\times(\mbox{Peso}_1) + (\mbox{Nota}_2)\times(\mbox{Peso}_2) + (\mbox{Nota}_3)\times(\mbox{Peso}_3)}{(\mbox{Peso}_1) + (\mbox{Peso}_2) + (\mbox{Peso}_3)}\\ &=& \frac{(10)\times(1) + (8)\times(2) + (6)\times(3)}{(1) + (2) + (3)}\\ &=& \frac{44}{6} = 7,33. \end{eqnarray*} ::: {.block} ### Observação - Se consideramos o __mesmo peso__ para cada dado observado, percebemos que a média aritmética é um caso particular da média ponderada quando $p_i = p$. ::: \framebreak - __Sua vez:__ imagine que a avaliação no semestre de "Estatística Descritiva" é feita considerando que as "Avaliações da Área 1" têm peso 1 (cada uma) e as "Avaliações da Área 2 e 3" tem peso 2. - Digamos que um aluno apresentou notas 8 e 5 para as duas avaliações da área 1, e 5 e 6 para as atividades das áreas 2 e 3. + Calcule a média ponderada das notas. + Se para atingir a aprovação é necessária uma média 6, este aluno seria aprovado? + Calcule a média aritmética simples (considerando o mesmo peso para as três avaliações). + Compare os resultados. # Média geométrica {.allowframebreaks} - A \structure{média geométrica} é dada pela raiz \structure{$n$}-ésima do produtório^[O produtório será denotado pela letra grega $\Pi$ e indica que os elementos do conjunto devem ser multiplicados: $\prod_{i=1}^n{x_i} = x_1\times x_2\times \ldots \times x_n$.] de um conjunto de \structure{$n$} elementos^[Em nosso contexto, estes elementos podem ser observações de uma variável.]. - Representando o conjunto de elementos por \structure{$x_1, x_2, \ldots, x_n$}, a média geométrica é dada por $$ G = \sqrt[n]{\prod_{i=1}^{n}{x_i}} = \sqrt[n]{x_1\cdot x_2\cdot \ldots \cdot x_n}. $$ ## Média geométrica {.allowframebreaks} - A média geométrica é utilizada, basicamente, quando há variações percentuais em sequência. - \structure{Exemplo:} suponha que uma certa loja teve aumento de 20% nas vendas em um mês, 12% no mês seguinte, e 7% no terceiro mês. + A média geométrica nos fornece o aumento médio nos três meses observados. + Assim, se representamos por $x$ a variação nas vendas mensais desta loja, temos \structure{$x_1 = 1,2$ (20\%)}, \structure{$x_2 = 1,12$ (12\%)} e \structure{$x_3 = 1,07$ (7\%)}. \framebreak - A média geométrica deste conjunto de observações é dada por $$ G = \sqrt[3]{1,2\times 1,12\times 1,07} = \sqrt[3]{1,43808} \approx 1,13. $$ - Assim, a média percentual de aumento de vendas da loja nos três meses observados foi de aproximadamente 13%. \framebreak - Note que a raiz \structure{$n$}-ésima de um valor \structure{$\sqrt[n]{a}$} pode ser escrita como uma potência fracionária \structure{$a^{1/n}$}. + Assim, a média geométrica pode ser reescrita da seguinte forma $$ G = \left(\prod_{i=1}^{n}{x_i}\right)^{1/n}. $$ \framebreak - Tomando o logaritmo^[Logaritmo natural.] nos dois lados da expressão acima, temos $$ \log{G} = \frac{1}{n}\sum_{i=1}^n{\log{x_i}}. $$ - Ou seja, o __logaritmo da média geométrica__ é igual a __média aritmética da log-transformada__ da variável \structure{$x$}. + Consequentemente, temos que \structure{$G = \exp{[\bar{x}_{(\log)}]}$}, em que \structure{$\bar{x}_{(\log)}$} é a __média aritmética da log-transformada__ de \structure{$x$}. # Média harmônica {.allowframebreaks} - A \structure{média harmônica} de um conjunto de \structure{$n$} elementos é o __inverso da média aritmética dos inversos__ desses elementos. - Representando o conjunto de elementos por \structure{$x_1, x_2, \ldots, x_n$}, a média harmônica é dada por $$ H = \frac{n}{\sum_{i=1}^n{\frac{1}{x_i}}} = \frac{n}{\frac{1}{x_1} + \frac{1}{x_2} + \ldots + \frac{1}{x_n}}. $$ \framebreak - Como exemplo, considere as notas das três avaliações apresentadas da __Seção da Média ponderada__. A média harmônica das três avaliações é dada por $$ H = \frac{3}{\frac{1}{10} + \frac{1}{8} + \frac{1}{6}} = \frac{3}{0,3916667} \approx 7,65. $$ - Note que a média aritmética simples é 8. Se substituíssemos a nota 10 por uma nota 9, e a nota 6 por uma nota 7, a média aritmética simples continuaria 8, porém a média harmônica seria 7,92. + Ou seja, a média harmônica tende a aumentar quando os valores são mais próximos. ## Para casa - Resolver os exercícios 4 a 11 do Capítulo 8.5 do livro __Fundamentos de Estatística__\footnote{Vieira, S. {\bf Fundamentos de Estatística}, Atlas, 2019, p. 136-138.} (disponível no Sabi+). ## Próxima aula - Médias ponderada, geométrica e harmônica. ## Por hoje é só! \begin{center} {\bf Bons estudos!} \end{center} ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='50%', out.height='50%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'Statistically-Insignificant-barras03.jpg')) ``` <file_sep>## ----pio, echo=FALSE, warning=FALSE, message=FALSE------------------------------------------------------------------------ idade <- c(35, 40, 41, 44, 45, 48, 50, 50, 50, 52, 54, 55, 55, 55, 57, 58, 59, 60, 60, 61, 63, 65, 67, 71, 77) pio <- c(15, 17, 16, 18, 15, 19, 19, 18, 17, 16, 19, 18, 21, 20, 19, 20, 19, 23, 19, 22, 23, 24, 23, 24, 22) pio_df <- data.frame(id = 1:length(pio), idade, pio) kable(x = pio_df, caption = "Tabela de dados brutos.", col.names = c("ID", "Idade", "PIO"), align = 'c', format = "pandoc") ## ----pontos, echo=FALSE, warning=FALSE, message=FALSE, fig.align='center', out.width="80%"-------------------------------- p <- ggplot(data = pio_df, mapping = aes(x = idade, y = pio)) + geom_point(colour = I("purple4"), size = 2) + labs(x = "Idade (anos)", y = "PIO") + theme_bw() p ## ----pos_neg, echo=FALSE, warning=FALSE, message=FALSE, fig.align='center', out.width="80%"------------------------------- library(MASS) set.seed(1000) rho <- cbind(c(1, .9), c(.9, 1)) x <- as.data.frame(mvrnorm(n = 1000, mu = c(0,0), Sigma = rho)) names(x) <- c("X", "Y") p1 <- ggplot(data = x, mapping = aes(x = X, y = Y)) + geom_point(alpha = 0.5) + geom_vline(xintercept = 0, linetype = "dashed", col = "blue") + geom_hline(yintercept = 0, linetype = "dashed", col = "blue") + stat_ellipse(type = "norm", col = "red") + labs(title = "Relação direta") + theme_bw() rho <- cbind(c(1, -.9), c(-.9, 1)) x <- as.data.frame(mvrnorm(n = 1000, mu = c(0,0), Sigma = rho)) names(x) <- c("X", "Y") p2 <- ggplot(data = x, mapping = aes(x = X, y = Y)) + geom_point(alpha = 0.5) + geom_vline(xintercept = 0, linetype = "dashed", col = "blue") + geom_hline(yintercept = 0, linetype = "dashed", col = "blue") + stat_ellipse(type = "norm", col = "red") + labs(title = "Relação inversa") + theme_bw() library(cowplot) plot_grid(p1, p2, labels = c('', ''), label_size = 5, ncol = 2) ## ----cor_nula, echo=FALSE, warning=FALSE, message=FALSE, fig.align='center', out.height="60%", out.width="60%"------------ rho <- cbind(c(1, 0), c(0, 1)) x <- as.data.frame(mvrnorm(n = 1000, mu = c(0,0), Sigma = rho)) names(x) <- c("X", "Y") p <- ggplot(data = x, mapping = aes(x = X, y = Y)) + geom_point(alpha = 0.5) + geom_vline(xintercept = 0, linetype = "dashed", col = "blue") + geom_hline(yintercept = 0, linetype = "dashed", col = "blue") + stat_ellipse(type = "norm", col = "red") + labs(title = "Ausência de relação") + theme_bw() p ## ----linear, echo=FALSE, warning=FALSE, message=FALSE, fig.align='center', out.width="100%"------------------------------- library(MASS) set.seed(1000) rho <- cbind(c(1, .9), c(.9, 1)) x <- as.data.frame(mvrnorm(n = 1000, mu = c(0,0), Sigma = rho)) names(x) <- c("X", "Y") p1 <- ggplot(data = x, mapping = aes(x = X, y = Y)) + geom_point(alpha = 0.5) + geom_smooth(method = "lm", se = FALSE, color = "red") + labs(caption = "Relação linear positiva forte") + theme_bw() rho <- cbind(c(1, .5), c(.5, 1)) x <- as.data.frame(mvrnorm(n = 1000, mu = c(0,0), Sigma = rho)) names(x) <- c("X", "Y") p2 <- ggplot(data = x, mapping = aes(x = X, y = Y)) + geom_point(alpha = 0.5) + geom_smooth(method = "lm", se = FALSE, color = "red") + labs(caption = "Relação linear positiva fraca") + theme_bw() x <- data.frame(X = runif(n = 1000, min = 0.1, max = 2)) x$Y <- 1/x$X^2 + rnorm(1000, sd = 1) p3 <- ggplot(data = x, mapping = aes(x = X, y = Y)) + geom_point(alpha = 0.5) + geom_smooth(method = "lm", formula = y ~ I(1/x^2), se = FALSE, color = "red") + labs(caption = "Relação não-linear negativa forte") + theme_bw() plot_grid(p1, p2, p3, labels = c('', '', ''), label_size = 1, ncol = 3) ## ----exemplos, echo=FALSE, warning=FALSE, message=FALSE, fig.align='center', out.height="80%", out.width="80%"------------ library(MASS) set.seed(1000) rho <- cbind(c(1, 0), c(0, 1)) x <- as.data.frame(mvrnorm(n = 100, mu = c(0,0), Sigma = rho)) names(x) <- c("X", "Y") p1 <- ggplot(data = x, mapping = aes(x = X, y = Y)) + geom_point(alpha = 0.5) + ylim(-3,3) + xlim(-3,3) + labs(title = "r = 0") + theme_bw() rho <- cbind(c(1, .5), c(.5, 1)) x <- as.data.frame(mvrnorm(n = 100, mu = c(0,0), Sigma = rho)) names(x) <- c("X", "Y") p2 <- ggplot(data = x, mapping = aes(x = X, y = Y)) + geom_point(alpha = 0.5) + ylim(-3,3) + xlim(-3,3) + labs(title = "r = 0,5") + theme_bw() rho <- cbind(c(1, .8), c(.8, 1)) x <- as.data.frame(mvrnorm(n = 100, mu = c(0,0), Sigma = rho)) names(x) <- c("X", "Y") p3 <- ggplot(data = x, mapping = aes(x = X, y = Y)) + geom_point(alpha = 0.5) + ylim(-3,3) + xlim(-3,3) + labs(title = "r = 0,8") + theme_bw() rho <- cbind(c(1, 1), c(1, 1)) x <- as.data.frame(mvrnorm(n = 100, mu = c(0,0), Sigma = rho)) names(x) <- c("X", "Y") p4 <- ggplot(data = x, mapping = aes(x = X, y = Y)) + geom_point(alpha = 0.5) + ylim(-3,3) + xlim(-3,3) + labs(title = "r = 1") + theme_bw() x <- data.frame(X = rnorm(n = 100)) x$Y <- 0.5* x$X p5 <- ggplot(data = x, mapping = aes(x = X, y = Y)) + geom_point(alpha = 0.5) + ylim(-3,3) + xlim(-3,3) + labs(title = "r = 1") + theme_bw() x <- data.frame(X = rnorm(n = 100)) x$Y <- 2* x$X p6 <- ggplot(data = x, mapping = aes(x = X, y = Y)) + geom_point(alpha = 0.5) + ylim(-3,3) + xlim(-3,3) + labs(title = "r = 1") + theme_bw() rho <- cbind(c(1, -1), c(-1, 1)) x <- as.data.frame(mvrnorm(n = 100, mu = c(0,0), Sigma = rho)) names(x) <- c("X", "Y") p7 <- ggplot(data = x, mapping = aes(x = X, y = Y)) + geom_point(alpha = 0.5) + ylim(-3,3) + xlim(-3,3) + labs(title = "r = -1") + theme_bw() rho <- cbind(c(1, -.7), c(-.7, 1)) x <- as.data.frame(mvrnorm(n = 100, mu = c(0,0), Sigma = rho)) names(x) <- c("X", "Y") p8 <- ggplot(data = x, mapping = aes(x = X, y = Y)) + geom_point(alpha = 0.5) + ylim(-3,3) + xlim(-3,3) + labs(title = "r = -0,7") + theme_bw() rho <- cbind(c(1, -.3), c(-.3, 1)) x <- as.data.frame(mvrnorm(n = 100, mu = c(0,0), Sigma = rho)) names(x) <- c("X", "Y") p9 <- ggplot(data = x, mapping = aes(x = X, y = Y)) + geom_point(alpha = 0.5) + ylim(-3,3) + xlim(-3,3) + labs(title = "r = -0,3") + theme_bw() plot_grid(p1, p2, p3, p4, p5, p6, p7, p8, p9, labels = rep('', 9), label_size = 5, ncol = 3) ## ----pio_coef, echo=FALSE, warning=FALSE, message=FALSE------------------------------------------------------------------- idade <- c(35, 40, 41, 44, 45, 48, 50, 50, 50, 52, 54, 55, 55, 55, 57, 58, 59, 60, 60, 61, 63, 65, 67, 71, 77) pio <- c(15, 17, 16, 18, 15, 19, 19, 18, 17, 16, 19, 18, 21, 20, 19, 20, 19, 23, 19, 22, 23, 24, 23, 24, 22) pio_df <- data.frame(id = 1:length(pio), idade, pio) pio_df$idade_centrada <- pio_df$idade - mean(pio_df$idade) pio_df$pio_centrada <- pio_df$pio - mean(pio_df$pio) pio_df$idade_z <- (pio_df$idade - mean(pio_df$idade))/sd(pio_df$idade) pio_df$pio_z <- (pio_df$pio - mean(pio_df$pio))/sd(pio_df$pio) pio_df$zi_zp <- pio_df$idade_z * pio_df$pio_z aux <- colSums(pio_df) pio_df <- rbind(pio_df, aux) aux <- c(rep(NA, 25), "Soma") pio_df <- cbind(aux, pio_df) pio_df$idade_z[26] <- NA pio_df$pio_z[26] <- NA options(knitr.kable.NA = '') kable(x = pio_df, escape = FALSE, caption = "Cálculo do coeficiente de correlação.", col.names = c(" " ,"ID", "Idade ($x$)", "PIO ($y$)", "$x- \\bar{x}$", "$y- \\bar{y}$", "$\\frac{x- \\bar{x}}{s_x} = z_x$", "$\\frac{y- \\bar{y}}{s_y} = z_y$", "$z_x\\cdot z_y$"), align = 'c', digits = c(0, 0, 0, 0, 2, 2, 2, 2, 2), format.args = list(decimal.mark = ","), format = "pandoc") <file_sep>## ----mb, echo=FALSE, warning=FALSE, message=FALSE---------------------------------------------------------------- library(dplyr) library(readxl) library(knitr) mb_df <- read_excel(path = here::here("data", "companhia_mb.xlsx")) mb_df %>% select(N ,`Região de Procedência`, `Grau de Instrução`) %>% rename("ID" = "N") %>% # slice_head(n = 10) %>% kable(caption = "Tabela de dados brutos.") ## ----tab_dupla, echo=FALSE, warning=FALSE, message=FALSE--------------------------------------------------------- library(kableExtra) tab <- mb_df %>% select(`Região de Procedência`, `Grau de Instrução`) %>% table() %>% addmargins() row.names(tab)[4] <- "Total" colnames(tab)[4] <- "Total" kable(tab, caption = "Distribuição conjunta das frequências das variáveis grau de instrução e região de procedência.") %>% add_header_above(c("Região de Procedência", "Grau de Instrução" = 3, " ")) ## ----percent_tot_geral, echo=FALSE, warning=FALSE, message=FALSE------------------------------------------------- prop.tab <- mb_df %>% select(`Região de Procedência`, `Grau de Instrução`) %>% table() %>% prop.table() %>% addmargins() * 100 row.names(prop.tab)[4] <- "Total" colnames(prop.tab)[4] <- "Total" kable(prop.tab, digits = 0, caption = "Distribuição conjunta das frequências relativas (em porcentagem) em relação ao total geral das variáveis grau de instrução e região de procedência.") %>% add_header_above(c("Região de Procedência", "Grau de Instrução" = 3, " ")) ## ----percent_tot_coluna, echo=FALSE, warning=FALSE, message=FALSE------------------------------------------------ prop.tab <- mb_df %>% select(`Região de Procedência`, `Grau de Instrução`) %>% table() %>% prop.table(margin = 2) %>% addmargins() * 100 row.names(prop.tab)[4] <- "Total" colnames(prop.tab)[4] <- "Total" kable(prop.tab, digits = 0, caption = "Distribuição conjunta das frequências relativas (em porcentagem) em relação aos totais de colunas das variáveis grau de instrução e região de procedência.") %>% add_header_above(c("Região de Procedência", "Grau de Instrução" = 3, " ")) ## ----barras, echo=FALSE, warning=FALSE, message=FALSE, fig.align='center', out.height="100%"--------------------- library(ggplot2) library(viridis) library(reshape2) mb_gg <- mb_df %>% select(`Região de Procedência`, `Grau de Instrução`) %>% table() %>% prop.table(margin = 2) %>% melt() p <- ggplot(data = mb_gg, mapping = aes(x = `Grau de Instrução`, fill = `Região de Procedência`, y = value)) + geom_bar(position = "fill", stat = "identity") + scale_fill_viridis(discrete = T) + scale_y_continuous(labels = scales::percent) + theme_bw() + ylab("Frequências relativas") + theme(legend.position = "bottom") p ## ----gremio, echo=FALSE, warning=FALSE, message=FALSE------------------------------------------------------------ tab <- matrix(c(10, 9, 4, 17, 7, 5), byrow = T, ncol = 3, dimnames = list(c("Sem Maicon", "Com Maicon"), c("Vitórias", "Empates", "Derrotas"))) prop.tab <- addmargins(prop.table(addmargins(tab, margin = 1), margin = 1), margin = 2) * 100 row.names(prop.tab)[3] <- "Total" colnames(prop.tab)[4] <- "Total" kable(prop.tab, digits = 2, caption = "Resultados dos jogos do Grêmio em 2019.") ## ----pio, echo=FALSE, warning=FALSE, message=FALSE--------------------------------------------------------------- idade <- c(35, 40, 41, 44, 45, 48, 50, 50, 50, 52, 54, 55, 55, 55, 57, 58, 59, 60, 60, 61, 63, 65, 67, 71, 77) pio <- c(15, 17, 16, 18, 15, 19, 19, 18, 17, 16, 19, 18, 21, 20, 19, 20, 19, 23, 19, 22, 23, 24, 23, 24, 22) pio_df <- data.frame(id = 1:length(pio), idade, pio) kable(x = pio_df, caption = "Tabela de dados brutos.", col.names = c("ID", "Idade", "PIO"), align = 'c') ## ----pontos, echo=FALSE, warning=FALSE, message=FALSE, fig.align='center', out.height="100%"--------------------- p <- ggplot(data = pio_df, mapping = aes(x = idade, y = pio)) + geom_point(colour = I("purple4"), size = 2) + labs(x = "Idade (anos)", y = "PIO") + theme_bw() p ## ----pos_neg, echo=FALSE, warning=FALSE, message=FALSE, fig.align='center', out.height="100%", out.width="100%"---- library(MASS) set.seed(1000) rho <- cbind(c(1, .9), c(.9, 1)) x <- as.data.frame(mvrnorm(n = 1000, mu = c(0,0), Sigma = rho)) names(x) <- c("X", "Y") p1 <- ggplot(data = x, mapping = aes(x = X, y = Y)) + geom_point(alpha = 0.5) + geom_vline(xintercept = 0, linetype = "dashed", col = "blue") + geom_hline(yintercept = 0, linetype = "dashed", col = "blue") + stat_ellipse(type = "norm", col = "red") + labs(title = "Relação direta") + theme_bw() rho <- cbind(c(1, -.9), c(-.9, 1)) x <- as.data.frame(mvrnorm(n = 1000, mu = c(0,0), Sigma = rho)) names(x) <- c("X", "Y") p2 <- ggplot(data = x, mapping = aes(x = X, y = Y)) + geom_point(alpha = 0.5) + geom_vline(xintercept = 0, linetype = "dashed", col = "blue") + geom_hline(yintercept = 0, linetype = "dashed", col = "blue") + stat_ellipse(type = "norm", col = "red") + labs(title = "Relação inversa") + theme_bw() library(cowplot) plot_grid(p1, p2, labels = c('', ''), label_size = 5, ncol = 2) ## ----cor_nula, echo=FALSE, warning=FALSE, message=FALSE, fig.align='center', out.height="100%", out.width="100%"---- rho <- cbind(c(1, 0), c(0, 1)) x <- as.data.frame(mvrnorm(n = 1000, mu = c(0,0), Sigma = rho)) names(x) <- c("X", "Y") p <- ggplot(data = x, mapping = aes(x = X, y = Y)) + geom_point(alpha = 0.5) + geom_vline(xintercept = 0, linetype = "dashed", col = "blue") + geom_hline(yintercept = 0, linetype = "dashed", col = "blue") + stat_ellipse(type = "norm", col = "red") + labs(title = "Ausência de relação") + theme_bw() p ## ----linear, echo=FALSE, warning=FALSE, message=FALSE, fig.align='center', out.height="100%", out.width="100%"---- library(MASS) set.seed(1000) rho <- cbind(c(1, .9), c(.9, 1)) x <- as.data.frame(mvrnorm(n = 1000, mu = c(0,0), Sigma = rho)) names(x) <- c("X", "Y") p1 <- ggplot(data = x, mapping = aes(x = X, y = Y)) + geom_point(alpha = 0.5) + geom_smooth(method = "lm", se = FALSE, color = "red") + labs(caption = "Relação linear positiva forte") + theme_bw() rho <- cbind(c(1, .5), c(.5, 1)) x <- as.data.frame(mvrnorm(n = 1000, mu = c(0,0), Sigma = rho)) names(x) <- c("X", "Y") p2 <- ggplot(data = x, mapping = aes(x = X, y = Y)) + geom_point(alpha = 0.5) + geom_smooth(method = "lm", se = FALSE, color = "red") + labs(caption = "Relação linear positiva fraca") + theme_bw() x <- data.frame(X = runif(n = 1000, min = 0.1, max = 2)) x$Y <- 1/x$X^2 + rnorm(1000, sd = 1) p3 <- ggplot(data = x, mapping = aes(x = X, y = Y)) + geom_point(alpha = 0.5) + geom_smooth(method = "lm", formula = y ~ I(1/x^2), se = FALSE, color = "red") + labs(caption = "Relação não-linear negativa forte") + theme_bw() plot_grid(p1, p2, p3, labels = c('', '', ''), label_size = 1, ncol = 3) ## ----exemplos, echo=FALSE, warning=FALSE, message=FALSE, fig.align='center', out.height="100%", out.width="100%"---- library(MASS) set.seed(1000) rho <- cbind(c(1, 0), c(0, 1)) x <- as.data.frame(mvrnorm(n = 100, mu = c(0,0), Sigma = rho)) names(x) <- c("X", "Y") p1 <- ggplot(data = x, mapping = aes(x = X, y = Y)) + geom_point(alpha = 0.5) + ylim(-3,3) + xlim(-3,3) + labs(title = "r = 0") + theme_bw() rho <- cbind(c(1, .5), c(.5, 1)) x <- as.data.frame(mvrnorm(n = 100, mu = c(0,0), Sigma = rho)) names(x) <- c("X", "Y") p2 <- ggplot(data = x, mapping = aes(x = X, y = Y)) + geom_point(alpha = 0.5) + ylim(-3,3) + xlim(-3,3) + labs(title = "r = 0,5") + theme_bw() rho <- cbind(c(1, .8), c(.8, 1)) x <- as.data.frame(mvrnorm(n = 100, mu = c(0,0), Sigma = rho)) names(x) <- c("X", "Y") p3 <- ggplot(data = x, mapping = aes(x = X, y = Y)) + geom_point(alpha = 0.5) + ylim(-3,3) + xlim(-3,3) + labs(title = "r = 0,8") + theme_bw() rho <- cbind(c(1, 1), c(1, 1)) x <- as.data.frame(mvrnorm(n = 100, mu = c(0,0), Sigma = rho)) names(x) <- c("X", "Y") p4 <- ggplot(data = x, mapping = aes(x = X, y = Y)) + geom_point(alpha = 0.5) + ylim(-3,3) + xlim(-3,3) + labs(title = "r = 1") + theme_bw() x <- data.frame(X = rnorm(n = 100)) x$Y <- 0.5* x$X p5 <- ggplot(data = x, mapping = aes(x = X, y = Y)) + geom_point(alpha = 0.5) + ylim(-3,3) + xlim(-3,3) + labs(title = "r = 1") + theme_bw() x <- data.frame(X = rnorm(n = 100)) x$Y <- 2* x$X p6 <- ggplot(data = x, mapping = aes(x = X, y = Y)) + geom_point(alpha = 0.5) + ylim(-3,3) + xlim(-3,3) + labs(title = "r = 1") + theme_bw() rho <- cbind(c(1, -1), c(-1, 1)) x <- as.data.frame(mvrnorm(n = 100, mu = c(0,0), Sigma = rho)) names(x) <- c("X", "Y") p7 <- ggplot(data = x, mapping = aes(x = X, y = Y)) + geom_point(alpha = 0.5) + ylim(-3,3) + xlim(-3,3) + labs(title = "r = -1") + theme_bw() rho <- cbind(c(1, -.7), c(-.7, 1)) x <- as.data.frame(mvrnorm(n = 100, mu = c(0,0), Sigma = rho)) names(x) <- c("X", "Y") p8 <- ggplot(data = x, mapping = aes(x = X, y = Y)) + geom_point(alpha = 0.5) + ylim(-3,3) + xlim(-3,3) + labs(title = "r = -0,7") + theme_bw() rho <- cbind(c(1, -.3), c(-.3, 1)) x <- as.data.frame(mvrnorm(n = 100, mu = c(0,0), Sigma = rho)) names(x) <- c("X", "Y") p9 <- ggplot(data = x, mapping = aes(x = X, y = Y)) + geom_point(alpha = 0.5) + ylim(-3,3) + xlim(-3,3) + labs(title = "r = -0,3") + theme_bw() plot_grid(p1, p2, p3, p4, p5, p6, p7, p8, p9, labels = rep('', 9), label_size = 5, ncol = 3) ## ----pio_coef, echo=FALSE, warning=FALSE, message=FALSE---------------------------------------------------------- idade <- c(35, 40, 41, 44, 45, 48, 50, 50, 50, 52, 54, 55, 55, 55, 57, 58, 59, 60, 60, 61, 63, 65, 67, 71, 77) pio <- c(15, 17, 16, 18, 15, 19, 19, 18, 17, 16, 19, 18, 21, 20, 19, 20, 19, 23, 19, 22, 23, 24, 23, 24, 22) pio_df <- data.frame(id = 1:length(pio), idade, pio) pio_df$idade_centrada <- pio_df$idade - mean(pio_df$idade) pio_df$pio_centrada <- pio_df$pio - mean(pio_df$pio) pio_df$idade_z <- (pio_df$idade - mean(pio_df$idade))/sd(pio_df$idade) pio_df$pio_z <- (pio_df$pio - mean(pio_df$pio))/sd(pio_df$pio) pio_df$zi_zp <- pio_df$idade_z * pio_df$pio_z aux <- colSums(pio_df) pio_df <- rbind(pio_df, aux) aux <- c(rep(NA, 25), "Soma") pio_df <- cbind(aux, pio_df) pio_df$idade_z[26] <- NA pio_df$pio_z[26] <- NA options(knitr.kable.NA = '') kable(x = pio_df, escape = FALSE, caption = "Cálculo do coeficiente de correlação.", col.names = c(" " ,"ID", "Idade ($x$)", "PIO ($y$)", "$x- \\bar{x}$", "$y- \\bar{y}$", "$\\frac{x- \\bar{x}}{s_x} = z_x$", "$\\frac{y- \\bar{y}}{s_y} = z_y$", "$z_x\\cdot z_y$"), align = 'c', digits = c(0, 0, 0, 0, 2, 2, 2, 2, 2), format.args = list(decimal.mark = ",")) ## ----sal_grupo, echo=FALSE, warning=FALSE, message=FALSE--------------------------------------------------------- mb_df_arrange <- mb_df %>% dplyr::select("N" ,`Salario (x Sal Min)`, `Grau de Instrução`) %>% rename("ID" = "N") %>% arrange(`Grau de Instrução`) mb_df_arrange %>% kable(caption = "Tabela de dados brutos.", align = 'c', format.args = list(decimal.mark = ",")) %>% kable_styling() %>% row_spec(which(mb_df_arrange$`Grau de Instrução` == "ensino fundamental"), background = "lightsalmon") %>% row_spec(which(mb_df_arrange$`Grau de Instrução` == "ensino médio"), background = "lightblue") %>% row_spec(which(mb_df_arrange$`Grau de Instrução` == "superior"), background = "lightyellow") ## ----sal_grupo_res, echo=FALSE, warning=FALSE, message=FALSE----------------------------------------------------- tab <- mb_df_arrange %>% group_by(`Grau de Instrução`) %>% summarize(n = n(), `Média` = mean(`Salario (x Sal Min)`), `D. Padrão` = sd(`Salario (x Sal Min)`), `Variância` = var(`Salario (x Sal Min)`), `Min` = min(`Salario (x Sal Min)`), `Q1` = quantile(`Salario (x Sal Min)`, 0.25), `Q2` = quantile(`Salario (x Sal Min)`, 0.5), `Q3` = quantile(`Salario (x Sal Min)`, 0.75), `Max` = max(`Salario (x Sal Min)`) ) tab2 <- mb_df_arrange %>% summarize(n = n(), `Média` = mean(`Salario (x Sal Min)`), `D. Padrão` = sd(`Salario (x Sal Min)`), `Variância` = var(`Salario (x Sal Min)`), `Min` = min(`Salario (x Sal Min)`), `Q1` = quantile(`Salario (x Sal Min)`, 0.25), `Q2` = quantile(`Salario (x Sal Min)`, 0.5), `Q3` = quantile(`Salario (x Sal Min)`, 0.75), `Max` = max(`Salario (x Sal Min)`) ) tab2$`Grau de Instrução` <- "Global" tab2 <- tab2[c(names(tab2)[10],names(tab2)[-10])] tab <- rbind(tab, tab2) kable(tab, caption = "Medidas-resumo para a variável salário, segundo o grau de instrução, na Companhia MB.", align = 'c', digits = c(0,0,rep(2,8)), format.args = list(decimal.mark = ",")) %>% kable_styling() %>% row_spec(1, background = "lightsalmon") %>% row_spec(2, background = "lightblue") %>% row_spec(3, background = "lightyellow") ## ----sal_bp, echo=FALSE, warning=FALSE, message=FALSE, fig.align='center', out.height="100%", out.width="100%"---- mb_df_arrange$cor <- NULL mb_df_arrange$cor <- ifelse(mb_df_arrange$`Grau de Instrução` == "ensino fundamental", "lightsalmon", ifelse(mb_df_arrange$`Grau de Instrução` == "ensino médio", "lightblue", "lightyellow")) bp <- ggplot(data = mb_df_arrange, mapping = aes(x = `Grau de Instrução`, y = `Salario (x Sal Min)`)) + geom_boxplot(fill = c("lightsalmon", "lightblue", "lightyellow")) + theme_bw() bp ## ----iris, echo=FALSE, message=FALSE, warning=FALSE-------------------------------------------------------------- set.seed(1000) iris_ex_1 <- iris %>% filter(Species == "setosa") %>% slice_head(n = 10) iris_ex_2 <- iris %>% filter(Species == "versicolor") %>% slice_head(n = 10) iris_ex_3 <- iris %>% filter(Species == "virginica") %>% slice_head(n = 10) iris_ex <- rbind(iris_ex_1, iris_ex_2) iris_ex <- rbind(iris_ex, iris_ex_3) iris_ex %>% kable(caption = "Tabela de dados brutos.", align = 'c', col.names = c("comprimento da sépala", "largura da sépala", "comprimento da pétala", "largura da pétala", "espécie"), format.args = list(decimal.mark = ",")) <file_sep>--- # title: "Estatística Descritiva" title: "Organização dos dados" author: "<NAME>, Dep. de Estatística - UFRGS" date: '`r paste(stringr::str_to_title(format(Sys.Date(), "%B")), format(Sys.Date(), "%Y"), sep = " de ")`' output: tufte::tufte_handout: citation_package: natbib latex_engine: xelatex tufte::tufte_html: self_contained: true tufte::tufte_book: citation_package: natbib latex_engine: xelatex bibliography: estatistica-descritiva.bib csl: associacao-brasileira-de-normas-tecnicas-ufrgs-initials.csl link-citations: yes --- ```{r setup, include=FALSE, purl=FALSE} library(tufte) # invalidate cache when the tufte version changes knitr::opts_chunk$set(tidy = FALSE, cache.extra = packageVersion('tufte')) options(htmltools.dir.version = FALSE) ``` # Introdução Agora que já discutimos alguns __conceitos básicos__ de estatística e as etapas gerais de um __levantamento estatístico__, vamos apresentar como é feito o __registro__ e a __organização de dados__ referentes a uma certa coleta de dados. Começaremos com a __planilha__ para o registro dos dados e a __tabela de dados brutos__ resultante. Logo em seguida, discutiremos como fazer a __apuração dos dados__. <!-- e o obtenção da __distribuição de frequências__. --> # Coleta de dados - __Lembrando:__ a __estatística__ é a ciência que tem por objetivo orientar a _coleta_, o _resumo_, a _apresentação_, a _análise_ e a _interpretação_ de dados. Para _coletar dados_, o pesquisador necessitará armazenar os dados coletados em algum lugar. Assim, se faz necessário organizar uma _planilha_. Com o advento da computação, grande parte dos profissionais da área de estatística registram dados em uma _planilha eletrônica_^[Softwares como _Calc_ (OpenOffice), _Microsoft Excel_ (Office) e _Google Sheets_ (Google) são exemplos de _softwares_ que trabalham com planilhas eletrônicas.]. No entanto, os dados também podem ser registrados em meio físico como, por exemplo, fichas, cadernos ou cadernetas, ou seja, a chamada _planilha física_. As planilhas eletrônicas podem ser construídas a partir de planilhas físicas ou serem alimentadas por algum __instrumento de coleta__ em meio eletrônico (formulário ou questionário)^[O _Google Forms_, por exemplo, cria e alimenta uma planilha eletrônica a partir do formulário de coleta.]. Vamos apresentar como se desenha uma planilha física para registro dos dados. Se você tiver possibilidade, pode experimentar como organizar os dados em uma planilha eletrônica. - __Planilha__ é o documento que armazena os dados coletados, distribuindo-os em linhas e colunas^[Ou seja, planilhas são "matrizes de dados".]. Em planilhas eletrônicas, geralmente, as linhas são numeradas e as colunas são indicadas por letras maiúsculas. ```{r fig-plan_eletro, fig.margin = TRUE, fig.cap = "Célula D2, no cruzamento da coluna D com a linha 2.", fig.width=1.5, fig.height=1.5, cache=TRUE, message=FALSE, echo=FALSE, out.width="100%", purl=FALSE} knitr::include_graphics(here::here('images', 'planilha_eletro.png')) ``` __Exemplo:__ considere o exemplo adaptado de [@morettin_estatistica_2017]. Um pesquisador está interessado em fazer um levantamento sobre alguns aspectos socioeconômicos dos empregados da seção de orçamentos da Companhia MB, um grupo de 15 pessoas. Temos a seguinte planilha (Fig. 2) para registrar os dados do grupo. ```{r fig-plan_fis, fig.cap = "Planilha física para o registro dos dados do grupo de 15 empregados da seção de orçamentos da Companhia MB.", cache=TRUE, echo=FALSE, out.width="100%", purl=FALSE} knitr::include_graphics(here::here('images', 'planilha_fisica.png')) ``` - __Dados brutos__ são os dados na forma em que foram coletados, sem qualquer tipo de tratamento. Após a coleta de dados, o pesquisador tem em sua planilha o registro dos dados brutos (Fig. 3). ```{r fig-dados_brutos, fig.cap = "Planilha com o registro dos dados brutos do grupo de 15 empregados da seção de orçamentos da Companhia MB. EF, EM e S representam Ensino Fundamental, Ensino Médio e Superior, respectivamente.", cache=TRUE, echo=FALSE, out.width="100%", purl=FALSE} knitr::include_graphics(here::here('images', 'dados_brutos.png')) ``` - O que podemos falar sobre as variáveis coletadas? - Qual a informação podemos apresentar sobre os dados coletados? Para responder tais perguntadas, precisaremos __resumir__ os dados de alguma forma. Na próxima seção discutiremos a etapa de __apuração dos dados__. - __Exercício:__ construa a planilha para o registro do levantamento dos dados planejado nas aulas anteriores. # Apuração dos dados - __Apuração__ é o processo de retirar os dados da planilha e organizá-los, para apresentação. No exemplo apresentado anteriormente, foram coletadas as seguintes variáveis: estado civil, grau de instrução, número de filhos, salário, idade e região de procedência. Note que estas são variáveis de diferentes tipos^[__Exercício:__ classifique cada uma destas variáveis em _qualitativa nominal_, _qualitativa ordinal_, _quantitativa discreta_ e _quantitativa contínua_.]. ## Apuração de dados nominais Se quisermos saber quantos solteiros e quantos casados trabalham na seção de orçamentos da Companhia MB devemos escrever os valores possíveis da variável _estado civil_^[__Pergunta:__ a ordem de escrita dos valores possíveis da variável _estado civil_ importa? Por que?]. ```{r fig-apura_0, cache=TRUE, echo=FALSE, out.width="70%", purl=FALSE} knitr::include_graphics(here::here('images', 'apura_0.png')) ``` Logo após, precisamos inspecionar cada registro da tabela de dados brutos e marcar um traço ao lado de _solteiro_, para cada indivíduo solteiro inspecionado, e um traço ao lado de _casado_ para cada indivíduo casado inspecionado. A cada quatro traços, corta-se com um traço, e este conjunto representa uma contagem de cinco indivíduos ^[No inglês, _tally marks_ (marcas de registro).]. ```{r fig-apura_1, cache=TRUE, echo=FALSE, out.width="70%", purl=FALSE} knitr::include_graphics(here::here('images', 'apura_1.png')) ``` Desta forma, verificamos que na seção de orçamentos da Companhia MB trabalham oito solteiros e sete casados. Duas outras formas alternativas de se fazer a apuração dos dados são apresentadas a seguir^[__Comentário:__ é fácil apurar uma pequena massa de dados, como no caso do exemplo. Já uma grande massa de dados tornará a tarefa difícil e entediante. Além disso, com um grande volume de dados, a _probabilidade_ de incorrermos em erros aumenta! Necessitaremos do auxílio de _pacotes estatísticos_!]. ```{r fig-apura_2, cache=TRUE, echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='100%', purl=FALSE} library(cowplot) library(ggplot2) p1 <- ggdraw() + draw_image(here::here('images', 'apura_2.png'), scale = 0.9) p2 <- ggdraw() + draw_image(here::here('images', 'apura_3.png'), scale = 0.9) plot_grid(p1, p2) ``` ## Apuração de dados ordinais Para apurar dados de grau de instrução (variável qualitativa ordinal), o procedimento é similar ao adotado para apurar dados nominais. A diferença é que, para dados ordinais, __impõe-se uma ordem__. Contudo, a apuração se faz por contagem. ```{r fig-apura_4, cache=TRUE, echo=FALSE, out.width="70%", purl=FALSE} knitr::include_graphics(here::here('images', 'apura_4.png')) ``` ## Apuração de dados discretos Para apurar o número de filhos (variável quantitativa discreta), também devemos fazer uma contagem. Escrevemos os resultados respeitando a ordem numérica. ```{r fig-apura_5, cache=TRUE, echo=FALSE, out.width="70%", purl=FALSE} knitr::include_graphics(here::here('images', 'apura_5.png')) ``` ## Apuração de dados contínuos Em geral, os dados contínuos são apresentados na forma como foram coletados, porque assumem valores diferentes, mesmo em amostras pequenas. É o caso da variável idade no exemplo considerado: os empregados da seção de orçamentos da Companhia MB tinham idades diferentes. No entanto, é possível organizar as idades por faixas, como veremos nas aulas seguintes. # Exercícios Faça uma pequena coleta de dados incluindo pelo menos uma variável de cada tipo (_qualitativa nominal_, _qualitativa ordinal_, _quantitativa discreta_ e _quantitativa contínua_). 1. Organize uma planilha (física ou eletrônica) para o registro dos dados coletados. 2. Faça a coleta e preencha a planilha para obter os dados brutos. 3. Faça a apuração dos dados e comente brevemente sobre os resultados encontrados. # Complementa`R` Esta seção é complementar. São apresentadas algumas poucas funções em `R` relacionadas a discussão da aula. Para tal, vamos utilizar o exemplo original de [@morettin_estatistica_2017] sobre os dados dos empregados da seção de orçamentos da Companhia MB. A planilha eletrônica correspondente encontra-se no arquivo `companhia_mb.xlsx`. Vamos começar carregando os dados para o `R`. Existem várias formas de se carregar __arquivos de dados__ em diferentes no `R`. Como arquivo de interesse encontra-se no formato do Excel (xlsx), vamos utilizar a função `read_excel` do pacote `readxl`^[Caso você não tenha o pacote, instale-o:`install.packages("readxl")`.]. ```{r carrega-dados0, echo=TRUE, eval=FALSE, warning=FALSE, message=FALSE} # install.packages("readxl") library(readxl) dados <- read_excel(path = "companhia_mb.xlsx") ``` ```{r carrega-dados1, echo=FALSE, warning=FALSE, message=FALSE, purl=FALSE} # install.packages("readxl") library(readxl) dados <- read_excel(path = here::here("data", "companhia_mb.xlsx")) ``` ```{r carrega-dados2, warning=FALSE, message=FALSE} class(dados) # classe do objeto dados dim(dados) # dimensão do objeto dados ``` Note que o objeto `dados` é uma tabela de dados bruto. ```{r carrega-dados3, warning=FALSE, message=FALSE} head(dados) # apresenta as primeiras linhas do objeto dados ``` A função `table` retorna contagens dos valores de cada variável, e portanto, podemos utilizar esta função para a apuração dos dados. ```{r apuracao, warning=FALSE, message=FALSE} table(dados$`Estado Civil`) # apura dados nominais table(dados$`Grau de Instrução`) # apura dados ordinais table(dados$`N de Filhos`) # apura dados discretos dados$Idade # apura dados contínuos ``` <!-- # Distribuição de frequências --><file_sep>## ----carrega-dados0, echo=TRUE, eval=FALSE, warning=FALSE, message=FALSE------------------------------------------------ ## # install.packages("readxl") library(readxl) dados <- read_excel(path = here::here("data", "companhia_mb.xlsx")) ## ----carrega-dados2, warning=FALSE, message=FALSE----------------------------------------------------------------------- class(dados) # classe do objeto dados dim(dados) # dimensão do objeto dados ## ----carrega-dados3, warning=FALSE, message=FALSE----------------------------------------------------------------------- head(dados) # apresenta as primeiras linhas do objeto dados ## ----freqs, warning=FALSE, message=FALSE-------------------------------------------------------------------------------- table(dados$`Estado Civil`) table(dados$`Grau de Instrução`) table(dados$`N de Filhos`) ## ----freqs2, warning=FALSE, message=FALSE------------------------------------------------------------------------------- dados$Idade.classes <- cut(x = dados$Idade, breaks = c(20, 29, 39, 49), include.lowest = TRUE) table(dados$Idade.classes) ## ----freqs3, warning=FALSE, message=FALSE------------------------------------------------------------------------------- table(dados$`Estado Civil`) / 36 table(dados$`Grau de Instrução`) / length(dados$`Grau de Instrução`) ## ----freqs4, warning=FALSE, message=FALSE------------------------------------------------------------------------------- prop.table(x = table(dados$`N de Filhos`)) ## ----porcentagem, warning=FALSE, message=FALSE-------------------------------------------------------------------------- prop.table(x = table(dados$Idade.classes)) * 100 ## ----porcentagem2, warning=FALSE, message=FALSE------------------------------------------------------------------------- round(x = prop.table(x = table(dados$Idade.classes)) * 100, digits = 2) ## ----freqcum, warning=FALSE, message=FALSE------------------------------------------------------------------------------ cumsum(x = table(dados$`Grau de Instrução`)) cumsum(x = prop.table(x = table(dados$`Grau de Instrução`))) cumsum(x = prop.table(x = table(dados$`N de Filhos`)) * 100) cumsum(round(x = prop.table(x = table(dados$Idade.classes)) * 100, digits = 2)) ## ----freqtab, warning=FALSE, message=FALSE------------------------------------------------------------------------------ df.freq <- data.frame(Idade = unique(dados$Idade.classes), Freq = as.numeric(table(dados$Idade.classes)), FreqRel = as.numeric(prop.table(table(dados$Idade.classes))), Porcentagem = as.numeric(prop.table(table(dados$Idade.classes)) * 100), FreqAcumulada = as.numeric(cumsum(table(dados$Idade.classes))), FreqRelAcumulada = as.numeric(cumsum(prop.table(table(dados$Idade.classes))))) df.freq ## ----freqtab2, warning=FALSE, message=FALSE----------------------------------------------------------------------------- # install.packages("summarytools") summarytools::freq(dados$`Grau de Instrução`) <file_sep>## ----mb, echo=FALSE, warning=FALSE, message=FALSE--------------------------------------------------------------- library(dplyr) library(readxl) library(knitr) library(kableExtra) library(ggplot2) mb_df <- read_excel(path = here::here("data", "companhia_mb.xlsx")) ## ----sal_grupo, echo=FALSE, warning=FALSE, message=FALSE-------------------------------------------------------- mb_df_arrange <- mb_df %>% dplyr::select("N" ,`Salario (x Sal Min)`, `Grau de Instrução`) %>% rename("ID" = "N") %>% arrange(`Grau de Instrução`) mb_df_arrange[1:18,] %>% kable(#caption = "Tabela de dados brutos.", align = 'c', format.args = list(decimal.mark = ","), format = "latex") %>% kable_styling() %>% row_spec(which(mb_df_arrange[1:18,]$`Grau de Instrução` == "ensino fundamental"), background = "lightsalmon") %>% row_spec(which(mb_df_arrange[1:18,]$`Grau de Instrução` == "ensino médio"), background = "lightblue") %>% row_spec(which(mb_df_arrange[1:18,]$`Grau de Instrução` == "superior"), background = "lightyellow") ## ----sal_grupo2, echo=FALSE, warning=FALSE, message=FALSE------------------------------------------------------- mb_df_arrange[19:36,] %>% kable(#caption = "Tabela de dados brutos.", align = 'c', format.args = list(decimal.mark = ","), format = "latex") %>% kable_styling() %>% row_spec(which(mb_df_arrange[19:36,]$`Grau de Instrução` == "ensino fundamental"), background = "lightsalmon") %>% row_spec(which(mb_df_arrange[19:36,]$`Grau de Instrução` == "ensino médio"), background = "lightblue") %>% row_spec(which(mb_df_arrange[19:36,]$`Grau de Instrução` == "superior"), background = "lightyellow") ## ----sal_grupo_res, echo=FALSE, warning=FALSE, message=FALSE---------------------------------------------------- tab <- mb_df_arrange %>% group_by(`Grau de Instrução`) %>% summarize(n = n(), `Média` = mean(`Salario (x Sal Min)`), `D. Padrão` = sd(`Salario (x Sal Min)`), `Variância` = var(`Salario (x Sal Min)`), `Min` = min(`Salario (x Sal Min)`), `Q1` = quantile(`Salario (x Sal Min)`, 0.25), `Q2` = quantile(`Salario (x Sal Min)`, 0.5), `Q3` = quantile(`Salario (x Sal Min)`, 0.75), `Max` = max(`Salario (x Sal Min)`) ) tab2 <- mb_df_arrange %>% summarize(n = n(), `Média` = mean(`Salario (x Sal Min)`), `D. Padrão` = sd(`Salario (x Sal Min)`), `Variância` = var(`Salario (x Sal Min)`), `Min` = min(`Salario (x Sal Min)`), `Q1` = quantile(`Salario (x Sal Min)`, 0.25), `Q2` = quantile(`Salario (x Sal Min)`, 0.5), `Q3` = quantile(`Salario (x Sal Min)`, 0.75), `Max` = max(`Salario (x Sal Min)`) ) tab2$`Grau de Instrução` <- "Global" tab2 <- tab2[c(names(tab2)[10],names(tab2)[-10])] tab <- rbind(tab, tab2) kable(tab, caption = "Medidas-resumo para a variável salário, segundo o grau de instrução, na Companhia MB.", align = 'c', digits = c(0,0,rep(2,8)), format.args = list(decimal.mark = ","), format = "latex") %>% kable_styling() %>% row_spec(1, background = "lightsalmon") %>% row_spec(2, background = "lightblue") %>% row_spec(3, background = "lightyellow") ## ----sal_bp, echo=FALSE, warning=FALSE, message=FALSE, fig.align='center', out.width="100%"--------------------- mb_df_arrange$cor <- NULL mb_df_arrange$cor <- ifelse(mb_df_arrange$`Grau de Instrução` == "ensino fundamental", "lightsalmon", ifelse(mb_df_arrange$`Grau de Instrução` == "ensino médio", "lightblue", "lightyellow")) bp <- ggplot(data = mb_df_arrange, mapping = aes(x = `Grau de Instrução`, y = `Salario (x Sal Min)`)) + geom_boxplot(fill = c("lightsalmon", "lightblue", "lightyellow")) + theme_bw() bp ## ----iris, echo=FALSE, message=FALSE, warning=FALSE------------------------------------------------------------- set.seed(1000) iris_ex_1 <- iris %>% filter(Species == "setosa") %>% slice_head(n = 10) iris_ex_2 <- iris %>% filter(Species == "versicolor") %>% slice_head(n = 10) iris_ex_3 <- iris %>% filter(Species == "virginica") %>% slice_head(n = 10) iris_ex <- rbind(iris_ex_1, iris_ex_2) iris_ex <- rbind(iris_ex, iris_ex_3) iris_ex %>% kable(caption = "Tabela de dados brutos.", align = 'c', col.names = c("comprimento da sépala", "largura da sépala", "comprimento da pétala", "largura da pétala", "espécie"), format.args = list(decimal.mark = ","), format = "pandoc") <file_sep>--- title: "MAT02018 - Estatística Descritiva" subtitle: "Distribuições bidimensionais" fontsize: 10pt author: | | <NAME> | `<EMAIL>` institute: | | \textsc{Universidade Federal do Rio Grande do Sul} | \textsc{Instituto de Matemática e Estatística} | \textsc{Departamento de Estatística} date: | | Porto Alegre, 2022 bibliography: estatistica-descritiva.bib csl: associacao-brasileira-de-normas-tecnicas-ufrgs-initials.csl link-citations: yes --- ```{r setup, include=FALSE, purl=FALSE} options(knitr.kable.NA = '-') library(dplyr) library(knitr) ``` # Apresentação {.allowframebreaks} - Até o presente momento vimos como organizar, resumir e apresentar informações referentes a uma __única variável__. - Muito do interesse em se coletar diversas variáveis em um levantamento estatístico está em analisar o \structure{comportamento conjunto} de __duas ou mais variáveis__. - Algumas questões de pesquisa, relacionadas a este objetivo, que podem ser listadas: - As variáveis estão relacionadas \structure{(associadas, correlacionadas)}? - Como caraterizar esta realação? - Qual a força desta relação? - Nestas breves notas de aula vamos apresentar formas de organização e apresentação de \structure{distribuições bidimensionais}^[Distribuições de duas variáveis. Nestas notas de aula nos concentraremos no caso de duas variáveis, mas tais ideias podem ser generalizados para o caso de mais que duas variáveis.] de frequências, assim como o cálculo e interpretação de medidas resumo. # Introdução {.allowframebreaks} - Quando consideramos duas variáveis^[Ou ainda, dois grupos em que as mesmas variáveis foram mensuradas, formando dois conjuntos de dados. Exemplo: a atividade física é mensurada (por algum instrumento de medida: questionário de hábitos de vida; acelerômetro) em dois grupos de indivíduos: fumantes e não-fumantes.], podemos ter três situações: - As duas variáveis são qualitativas; - As duas variáveis são quantitativas; - Uma variável é qualitativa e outra é quantitativa. - As técnicas de análise de dados nas três situações são diferentes. ## Introdução {.allowframebreaks} - Quando as variáveis são qualitativas, os dados são resumidos e apresentados em __tabelas de dupla entrada__^[Também conhecidas como __tabelas de contingência__.]. - Quando as duas variáveis são quantitativas, __gráficos de dispersão__ são apropriados. - Quando temos uma variável qualitativa e outra quantitativa, em geral, analisamos o que acontece com a variável quantitativa agrupada em classes^[Ou seja, a variável qualitativa é interpretada como uma variável de grupo de observações.]. ## Introdução {.allowframebreaks} - Contudo, em todas as situações, o objetivo é encontrar as possíveis relações __(associações)__ entre as duas variáveis. - Essas relações podem ser detectadas por meio de métodos gráficos e medidas resumo. - Interpretaremos a existência de associação como uma \structure{``mudança''} de opinião sobre o comportamento de uma variável na presença de informação sobre a segunda variável. \framebreak :::{.block} ### Exemplificando Os clientes de um serviço de __Streaming__ têm a __comédia__ como gênero preferido de filme. Se estratificamos os clientes entre _jovens_ e _idosos_, esta preferência se mantém a mesma nos dois grupos? + Se a preferência por gênero de filme muda entre as faixas etárias, então temos uma __associação__ entre as variáveis __idade__ e __preferência por gênero de filme__. Tal informação pode ser utilizada para a definição de campanhas de _marketing_ específicas para cada faixa etária, com sugestões "mais precisas". ::: # Variáveis qualitativas {.allowframebreaks} - Considere como exemplo o conjunto de dados coletados de empregados da seção de orçamentos da Companhia MB [@bussab_estatistica_2017]. Suponha que queiramos analisar o comportamento conjunto das variáveis __grau de instrução__ e __região de procedência__. \footnotesize ```{r mb, echo=FALSE, warning=FALSE, message=FALSE} library(dplyr) library(readxl) library(knitr) mb_df <- read_excel(path = here::here("data", "companhia_mb.xlsx")) mb_df %>% select(N ,`Região de Procedência`, `Grau de Instrução`) %>% rename("ID" = "N") %>% # slice_head(n = 10) %>% kable(caption = "Tabela de dados brutos.", format = "pandoc") ``` \framebreak \normalsize - A __distribuição conjunta de frequências__ é apresentada logo a seguir, na tabela de dupla entrada: \footnotesize ```{r tab_dupla, echo=FALSE, warning=FALSE, message=FALSE} library(kableExtra) tab <- mb_df %>% select(`Região de Procedência`, `Grau de Instrução`) %>% table() %>% addmargins() row.names(tab)[4] <- "Total" colnames(tab)[4] <- "Total" kable(tab, caption = "Distribuição conjunta das frequências das variáveis grau de instrução e região de procedência.", align = "cccc", format = "latex") %>% add_header_above(c("Região de Procedência", "Grau de Instrução" = 3, " ")) ``` \normalsize \framebreak Note que cada elemento do corpo da tabela fornece a frequência observada das __realizações simultâneas__ de __Região de Procedência__ ($X$) e __Grau de Instrução__ ($Y$). - Assim, observamos quatro indivíduos da capital com ensino fundamental, sete do interior com ensino médio, etc. - A __linha dos totais__ fornece a \structure{distribuição (unidimensional)} da variável __Grau de Instrução__, ao passo que a __coluna dos totais__ fornece a \structure{distribuição} da variável __Região de Procedência__. - As distribuições assim obtidas são chamadas tecnicamente de __distribuições marginais__, enquanto a tabela do slide anterior constitui a __distribuição conjunta__^[Podemos concluir que a partir da distribuição conjunta das variáveis ($n_{ij}$) é possível obter as distribuições marginais de cada uma das variáveis, somando os elementos da linha ($n_{i\cdot} = \sum_{j = 1}^J{n_{ij}},\ i = 1, \ldots, I$), ou da coluna ($n_{\cdot j} = \sum_{i = 1}^I{n_{ij}},\ j = 1, \ldots, J$). Por outro lado, não é possível obter a distribuição conjunta a partir das distribuições marginais.] de $X$ e $Y$. ## Variáveis qualitativas {.allowframebreaks} - Assim como no caso unidimensional, podemos ter interesse não só em __frequências absolutas__, mas também em __frequências relativas__ e __porcentagens__. - Mas aqui existem três possibilidades de expressarmos a proporção de cada casela: - Em relação ao total geral; - Em relação ao total de cada linha; - Em relação ao total de cada coluna. - De acordo com o objetivo do problema em estudo, uma delas será a mais conveniente. \framebreak ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='100%', purl=FALSE} knitr::include_graphics(here::here('images', 'percent_linha.jpg')) ``` \framebreak ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='100%', purl=FALSE} knitr::include_graphics(here::here('images', 'percent_coluna.jpg')) ``` \framebreak - A tabela a seguir apresenta a distribuição conjunta das frequências relativas, expressas como proporções do total geral. - Ou seja, cada elemento da tabela abaixo é obtido pela divisão da frequência absoluta (apresenta na tabela anterior) pelo total de observações, $n = 36$ (e multiplicação por $100$). \footnotesize ```{r percent_tot_geral, echo=FALSE, warning=FALSE, message=FALSE} prop.tab <- mb_df %>% select(`Região de Procedência`, `Grau de Instrução`) %>% table() %>% prop.table() %>% addmargins() * 100 row.names(prop.tab)[4] <- "Total" colnames(prop.tab)[4] <- "Total" kable(prop.tab, digits = 0, caption = "Distribuição conjunta das frequências relativas (em porcentagem) em relação ao total geral das variáveis grau de instrução e região de procedência.", align = "cccc", format = "latex") %>% add_header_above(c("Região de Procedência", "Grau de Instrução" = 3, " ")) ``` \normalsize \framebreak - Podemos, então, afirmar que \structure{11\%} dos funcionários __vêm da capital e possuem o ensino fundamental__. - Os totais nas margens fornecem as distribuições unidimensionais de cada uma das variáveis. + Por exemplo, 31% dos indivíduos vêm da capital, 33% do interior e 36% de outras regiões. \framebreak - A tabela seguinte apresenta a distribuição das proporções em relação ao total das colunas. - Os elementos da coluna de _ensino fundamental_ foram obtidos por dividir as frequências absolutas ($4$, $3$ e $5$) por $12$, o total desta coluna. \footnotesize ```{r percent_tot_coluna, echo=FALSE, warning=FALSE, message=FALSE} prop.tab <- mb_df %>% select(`Região de Procedência`, `Grau de Instrução`) %>% table() %>% prop.table(margin = 2) %>% addmargins() * 100 row.names(prop.tab)[4] <- "Total" colnames(prop.tab)[4] <- "Total" kable(prop.tab, digits = 0, caption = "Distribuição conjunta das frequências relativas (em porcentagem) em relação aos totais de colunas das variáveis grau de instrução e região de procedência.", align = "cccc", format = "latex") %>% add_header_above(c("Região de Procedência", "Grau de Instrução" = 3, " ")) ``` \normalsize \framebreak - Podemos dizer que, entre os empregados com instrução até o ensino fundamental, 33% vêm da capital, ao passo que entre os empregados com ensino médio, 28% vêm da capital. - Esse tipo de tabela serve para comparar a distribuição da procedência dos indivíduos conforme o grau de instrução. - Se tivéssemos interesse em comparar a distribuição do grau de instrução dos indivíduos conforme a procedência, então calcularíamos as frequências relativas em relação aos totais das linhas^[__Sua vez:__ construa a distribuição conjunta de frequências relativas (em porcentagem) em relação aos totais de linhas.]. ## Variáveis qualitativas {.allowframebreaks} - Uma forma alternativa de apresentação da distribuição conjunta de duas variáveis qualitativas é feita por meio de gráficos. - Em geral, utiliza-se o \structure{gráfico de barras}. \framebreak ```{r barras, echo=FALSE, warning=FALSE, message=FALSE, fig.align='center', out.width="90%"} library(ggplot2) library(viridis) library(reshape2) mb_gg <- mb_df %>% select(`Região de Procedência`, `Grau de Instrução`) %>% table() %>% prop.table(margin = 1) %>% melt() mb_gg <- mb_gg %>% group_by(`Região de Procedência`) %>% mutate(value_pos = cumsum(value) - (0.5 * value)) %>% mutate(value_lab = round(value * 100, 1)) p <- ggplot(data = mb_gg, mapping = aes(x = `Região de Procedência`, y = value)) + geom_bar(mapping = aes(fill = rev(`Grau de Instrução`)), stat = "identity") + geom_text(mapping = aes(y = value_pos, label = value_lab), col = "white", vjust = 0) + scale_fill_viridis(discrete = T) + scale_y_continuous(labels = scales::percent) + labs(y = "Frequências relativas", fill = "Grau de Instrução") + theme_bw() + theme(legend.position = "bottom") p ``` \framebreak - Uma pergunta frequente de pesquisadores e usuários de Estatística é sobre a associação entre duas variáveis. - Buscar explicar como se comporta uma variável em função da distribuição de outra tem sido o objetivo de vários estudos que utilizam a Estatística como ferramenta auxiliar. - Em outras palavras, a distribuição de frequências da variável $Y$ muda de acordo com o nível (categoria) da variável $X$? - Em caso afirmativo, diremos que as variáveis são __associadas__, ou dependem uma da outra. - Caso contrário, diremos que as variáveis são __independentes__, e portanto, não há associação entre as variáveis. \framebreak ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='90%', purl=FALSE} knitr::include_graphics(here::here('images', 'associacao_mascara_covid.jpg')) ``` [Estudo da UFRGS mostra que uso de máscara reduz em 87% a chance de contrair covid-19](https://www.ufrgs.br/coronavirus/base/estudo-da-ufrgs-mostra-que-uso-de-mascara-reduz-em-87-a-chance-de-contrair-covid-19/) \framebreak - __Exemplo:__ em setembro de 2019, o jornalismo esportivo divulgava os resultados das partidas disputas pelo Grêmio. + Uma questão era observada pelos especialistas: sem o jogador Maicon, o Grêmio tinha apresentado um desempenho pior. + Na tabela a seguir são apresentadas as frequências relativas (em porcentagem) de 52 partidas disputadas até aquele momento. \footnotesize ```{r gremio, echo=FALSE, warning=FALSE, message=FALSE} tab <- matrix(c(10, 9, 4, 17, 7, 5), byrow = T, ncol = 3, dimnames = list(c("Sem Maicon", "Com Maicon"), c("Vitórias", "Empates", "Derrotas"))) prop.tab <- addmargins(prop.table(addmargins(tab, margin = 1), margin = 1), margin = 2) * 100 row.names(prop.tab)[3] <- "Total" colnames(prop.tab)[4] <- "Total" kable(prop.tab, digits = 2, caption = "Resultados dos jogos do Grêmio em 2019.", align = "cccc", format = "latex", format.args = list(decimal.mark = ",")) ``` \normalsize \framebreak - Note que as frequências são relativas a linha. - Assim, observamos que sem considerar que Maicon jogou, o jogo resulta em vitória do Grêmio em aproximadamente 52% das vezes. - Mas, quando Maicon está em campo esta porcentagem muda para aproximadamente 59%. - Quando ele não está em campo, a porcentagem de vitórias cai para 43%. \framebreak - Assim, poderíamos concluir que a presença de Maicon no jogo foi importante para o desempenho do time do Grêmio no ano de 2019. - Em outras palavras, as variáveis _resultado do jogo do Grêmio_ e _escalação do time do Grêmio_ são associadas (ou dependentes), pois a distribuição de frequências da variável _resultado do jogo do Grêmio_ muda conforme o nível (categoria) da variável _escalação do time do Grêmio_^[Um caminho natural a partir deste resultado seria quantificar o grau de dependência entre estas variáveis. A medida resumo mais utilizada é __coeficiente de contingência__, mais conhecido como o $\chi^2$ de Pearson. Não apresentaremos nestas notas o coeficiente de contingência, mas recomendamos a leitura complementar deste.]. ## Próxima aula - Distribuições bivariadas: variáveis quantitativas. ## Por hoje é só! \begin{center} {\bf Bons estudos!} \end{center} ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='50%', out.height='50%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'Statistically-Insignificant-final02.jpg')) ``` <file_sep>## ----carrega-dados0, echo=TRUE, eval=FALSE, warning=FALSE, message=FALSE------------------------ ## # install.packages("readxl") library(readxl) dados <- read_excel(path = here::here("companhia_mb.xlsx")) ## ----carrega-dados2, warning=FALSE, message=FALSE----------------------------------------------- class(dados) # classe do objeto dados dim(dados) # dimensão do objeto dados ## ----carrega-dados3, warning=FALSE, message=FALSE----------------------------------------------- head(dados) # apresenta as primeiras linhas do objeto dados ## ----exetremos, warning=FALSE, message=FALSE---------------------------------------------------- min(dados$Idade) max(dados$Idade) range(dados$Idade) ## ----amplitude, warning=FALSE, message=FALSE---------------------------------------------------- diff(range(dados$Idade)) ## ----extremos2, warning=FALSE, message=FALSE---------------------------------------------------- min(dados$`N de Filhos`, na.rm = TRUE) max(dados$`N de Filhos`, na.rm = TRUE) ## ----var, warning=FALSE, message=FALSE---------------------------------------------------------- var(dados$Idade) sd(dados$Idade) sqrt(var(dados$Idade)) ## ----cv, warning=FALSE, message=FALSE----------------------------------------------------------- sd(dados$Idade)/mean(dados$Idade) ## ----quantis, warning=FALSE, message=FALSE------------------------------------------------------ quantile(dados$Idade, probs = c(0.25, 0.5, 0.75)) ## ----boxplot, warning=FALSE, message=FALSE, out.width='70%', fig.align='center'----------------- boxplot(dados$Idade, ylab = "Idade", col = "gold", border = "purple") ## ----boxplot2, warning=FALSE, message=FALSE, out.width='70%', fig.align='center'---------------- boxplot(Idade ~ `Estado Civil`, data = dados, ylab = "Idade", col = "gold", border = "purple") <file_sep>--- title: "MAT02018 - Estatística Descritiva" subtitle: "Medidas de tendência central (continuação)" fontsize: 10pt author: | | <NAME> | `<EMAIL>` institute: | | \textsc{Universidade Federal do Rio Grande do Sul} | \textsc{Instituto de Matemática e Estatística} | \textsc{Departamento de Estatística} date: | | Porto Alegre, 2021 bibliography: estatistica-descritiva.bib csl: associacao-brasileira-de-normas-tecnicas-ufrgs-initials.csl link-citations: yes header-includes: - \titlegraphic{\hfill\includegraphics[height=1.5cm]{logos/Logo-40-anos-estatistica.png}} --- ```{r setup, include=FALSE, purl=FALSE} options(knitr.kable.NA = '-') library(dplyr) library(knitr) ``` # Mediana ## Mediana {.allowframebreaks} - A \structure{mediana}, geralmente representada por \structure{$md$}, é o valor de \structure{$x$}, em uma \structure{série ordenada de dados}, que divide a série em dois subgrupos de igual tamanho. - Considere que observamos as notas de cinco alunos: - André: nota 5,0; - Carla: nota 5,5; - Eliana: nota 8,5; - Júlio: nota 7,0; - Pedro: nota 8,0. \framebreak - Para obter a mediana desde conjunto de dados, primeiro ordenamos de maneira crescente as notas observadas: $$ 5,0; 5,5; \textcolor{blue}{7,0}; 8,0; 8,5 $$ - A mediana é o valor que está no centro, ou seja, \structure{$7,0$}^[A mediana é também definida por alguns autores como o __valor que ocupa a posição central__ de um __conjunto de dados ordenados__.]. - Como interpretação, temos que metade das notas da turma estão abaixo de 7, e metade estão acima de 7. ## Mediana {.allowframebreaks} - Uma característica importante da mediana é a de que ela \structure{não é afetada} pelos extremos da série. - No exemplo anterior, se observássemos a nota $3,5$ para o aluno André e $9,0$ para a aluna Eliana, a mediana continuaria sendo o valor $7,0$: $$ 3,5; 5,5; \textcolor{blue}{7,0}; 8,0; 9,0 $$ \framebreak - Para calcular a mediana, \structure{ordenamos os dados} para que se possa identificar em que posição ela se localiza. ```{r fig.align='center', echo=FALSE, out.width="70%", purl=FALSE} knitr::include_graphics(here::here('images', 'median_w5vxxo.jpg')) ``` \framebreak - Em grandes conjuntos de dados, a \structure{posição da mediana}, ou seja, a posição central na versão ordenada deste conjunto, é encontrada facilmente por intermédio do seguinte cálculo: $$ \frac{n + 1}{2}. $$ - \structure{Exemplo:} em uma amostra de 35 medidas de estatura ($n = 35$), a mediana é o o valor que encontra-se no (35+1)/2 = 18 da __série dos dados ordenados__^[Lembre: para encontrarmos a mediana de uma distribuição é necessário ordenarmos os dados do conjunto observado.]. ## Mediana - Quando o conjunto contiver um __número par__ de elementos, a __mediana é a média dos dois valores centrais__ (do cojunto ordenado). + Assim, se observamos os seguintes valores para uma certa variável: $$ 1, 3, 7, 98 $$ - A mediana está na posição 2,5^[De maneira mais formal, a mediana está entre as posições 2 e 3 da série de dados ordenados.], e portanto, a mediana é a média dos valores centrais $md = (3+7)/2 = 5$^[__Sua vez!__ Calcule a mediana de altura da sua casa.]. ## Mediana em tabelas de frequências com agrupamento simples {.allowframebreaks} - Considere mais uma vez o exemplo do __número de carburadores__ em um conjunto de 32 modelos de automóveis. ```{r, echo=FALSE, message=FALSE, warning=FALSE, purl=FALSE} mtcars_pe <- mtcars[,-3] freq_table_carb <- as.data.frame(table(mtcars_pe$carb)) freq_table_carb[,1] <- as.character(freq_table_carb[,1]) aux <- data.frame(Var1 = as.character("Total"), Freq = sum(freq_table_carb$Freq)) freq_table_carb <- rbind(freq_table_carb, aux) names(freq_table_carb) <- c("Número de carburadores $(x_i)$", "$n_i$") freq_table_carb %>% kable(align = c('l','c'), digits = c(0,0), format.args = list(decimal.mark = ",")) ``` \framebreak - Note que os valores já estão ordenados. - Como o conjunto possui \structure{32} elementos, e portanto \structure{$n$ é par}, a fórmula \structure{$(n + 1)/2 = (32 + 1)/2$} nos diz que a mediana está entre as posições \structure{$16$} e \structure{$17$}. - A mediana será a média dos valores destas duas posições. - A frequência acumulada (\structure{$n_{ac}$}) pode nos ajudar. \framebreak \footnotesize ```{r, echo=FALSE, message=FALSE, warning=FALSE, purl=FALSE} freq_table_carb$"$n_{ac}$" <- cumsum(freq_table_carb$"$n_i$") freq_table_carb$"$n_{ac}$"[length(freq_table_carb$"$n_{ac}$")] <- NA freq_table_carb %>% kable(align = c('l','c', 'c'), digits = c(0,0,0), format.args = list(decimal.mark = ",")) ``` \normalsize - Percebemos que ambas as posições assumem o valor 2, e assim, $md = (2 + 2)/2 = 2$. \framebreak - Uma forma alternativa para se obter a mediana quando os dados estão agrupados é usar a frequência acumulada relativa (\structure{$f_{ac}$}). - O valor de \structure{$x$} para o qual \structure{$f_{ac} = 0,5$} é a mediana, pois metade dos valores é igual ou menor \structure{$f_{ac}^{-1}(x)$}. \footnotesize ```{r, echo=FALSE, message=FALSE, warning=FALSE, purl=FALSE} freq_table_carb$"$f_i$" <- freq_table_carb$`$n_i$`/sum(freq_table_carb$`$n_i$`[-length(freq_table_carb$"$n_{ac}$")]) freq_table_carb$"$f_{ac}$" <- cumsum(freq_table_carb$"$f_i$") freq_table_carb$"$f_{ac}$"[length(freq_table_carb$"$n_{ac}$")] <- NA freq_table_carb %>% kable(align = c('l','c', 'c', 'c', 'c'), digits = c(0,0,0,2,2), format.args = list(decimal.mark = ",")) ``` \normalsize - Na tabela acima, `r round(freq_table_carb$"$f_{ac}$"[1]*100)`% são iguais ou menores que 1 e `r round(freq_table_carb$"$f_{ac}$"[2]*100)`% são iguais ou menores do que 2; logo, a mediana é 2. ## Mediana em tabelas de frequências com dados agrupados por intervalos {.allowframebreaks} Quando os dados estiverem organizados em intervalos de classe, os valores individuais não podem ser identificados. Nesse caso, pode-se \structure{estimar} a mediana usando a seguinte expressão: $$ md = LIR_{md} +h\left(\frac{n/2 - n_{ac}^{(ant)}}{n_{md}}\right), $$ em que - $LIR_{md}$: limite inferior real do intervalo que contém a mediana; - $h$: amplitude do intervalo; - $n$: tamanho da amostra; - $n_{ac}^{(ant)}$: frequência absoluta acumulada no intervalo anterior ao que contém a mediana; - $n_{md}$: frequência absoluta simples no intervalo que contém a mediana. \framebreak - Assim, como nos casos anteriores, o primeiro passo é encontrar a posição do valor central do conjunto de dados ordenados pela fórmula $(n + 1)/2$, e em seguida, encontrar a classe em que a mediana se encontra utilizando a frequência acumulada. - Como exemplo, utilizaremos os dados de idades de 30 crianças de uma escola. \footnotesize ```{r, echo=FALSE, message=FALSE, warning=FALSE, purl=FALSE} idade <- c("5,5 $\\vdash$ 6,5", "6,5 $\\vdash$ 7,5", "7,5 $\\vdash$ 8,5", "8,5 $\\vdash$ 9,5", "Total") f <- c(1, 20, 7, 2, 30) n <- c(1, 21, 28, 30, NA) df <- data.frame(idade, f, n) kable(x = df, col.names = c("Idade (anos)", "$n_i$", "$n_{ac}$"), align = c('l','c', 'c'), digits = c(0,0,0)) ``` \framebreak \normalsize - Neste exemplo, a mediana está entre as posições \structure{15} e \structure{16}, pois \structure{$(30 + 1)/2 = 15,5$}. - Esse valor encontra-se no intervalo \structure{$6,5 \vdash 7,5$}, porque ali estão desde o 2º até o 20º valor deste conjunto de dados (ordenados). - Então, estima-se a idade mediana como: $$ md = 6,5 + 1,0\times \left(\frac{30/2 - 1}{20}\right) = 7,2. $$ - Este resultado nos informa que metade das crianças desta escola, que coletamos informação, tem idade superior a 7,2 anos. - __Sua vez!__ Calcule a mediana do __Teste de Desempenho Escolar__ (TDE; exercício da aula passada). # Moda ## Moda {.allowframebreaks} - A \structure{moda} é o \structure{valor mais frequente} (que apresenta a maior frequência) de uma série de valores^[Note que esta medida de tendência central se aplica a dados qualitativos, pois se refere às frequências da distribuição. Já a média se aplica apenas para dados quantitativos. Pense por um minuto na média da variável _cor dos olhos_. Faz algum sentido?]. - \structure{Exemplo:} considere que em uma certa quadra da cidade observamos as cores das faixadas das casas: \footnotesize $$ \color{yellow}{amarela}, \color{orange}{laranja}, \color{orange}{laranja}, \color{yellow}{amarela}, \color{green}{verde}, \color{yellow}{amarela}, \color{orange}{laranja}, \color{green}{verde}, \color{orange}{laranja}, \color{orange}{laranja} $$ \normalsize - A cor laranja é a __moda__ nesta quadra, pois apresenta a maior frequência (5). ## Moda {.allowframebreaks} - \structure{Exemplo:} considere novamente o exemplo do número de carburadores. + Temos que 10 carros apresentam dois carburadores e 10 carros apresentam quatro carburadores. + Assim, temos \structure{duas modas}, ou dizemos que a distribuições do __número de carburadores__ é \structure{bimodal}, com uma moda em \structure{2} e outra em \structure{4}. \framebreak - Quando os dados estão apresentados em intervalos de classe, costuma-se indicar um \structure{intervalo modal}. - No exemplo de __milhas por galão__ a classe \structure{$14,3 \vdash 18,2$} é o intervalo modal, pois apresenta maior frequência (10). - __Sua vez!__ Encontre o intervalo modal do exemplo do __Teste de Desempenho Escolar__ (TDE; exercício da aula passada). # Complementa`R` ## Complementa`R` {.allowframebreaks} ```{r fig.align='right', message=FALSE, echo=FALSE, out.width="15%", purl=FALSE, warning=FALSE} knitr::include_graphics(here::here('images', 'teclado.png')) ``` ### Esta seção é complementar. São apresentadas algumas poucas funções em `R` relacionadas a discussão da aula. Para tal, vamos utilizar o exemplo original de [@bussab_estatistica_2017] sobre os dados dos empregados da seção de orçamentos da Companhia MB. A planilha eletrônica correspondente encontra-se no arquivo `companhia_mb.xlsx`. Vamos começar carregando os dados para o `R`. Existem várias formas de se carregar __arquivos de dados__ em diferentes no `R`. Como arquivo de interesse encontra-se no formato do Excel (xlsx), vamos utilizar a função `read_excel` do pacote `readxl`^[Caso você não tenha o pacote, instale-o:`install.packages("readxl")`.]. ## Complementa`R` {.allowframebreaks} \footnotesize ```{r carrega-dados0, echo=TRUE, eval=FALSE, warning=FALSE, message=FALSE} # install.packages("readxl") library(readxl) dados <- read_excel(path = "companhia_mb.xlsx") ``` ```{r carrega-dados1, echo=FALSE, warning=FALSE, message=FALSE, purl=FALSE} # install.packages("readxl") library(readxl) dados <- read_excel(path = here::here("data", "companhia_mb.xlsx")) ``` ```{r carrega-dados2, warning=FALSE, message=FALSE} class(dados) # classe do objeto dados dim(dados) # dimensão do objeto dados ``` \normalsize - Note que o objeto `dados` é uma tabela de dados bruto. \footnotesize ```{r carrega-dados3, warning=FALSE, message=FALSE} head(dados) # apresenta as primeiras linhas do objeto dados ``` \normalsize - A função `mean` calcula a média aritmética de um conjunto de dados. \footnotesize ```{r medias, warning=FALSE, message=FALSE} mean(dados$Idade) mean(dados$`Salario (x Sal Min)`) ``` \normalsize - No caso em que a variável possui __dados ausentes__, como é o caso da variável _número de filhos_, precisamos utilizar o argumento `na.rm = TRUE` para remover os dados ausentes do conjunto antes de calcular a média. \footnotesize ```{r medias2, warning=FALSE, message=FALSE} mean(dados$`N de Filhos`, na.rm = TRUE) ``` \normalsize - A mediana de um conjunto de dados pode ser obtida utilizando a função `median`. \footnotesize ```{r medianas, warning=FALSE, message=FALSE} median(dados$Idade) median(dados$`Salario (x Sal Min)`) median(dados$`N de Filhos`, na.rm = TRUE) ``` \normalsize - A moda pode ser obtida observando-se a maior frequência em uma tabela de frequências. \footnotesize ```{r freqs, warning=FALSE, message=FALSE} table(dados$`Estado Civil`) ``` \normalsize - Casado é a moda na seção de orçamentos da Companhia MB. Outra possibilidade é recuperar a maior frequência do vetor de frequências utilizando a função `which.max`. \footnotesize ```{r modas, warning=FALSE, message=FALSE} which.max(table(dados$`Região de Procedência`)) which.max(table(dados$`N de Filhos`)) ``` \normalsize ## Para casa 1. Resolver os exercícios 1 a 3 do Capítulo 8.5 do livro __Fundamentos de Estatística__\footnote{Vieira, S. {\bf Fundamentos de Estatística}, Atlas, 2019, p. 135-136.} (disponível no Sabi+). 2. Para o seu levantamento estatístico, calcule médias, modas e medianas, de acordo com a classificação das variáveis. Compartilhe no Fórum Geral do Moodle. ## Próxima aula - Médias ponderada, geométrica e harmônica. ## Por hoje é só! \begin{center} {\bf Bons estudos!} \end{center} ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='50%', out.height='50%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'Statistically-Insignificant-barras04.jpg')) ``` <file_sep>library(ggplot2) library(UsingR) # Diamonds data("diamonds") writexl::write_xlsx(x = diamonds, path = here::here("data", "diamonds.xlsx")) # mpg data("mpg") writexl::write_xlsx(x = mpg, path = here::here("data", "mpg.xlsx")) # msleep data("msleep") writexl::write_xlsx(x = msleep, path = here::here("data", "msleep.xlsx")) # babies data("babies") writexl::write_xlsx(x = babies, path = here::here("data", "babies.xlsx")) # House Sales in Tyne and Wear housing <- readxl::read_excel(path = here::here("data", "Rogerson Chapter 2 Key.xlsx"), sheet = "Housing Data") writexl::write_xlsx(x = housing, path = here::here("data", "housing.xlsx")) <file_sep>--- title: "MAT02018 - Estatística Descritiva" subtitle: "Distribuições bidimensionais" fontsize: 10pt author: | | <NAME> | `<EMAIL>` institute: | | \textsc{Universidade Federal do Rio Grande do Sul} | \textsc{Instituto de Matemática e Estatística} | \textsc{Departamento de Estatística} date: | | Porto Alegre, 2021 bibliography: estatistica-descritiva.bib csl: associacao-brasileira-de-normas-tecnicas-ufrgs-initials.csl link-citations: yes header-includes: - \titlegraphic{\hfill\includegraphics[height=1.5cm]{logos/Logo-40-anos-estatistica.png}} --- ```{r setup, include=FALSE, purl=FALSE} options(knitr.kable.NA = '-') library(dplyr) library(knitr) ``` # Uma variável qualitativa e uma variável quantitativa {.allowframebreaks} - Como mencionado anteriormente, é comum nessas situações analisar o que acontece com a variável quantitativa dentro de cada categoria da variável qualitativa. - Essa análise pode ser conduzida por meio de medidas-resumo, histogramas ou _boxplots_. - Consideremos novamente o exemplo dos empregados da seção de orçamentos da Companhia MB, mas agora com o interesse de avaliar a associação entre a variável _salário_ e _grau de instrução_. \framebreak \scriptsize ```{r mb, echo=FALSE, warning=FALSE, message=FALSE} library(dplyr) library(readxl) library(knitr) library(kableExtra) library(ggplot2) mb_df <- read_excel(path = here::here("data", "companhia_mb.xlsx")) ``` ```{r sal_grupo, echo=FALSE, warning=FALSE, message=FALSE} mb_df_arrange <- mb_df %>% dplyr::select("N" ,`Salario (x Sal Min)`, `Grau de Instrução`) %>% rename("ID" = "N") %>% arrange(`Grau de Instrução`) mb_df_arrange[1:18,] %>% kable(#caption = "Tabela de dados brutos.", align = 'c', format.args = list(decimal.mark = ","), format = "latex") %>% kable_styling() %>% row_spec(which(mb_df_arrange[1:18,]$`Grau de Instrução` == "ensino fundamental"), background = "lightsalmon") %>% row_spec(which(mb_df_arrange[1:18,]$`Grau de Instrução` == "ensino médio"), background = "lightblue") %>% row_spec(which(mb_df_arrange[1:18,]$`Grau de Instrução` == "superior"), background = "lightyellow") ``` \framebreak ```{r sal_grupo2, echo=FALSE, warning=FALSE, message=FALSE} mb_df_arrange[19:36,] %>% kable(#caption = "Tabela de dados brutos.", align = 'c', format.args = list(decimal.mark = ","), format = "latex") %>% kable_styling() %>% row_spec(which(mb_df_arrange[19:36,]$`Grau de Instrução` == "ensino fundamental"), background = "lightsalmon") %>% row_spec(which(mb_df_arrange[19:36,]$`Grau de Instrução` == "ensino médio"), background = "lightblue") %>% row_spec(which(mb_df_arrange[19:36,]$`Grau de Instrução` == "superior"), background = "lightyellow") ``` \framebreak \normalsize - Vamos começar organizando em uma tabela as principais medidas resumo da variável salário para cada um dos grupos de escolaridade. - Ou seja, vamos calcular a média, o desvio padrão e demais medidas resumo considerando apenas os indivíduos com ensino superior. - Logo em seguida, calcularemos as mesmas medidas considerando apenas os indivíduos com ensino médio. - E por fim, calcularemos as mesmas medidas considerando apenas os indivíduos com ensino fundamental. \framebreak - Assim, a variável grau de instrução define grupos de indivíduos, e descreveremos a distribuição da variável salário para cada um dos grupos. \tiny ```{r sal_grupo_res, echo=FALSE, warning=FALSE, message=FALSE} tab <- mb_df_arrange %>% group_by(`Grau de Instrução`) %>% summarize(n = n(), `Média` = mean(`Salario (x Sal Min)`), `D. Padrão` = sd(`Salario (x Sal Min)`), `Variância` = var(`Salario (x Sal Min)`), `Min` = min(`Salario (x Sal Min)`), `Q1` = quantile(`Salario (x Sal Min)`, 0.25), `Q2` = quantile(`Salario (x Sal Min)`, 0.5), `Q3` = quantile(`Salario (x Sal Min)`, 0.75), `Max` = max(`Salario (x Sal Min)`) ) tab2 <- mb_df_arrange %>% summarize(n = n(), `Média` = mean(`Salario (x Sal Min)`), `D. Padrão` = sd(`Salario (x Sal Min)`), `Variância` = var(`Salario (x Sal Min)`), `Min` = min(`Salario (x Sal Min)`), `Q1` = quantile(`Salario (x Sal Min)`, 0.25), `Q2` = quantile(`Salario (x Sal Min)`, 0.5), `Q3` = quantile(`Salario (x Sal Min)`, 0.75), `Max` = max(`Salario (x Sal Min)`) ) tab2$`Grau de Instrução` <- "Global" tab2 <- tab2[c(names(tab2)[10],names(tab2)[-10])] tab <- rbind(tab, tab2) kable(tab, caption = "Medidas-resumo para a variável salário, segundo o grau de instrução, na Companhia MB.", align = 'c', digits = c(0,0,rep(2,8)), format.args = list(decimal.mark = ","), format = "latex") %>% kable_styling() %>% row_spec(1, background = "lightsalmon") %>% row_spec(2, background = "lightblue") %>% row_spec(3, background = "lightyellow") ``` \framebreak \normalsize - Uma outra forma de apresentarmos a distribuição de salário por grupo de instrução é através do gráfico de _boxplot_. - Novamente devemos construir cada uma das caixas considerando os dados dos indivíduos de cada um dos grupos. \framebreak ```{r sal_bp, echo=FALSE, warning=FALSE, message=FALSE, fig.align='center', out.width="100%"} mb_df_arrange$cor <- NULL mb_df_arrange$cor <- ifelse(mb_df_arrange$`Grau de Instrução` == "ensino fundamental", "lightsalmon", ifelse(mb_df_arrange$`Grau de Instrução` == "ensino médio", "lightblue", "lightyellow")) bp <- ggplot(data = mb_df_arrange, mapping = aes(x = `Grau de Instrução`, y = `Salario (x Sal Min)`)) + geom_boxplot(fill = c("lightsalmon", "lightblue", "lightyellow")) + theme_bw() bp ``` \framebreak - Estes resultados sugerem uma __dependência__ dos salários em relação ao grau de instrução: o salário aumenta conforme aumenta o nível de escolaridade do indivíduo. - O salário médio de um funcionário é 11,12 (salários mínimos), já para um funcionário com curso superior o salário médio passa a ser 16,48, enquanto funcionários com o ensino fundamental completo recebem, em média, 7,84. \framebreak - Como nos casos anteriores, é conveniente poder contar com uma medida que quantifique o __grau de dependência__ entre as variáveis. - Tal medida pode ser construída a partir das variâncias de grupo e a variância global. - Sem usar a informação da variável categorizada^[Em nosso exemplo, a variável grau de instrução.], a variância calculada para a variável quantitativa^[Em nosso exemplo, a variável salário.] para todos os dados mede a dispersão dos dados globalmente. - __Se a variância dentro de cada categoria for pequena e menor do que a global__, significa que a variável qualitativa __melhora a capacidade de previsão__^[Ao saber o grau de instrução conseguimos falar de maneira mais "precisa" sobre o salário dos empregados da Companhia MB?] da quantitativa __e portanto existe uma relação entre as duas variáveis__. ## Uma variável qualitativa e uma variável quantitativa {.allowframebreaks} - Observe que, para as variáveis salário (denotaremos por $Y$) e grau de instrução, as variâncias de $Y$ dentro das três categorias são menores do que a global^[Lembrando: para o grupo ensino fundamental, $s^2_Y = 8,74$; para o grupo ensino médio, $s^2_Y = 13,80$; para o grupo ensino superior, $s^2_Y = 20,27$; e por fim, para todo o grupo de empregados, $s^2_Y = 21,04$.]. - Necessita-se, então, de uma medida resumo da variância entre as categorias da variável qualitativa. - Vamos usar a __média das variâncias__ ponderada pelo número de observações em cada categoria, ou seja, $$ \bar{s^2}_Y = \frac{\sum_{j=1}^k{s^2_j(Y)n_j}}{\sum_{j=1}^k{n_j}}, $$ em que $k$ é o número de categorias ($k = 3$ em nosso exemplo) e $s^2_j(Y)$ denota a variância de $Y$ dentro da categoria $j$, $j = 1, 2, \ldots, k$. ## Uma variável qualitativa e uma variável quantitativa {.allowframebreaks} - Pode-se mostrar que a média das variâncias é menor ou igual a variância global^[$\bar{s^2}_Y \leq s^2_Y$.], de modo que podemos definir o __grau de associação__ entre as duas variáveis __como o ganho relativo na variância__, obtido pela introdução da variável qualitativa. Explicitamente, $$ R^2 = \frac{s^2_Y - \bar{s^2}_Y}{s^2_Y} = 1 - \frac{\bar{s^2}_Y}{s^2_Y}. $$ \framebreak - Note que $0 \leq R^2 \leq 1$. - Quanto maior a capacidade preditiva da variável de grupo, menor será a média das variâncias ($\bar{s^2}_Y$) em relação a variância global, e portanto a razão $\frac{\bar{s^2}_Y}{s^2_Y}$ será próxima de zero, enquanto que $R^2$ tenderá a 1. - Já se a média das variâncias é próxima da variância global, então a razão $\frac{\bar{s^2}_Y}{s^2_Y}$ será próxima de um, enquanto que $R^2$ tenderá a 0. Concluímos então, que: - $R^2$ alto (valores próximos de 1) indicam forte dependência (associação) entre a variável qualitativa e a variável quantitativa. - $R^2$ baixo (valores próximos de 0) indicam fraca dependência (associação), ou ausência de associação, entre a variável qualitativa e a variável quantitativa. \framebreak - Retomando o exemplo da Companhia MB, temos que $$ \bar{s^2}_Y = \frac{\sum_{j=1}^3{s^2_j(Y)n_j}}{\sum_{j=1}^3{n_j}} = \frac{12\times 8,74 + 18\times 13,8, + 6 \times 20,27}{12 + 18 + 6} = 13,19, $$ de modo que $$ R^2 = 1 - \frac{\bar{s^2}_Y}{s^2_Y} = 1 - \frac{13,19}{21,04} = 0,3731. $$ e dizemos que 37,31% da variância global do salário é explicada pela variável grau de instrução^[Uma dependência relativamente forte, levando em consideração que dificilmente um $R^2$ próximo de 1 é observado.]. # Exercício {.allowframebreaks} A tabela a seguir apresenta os dados referentes a uma amostra de 30 flores. \scriptsize ```{r iris, echo=FALSE, message=FALSE, warning=FALSE} set.seed(1000) iris_ex_1 <- iris %>% filter(Species == "setosa") %>% slice_head(n = 10) iris_ex_2 <- iris %>% filter(Species == "versicolor") %>% slice_head(n = 10) iris_ex_3 <- iris %>% filter(Species == "virginica") %>% slice_head(n = 10) iris_ex <- rbind(iris_ex_1, iris_ex_2) iris_ex <- rbind(iris_ex, iris_ex_3) iris_ex %>% kable(caption = "Tabela de dados brutos.", align = 'c', col.names = c("comprimento da sépala", "largura da sépala", "comprimento da pétala", "largura da pétala", "espécie"), format.args = list(decimal.mark = ","), format = "pandoc") ``` \normalsize ## Exercício {.allowframebreaks} - Crie uma nova variável a partir da variável comprimento da pétala, atribuindo valores: __pequeno__ se o comprimento da pétala é menor ou igual que 4,5 e __normal__ se o comprimento da pétala é superior a 4,5. Chame esta variável de _comprimento da pétala categorizado_. - Construa a tabela de dupla entrada da distribuição conjunta de frequências das variáveis _espécie_ e _comprimento da pétala categorizado_. Você diria que estas variáveis são associadas? - Construa o gráfico de dispersão das variáveis _comprimento da sépala_ e _largura da sépala_. Calcule o coeficiente de regressão. O que você diria sobre a associação entre estas variáveis? - Construa o gráfico de dispersão das variáveis _comprimento da sépala_ e _comprimento da pétala_. Calcule o coeficiente de regressão. O que você diria sobre a associação entre estas variáveis? \framebreak A partir dos seguintes exercícios, conclua a respeito da associação entre as variáveis _largura da pétala_ e _espécie_. + Organize uma tabela com o cálculo de diferentes medidas resumo para descrever a distribuição da variável _largura da pétala_ entre as diferentes _espécies_. + Construa um gráfico para apresentar a distribuição a distribuição da variável _largura da pétala_ entre as diferentes _espécies_. + Calcule o $R^2$ para avaliar a associação entre as variáveis _largura da pétala_ e _espécie_. ## Próxima aula - Números índices. ## Por hoje é só! \begin{center} {\bf Bons estudos!} \end{center} ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='50%', out.height='50%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'Statistically-Insignificant-final04.jpg')) ``` <file_sep>## ----carrega-dados0, echo=TRUE, eval=FALSE, warning=FALSE, message=FALSE---------------------------------------- ## # install.packages("readxl") library(readxl) dados <- read_excel(path = "companhia_mb.xlsx") ## ----carrega-dados2, warning=FALSE, message=FALSE--------------------------------------------------------------- class(dados) # classe do objeto dados dim(dados) # dimensão do objeto dados ## ----carrega-dados3, warning=FALSE, message=FALSE--------------------------------------------------------------- head(dados) # apresenta as primeiras linhas do objeto dados ## ----apuracao, warning=FALSE, message=FALSE--------------------------------------------------------------------- table(dados$`Estado Civil`) # apura dados nominais table(dados$`Grau de Instrução`) # apura dados ordinais table(dados$`N de Filhos`) # apura dados discretos dados$Idade # apura dados contínuos <file_sep>--- title: "MAT02018 - Estatística Descritiva" subtitle: "Construção de gráficos" fontsize: 10pt author: | | <NAME> | `<EMAIL>` institute: | | \textsc{Universidade Federal do Rio Grande do Sul} | \textsc{Instituto de Matemática e Estatística} | \textsc{Departamento de Estatística} date: | | Porto Alegre, 2021 bibliography: estatistica-descritiva.bib csl: associacao-brasileira-de-normas-tecnicas-ufrgs-initials.csl link-citations: yes header-includes: - \titlegraphic{\hfill\includegraphics[height=1.5cm]{logos/Logo-40-anos-estatistica.png}} --- # Introdução ## Introdução Nestas notas são apresentados, por meio de exemplos, os conceitos e métodos que devem ser utilizados na construção de gráficos. Serão apresentados: - os aspectos básicos na construção de gráficos; - os gráficos mais utilizados para apresentar \structure{distribuições univariadas}; - e uma discussão do apropriado uso de tais gráficos na descrição de dados qualitativos e quantitativos. # Gráficos ## Gráficos {.allowframebreaks} - Os dados apresentados em tabelas trazem informações sobre o assunto em estudo. - No entanto, figuras sempre \structure{causam maior impacto}. - Para chamar a atenção do leitor, os estatísticos expõem dados em gráficos bem editados e, em geral, \textcolor{red}{co}\textcolor{blue}{lo}\textcolor{green}{ri}\textcolor{orange}{dos}. - Além disso, os gráficos possuem uma __capacidade de síntese__ que nem sempre uma tabela pode alcançar. \framebreak Os gráficos estatísticos devem ter: - \structure{título}, escrito logo acima do gráfico; - \structure{fonte} e \structure{notas}, se houver, escritas abaixo do gráfico. # Apresentação gráfica de dados qualitativos ## Gráfico de barras {.allowframebreaks} - Podemos construir um \structure{gráficos de barras}\footnote{Algumas referências fazem a distinção entre {\bf gráfico de barra} e {\bf gráfico de colunas}, em que o gráfico de barras refere-se a posição horizontal das barras e gráfico de colunas refere-se ao gráfico com barras verticais. Aqui trataremos os ``dois'' gráficos como {\bf gráfico de barras}.} para apresentar \structure{dados qualitativos} que estão em uma \structure{tabela de distribuição de frequências}. - Cada categoria da variável é representada na forma de uma \structure{barra} __(um retângulo)__. ## Gráfico de barras {.allowframebreaks} - Para exemplificarmos o uso do gráfico de barras, vamos utilizar o exemplo adaptado de [@bussab_estatistica_2017] sobre os dados dos empregados da seção de orçamentos da Companhia MB\footnote{Neste caso estamos considerando os 36 empregados, porém alterando as observações de algumas variáveis apenas para fins didáticos.}. - Considere a variável \structure{``Grau de Instrução''}. ```{r carrega-dados1, echo=FALSE, warning=FALSE, message=FALSE} # install.packages("readxl") library(readxl) library(stringr) dados <- read_excel(path = here::here("data", "companhia_mb.xlsx")) set.seed(123) dados$`Grau de Instrução`[dados$`Grau de Instrução` == "ensino fundamental"] <- sample(x = c("fundamental incompleto", "fundamental completo"), size = length(dados$`Grau de Instrução`[dados$`Grau de Instrução` == "ensino fundamental"]), replace = T) dados$`Grau de Instrução`[dados$`Grau de Instrução` == "ensino médio"] <- sample(x = c("médio incompleto", "médio completo"), size = length(dados$`Grau de Instrução`[dados$`Grau de Instrução` == "ensino médio"]), replace = T) dados$`Grau de Instrução`[dados$`Grau de Instrução` == "superior"] <- sample(x = c("superior incompleto", "superior completo"), size = length(dados$`Grau de Instrução`[dados$`Grau de Instrução` == "superior"]), replace = T) dados$`Estado Civil` <- str_to_title(dados$`Estado Civil`) dados$`Grau de Instrução` <- str_to_title(dados$`Grau de Instrução`) dados$`Região de Procedência` <- str_to_title(dados$`Região de Procedência`) dados$`Grau de Instrução` <- factor(dados$`Grau de Instrução`, levels = c("Fundamental Incompleto", "Fundamental Completo", "Médio Incompleto", "Médio Completo", "Superior Incompleto", "Superior Completo")) ``` ```{r fig-barras1, echo=FALSE, warning=FALSE, message=FALSE, fig.align='center', out.width='75%'} library(ggplot2) p.barras <- ggplot(data = dados, mapping = aes(x = `Grau de Instrução`)) + geom_bar(stat = "count", width = 0.5, aes(fill = I("steelblue"))) + labs(x = "Grau de Instrução", y = "Frequência", title = "Escolaridade dos empregados da seção de orçamentos.", caption = "Fonte: Companhia MB.") + theme_bw() + theme(axis.text.x = element_text(angle = 45, hjust = 1)) p.barras ``` ## Gráfico de barras {.allowframebreaks} Passos para construir o gráfico de barras da distribuição da variável __Grau de Instrução__: 1. Trace o sistema de eixos cartesianos. ```{r fig-plano-cart, message=FALSE, echo=FALSE, out.width="80%", out.height='80%', purl=FALSE, fig.align='center'} knitr::include_graphics(here::here('images', 'plano-cartesiano.jpg')) ``` \framebreak 2. No eixo das abscissas (eixo horizontal), apresente os níveis da variável Grau de Instrução. 3. No eixo das ordenadas (eixo vertical), apresente as frequências dos níveis de Grau de Instrução\footnote{Observe que aqui é necessário ter sido realizada a apuração dos dados, e se possível a tabela de frequências. Os \emph{softwares} estatísticos acabam realizando estas tarefas conjuntamente, mas aqui estamos apresentando os passos para a construção sem que seja necessário o conhecimento de recursos computacionais.}. 4. Faça marcas no eixo das abscissas, de mesma largura e igualmente espaçadas, que serão as bases das barras (retângulos) que irão representar o número de empregados de cada nível da variável Grau de Instrução. 5. Desenhe as barras (retângulos) com bases nas abscissas e alturas dadas pelas frequências de cada categoria da variável Grau de Instrução. 6. Coloque legendas nos eixos, título no gráfico e fonte, quando houver. - É possível desenhar linhas auxiliares (grades) no interior do gráfico para facilitar a leitura das alturas das barras. ## Gráfico de barras {.allowframebreaks} - __Exercício:__ construa o gráfico de barras da variável __Grau de Instrução__ do exemplo __adaptado__ de [@bussab_estatistica_2017] (15 empregados da seção de orçamentos) que encontra-se na planilha física das __notas de aula "Organização dos dados"__. ```{r, message=FALSE, echo=FALSE, out.width="100%", purl=FALSE, fig.align='center'} knitr::include_graphics(here::here('images', 'quadro_preto.jpg')) ``` \framebreak - O gráfico de barras também pode ser utilizado para apresentar as frequências relativas (ou porcentagens) de um conjunto de dados referentes a uma variável. ```{r fig-barras2, echo=FALSE, warning=FALSE, message=FALSE, out.width="80%", fig.align='center'} p.barras <- ggplot(data = dados, mapping = aes(x = `Grau de Instrução`)) + geom_bar(stat = "count", width = 0.5, aes(y = (..count..)/sum(..count..), fill = I("lightsalmon"))) + labs(x = "Grau de Instrução", y = "Frequência relativa", title = "Escolaridade dos empregados da seção de orçamentos.", caption = "Fonte: Companhia MB.") + theme_bw() + theme(axis.text.x = element_text(angle = 45, hjust = 1)) p.barras ``` \framebreak - Uma forma de auxiliar o leitor na identificação das frequências é apresentar os valores destas no topo das barras\footnote{Em alguns casos, os valores das frequências são apresentados dentro das barras.}. ```{r fig-barras3, echo=FALSE, warning=FALSE, message=FALSE, out.width="80%", fig.align='center'} p.barras <- ggplot(data = dados, mapping = aes(x = `Grau de Instrução`)) + geom_bar(stat = "count", width = 0.5, aes(y = (..count..)/sum(..count..), fill = I("#77DD77"))) + geom_text(aes(label = scales::percent( (..count..)/sum(..count..)), y = (..count..)/sum(..count..) ), stat = "count", vjust = -.5) + scale_y_continuous(limits = c(0, 0.35), labels = scales::percent) + labs(x = "Grau de Instrução", y = "Porcentagem", title = "Escolaridade dos empregados da seção de orçamentos.", caption = "Fonte: Companhia MB.") + theme_bw() + theme(axis.text.x = element_text(angle = 45, hjust = 1)) p.barras ``` ## Gráfico de barras {.allowframebreaks} - Quando as categorias da variável tiverem nomes extensos, ou a variável apresentar muitas categorias, é conveniente apresentar o gráfico de barras na posição horizontal. ```{r fig-barras4, echo=FALSE, warning=FALSE, message=FALSE, out.width="65%", out.height='65%', fig.align='center'} p.barras <- ggplot(data = dados, mapping = aes(x = `Grau de Instrução`)) + geom_bar(stat = "count", width = 0.5, aes(y = (..count..)/sum(..count..), fill = I("#DA70D6"))) + geom_text(aes(label = scales::percent( (..count..)/sum(..count..)), y = (..count..)/sum(..count..) ), stat = "count", hjust = -.5) + scale_y_continuous(limits = c(0, 0.35), labels = scales::percent) + labs(x = "Grau de Instrução", y = "Porcentagem", title = "Escolaridade dos empregados da seção de orçamentos.", caption = "Fonte: Companhia MB.") + coord_flip() + theme_bw() p.barras ``` \framebreak Os passos para a construção do gráfico de barras na posição horizontal são semelhantes aos da construção do gráfico de barras na vertical: 1. Trace o sistema de eixos cartesianos. 2. Represente as categorias da variável em estudo na ordenada (eixo vertical). 3. Represente as frequências (absolutas, relativas ou porcentagens) da variável em estudo no eixo das abscissas (eixo horizontal). 4. Construa as barras: as bases ficam no eixo das ordenadas e os comprimentos devem ser iguais às frequências das categorias que elas representam. 5. Escreva legendas, título e a fonte, se houver. - Outra possibilidade é representar as frequências por bastões (segmentos de reta), ou ainda por outras formas. Uma forma bastante utilizada é conhecida com \structure{gráfico pirulito}. \framebreak ```{r fig-barras5, echo=FALSE, warning=FALSE, message=FALSE, out.width="100%", fig.align='center'} library(dplyr) df_barras <- dados %>% group_by(`Grau de Instrução`) %>% summarise(n = n()) %>% mutate(freq = 100 * (n / sum(n))) p.barras <- ggplot(data = df_barras, mapping = aes(y = `Grau de Instrução`, x = freq, label = paste0(round(freq, 0), "%"))) + geom_segment(aes(x = 0, y = `Grau de Instrução`, xend = freq, yend = `Grau de Instrução`), color = "grey50") + geom_point(size = 7, color = "#FF5349") + geom_text(color = "white", size = 2) + labs(y = "Grau de Instrução", x = "Porcentagem", title = "Escolaridade dos empregados da seção de orçamentos.", caption = "Fonte: Companhia MB.") + theme_bw() p.barras ``` \framebreak ### Observações - O gráfico de barras é indicado para representar as frequências de variáveis qualitativas nominais, ordinais e variáveis quantitativas discretas. - O gráfico de barras também pode ser utilizado para representar médias de grupos. No entanto, esta representação fará mais sentido após a discussão sobre medidas resumo (de tendência central e dispersão) e distribuições bivariadas. ## Gráfico de setores {.allowframebreaks} - O \structure{gráfico de setores}\footnote{Este gráfico é popularmente conhecido como {\bf gráfico de pizza}, pois lembra a forma de uma pizza redonda cortada em fatias.} é usado para apresentar frequências ou frequências relativas de categorias que constituem partes de um todo (a soma das frequências relativas deve ser obrigatoriamente 100%). - Como exemplo, considere mais uma vez os dados dos 36 empregados da seção de orçamento da Companhia MB. Veja a seguir a tabela de frequências da variável \structure{``Região de Procedência''}. ```{r, echo=FALSE, message=FALSE, warning=FALSE} library(janitor) df_regiao <- dados %>% group_by(`Região de Procedência`) %>% summarise(n = n()) %>% mutate(freq = round(100 * (n / sum(n)), 0)) %>% adorn_totals("row") knitr::kable(df_regiao, col.names = c("Região de Procedência", "Frequência ($n_i$)", "Porcentagem"), align = c('l', 'c', 'c'), digits = c(0,0,1)) ``` ## Gráfico de setores {.allowframebreaks} - O gráfico de setores correspondente aos dados da tabela é apresentado a seguir. ```{r fig-setores, echo=FALSE, warning=FALSE, message=FALSE, purl=FALSE, out.width="80%", fig.align='center'} # # p.setores <- ggplot(data = df_regiao, aes(x = "", y = freq, fill = `Região de Procedência`)) + # geom_bar(stat = "identity", width = 1) + # coord_polar("y", start = 0) + # theme_void() # remove background, grid, numeric labels p.setores <- ggplot(df_regiao[1:3, ], aes("", freq, fill = `Região de Procedência`)) + geom_bar(width = 1, size = 1, color = "white", stat = "identity") + coord_polar("y") + geom_text(aes(label = paste0(round(freq), "%")), position = position_stack(vjust = 0.5)) + labs(x = NULL, y = NULL, fill = NULL, title = "Região de Procedência") + guides(fill = guide_legend(reverse = TRUE)) + scale_fill_manual(values = c("#ffd700", "#254290", "#bcbcbc")) + labs(caption = "Fonte: Companhia MB.") + theme_classic() + theme(axis.line = element_blank(), axis.text = element_blank(), axis.ticks = element_blank(), plot.title = element_text(hjust = 0.5, color = "#666666")) p.setores ``` \framebreak Para a construção do gráfico de setores devemos seguir os seguintes passos: 1. Trace uma circunferência\footnote{Lembrando: uma circunferência possui 360º.}. 2. A área do círculo representará o total, ou seja, 100%. 3. Use a \structure{``regra de três''}: se 100% correspondem a 360º, 31% de empregados com origem na \structure{Capital} correspondem a um setor cujo ângulo central $g$ é dado por: \begin{eqnarray*} && 100\% \longrightarrow 360^{\text{o}}\\ && 31\% \longrightarrow g\\ &&\Rightarrow g = \frac{31 \times 360}{100} = 111,6^{\text{o}} \end{eqnarray*} ## Gráfico de setores {.allowframebreaks} 4. Proceda da mesma forma para calcular os outros ângulos. + Para \structure{Interior}: \begin{eqnarray*} && 100\% \longrightarrow 360^{\text{o}}\\ && 33\% \longrightarrow g\\ &&\Rightarrow g = \frac{33 \times 360}{100} = 118,8^{\text{o}} \end{eqnarray*} + Para \structure{Outra} região: \begin{eqnarray*} && 100\% \longrightarrow 360^{\text{o}}\\ && 36\% \longrightarrow g\\ &&\Rightarrow g = \frac{36 \times 360}{100} = 129,6^{\text{o}} \end{eqnarray*} \framebreak 5. Marque os valores dos ângulos calculados na circunferência e trace os raios, separando os setores. Um \structure{transferidor} pode auxiliar bastante neste processo. ```{r fig-transferidor, echo=FALSE, out.width="85%", purl=FALSE, fig.align='center'} knitr::include_graphics(here::here('images', 'transferidor.png')) ``` \framebreak 6. Para facilitar a distinção dos setores, use padrões de preenchimento ou cores diferentes. 7. Coloque legenda e título na figura. \framebreak ### Observações - O gráfico de setores é adequado para representar frequências de variáveis qualitativas nominais. Quando o número de categorias for muito grande é recomendado o uso de um gráfico de barras no lugar de gráfico de setores, pois a visualização das frequências fica prejudicada. ```{r fig-pizza-ruim, message=FALSE, echo=FALSE, out.width="60%", purl=FALSE, fig.align='center'} knitr::include_graphics(here::here('images', 'pizza-ruim.png')) ``` ## Gráfico de setores {.allowframebreaks} ### Observações - Assim como o gráfico de barras, o gráfico de setores apresenta variações na forma (veja a seguir). No entanto, todas estas versões apresentam a mesma informação. ## Gráfico de setores {.allowframebreaks} ```{r fig-variacoes-setores, echo=FALSE, warning=FALSE, message=FALSE, out.width="90%", fig.align='center'} # # p.setores <- ggplot(data = df_regiao, aes(x = "", y = freq, fill = `Região de Procedência`)) + # geom_bar(stat = "identity", width = 1) + # coord_polar("y", start = 0) + # theme_void() # remove background, grid, numeric labels p1 <- ggplot(df_regiao[1:3, ], aes(x = 2, freq, fill = `Região de Procedência`)) + geom_bar(width = 1, size = 1, color = "white", stat = "identity") + coord_polar("y") + geom_text(aes(label = paste0(round(freq), "%")), position = position_stack(vjust = 0.5)) + labs(x = NULL, y = NULL, fill = NULL, title = "Região de Procedência") + guides(fill = guide_legend(reverse = TRUE)) + scale_fill_manual(values = c("#ffd700", "#254290", "#bcbcbc")) + theme_classic() + theme(axis.line = element_blank(), axis.text = element_blank(), axis.ticks = element_blank(), plot.title = element_text(hjust = 0.5, color = "#666666")) + xlim(0.5, 2.5) p2 <- ggplot(dados, aes(y = "", fill = factor(`Região de Procedência`))) + geom_bar(width = 1, size = 0.1, color = "white", position = "fill") + scale_fill_manual(values = c("#ffd700", "#254290", "#bcbcbc")) + # geom_text(data = NULL, aes(label = paste(df_regiao$freq[1:3], "%"), # x = df_regiao$freq[1:3]), hjust = -.5) + scale_x_continuous(labels = scales::percent) + labs(fill = "Procedência", x = "") + theme_classic() + theme(legend.position = 'bottom', legend.text = element_text(size = 8), axis.title.y = element_blank(), axis.ticks.y = element_blank(), axis.line.y = element_blank(), axis.text.y = element_blank()) library(waffle) library(hrbrthemes) p3 <- ggplot(data = df_regiao[1:3,], aes(fill = `Região de Procedência`, values = n)) + geom_waffle(n_rows = 10, size = 0.33, colour = "white", flip = TRUE) + scale_fill_manual( name = "Região de Procedência", values = c("#ffd700", "#254290", "#bcbcbc"), labels = c("Capital", "Interior", "Outra") ) + coord_equal() + # theme_ipsum_rc(grid = "") + theme_enhance_waffle() library(cowplot) grid1 <- plot_grid(p1, p2, labels = c('A', 'B'), label_size = 10) plot_grid(grid1, p3, labels = c('', 'C'), label_size = 10, ncol = 1) ``` ## Para casa 1. Resolver os exercícios 1 e 2 do Capítulo 5.4 do livro __Fundamentos de Estatística__\footnote{Vieira, S. {\bf Fundamentos de Estatística}, Atlas, 2019, p. 75.} (disponível no Sabi+). 2. Para o seu levantamento estatístico, construa gráficos para os dados qualitativos. Compartilhe no Fórum Geral do Moodle. ## Próxima aula - Construção de gráficos para dados quantitativos. ## Por hoje é só! \begin{center} {\bf Bons estudos!} \end{center} ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='50%', out.height='50%', paged.print=FALSE} knitr::include_graphics(here::here('images', 'Statistically-Insignificant-capediem.jpg')) ``` <file_sep>## ----fig-stripchart, echo=FALSE, warning=FALSE, message=FALSE, fig.align='center', out.width='90%'------------------------ p <- ggplot(dados, aes(x = `N de Filhos`)) + geom_dotplot(fill = "steelblue") + labs(x = "Número de filhos", caption = "Fonte: Companhia MB.") + theme_classic() + theme(axis.title.y = element_blank(), axis.ticks.y = element_blank(), axis.line.y = element_blank(), axis.text.y = element_blank()) p ## ----fig-hist, echo=FALSE, warning=FALSE, message=FALSE, fig.align='center', out.width='90%'------------------------------ p <- ggplot(data = dados) + geom_histogram(mapping = aes(x = `Salario (x Sal Min)`, y = ..density..), breaks = seq(4, 24, by = 4), fill = "steelblue", color = "white") + labs(x = "Salário (x. sal. mínimo)", y = "Densidade de frequência", title = "Distribuição salarial da seção de orçamentos", caption = "Fonte: Companhia MB.") + theme_bw() p ## ----fig-hist2, echo=FALSE, warning=FALSE, message=FALSE, fig.align='center', out.width='60%'----------------------------- p <- ggplot(data = dados) + geom_histogram(mapping = aes(x = `Salario (x Sal Min)`, y = I(36 * ..density..)), breaks = seq(4, 24, by = 4), fill = "steelblue", color = "white") + labs(x = "Salário (x. sal. mínimo)", y = "Densidade de frequência", title = "Distribuição salarial da seção de orçamentos", caption = "Fonte: Companhia MB.") + theme_bw() p ## ----fig-freqpoly, echo=FALSE, warning=FALSE, message=FALSE, fig.align='center', out.width='90%'-------------------------- p <- ggplot(data = dados) + geom_freqpoly(mapping = aes(x = `Salario (x Sal Min)`), breaks = seq(4, 24, by = 4), color = I("#DA70D6"), size = 1) + scale_x_continuous(breaks = seq(4, 24, by = 4)) + labs(x = "Salário (x. sal. mínimo)", y = "Frequência", title = "Distribuição salarial da seção de orçamentos", caption = "Fonte: Companhia MB.") + theme_bw() p <file_sep>--- title: "MAT02018 - Estatística Descritiva" subtitle: "Distribuição de Frequências" fontsize: 10pt author: | | <NAME> | `<EMAIL>` institute: | | \textsc{Universidade Federal do Rio Grande do Sul} | \textsc{Instituto de Matemática e Estatística} | \textsc{Departamento de Estatística} date: | | Porto Alegre, 2021 header-includes: - \titlegraphic{\hfill\includegraphics[height=1.5cm]{logos/Logo-40-anos-estatistica.png}} --- # Introdução ## Introdução {.allowframebreaks} - Uma contribuição importante da estatística no manejo das informações foi a criação de procedimentos para a organização e o resumo de grandes quantidades de dados. - A descrição das variáveis é imprescindível como passo prévio para a adequada interpretação dos resultados de uma investigação, e a metodologia empregada faz parte da estatística descritiva. - Os dados podem ser organizados em \structure{tabelas} ou \structure{gráficos}. Nestas notas de aula, vamos apresentar como organizar a informação em \structure{tabelas de frequências}. # Distribuição de Frequências ## Distribuição de Frequências {.allowframebreaks} - Dados nominais, ordinais e discretos, depois de apurados, devem ser organizados em \structure{tabelas de distribuição de frequências}. - \structure{Frequência de uma categoria (ou valor)} é o número de vezes que essa categoria (ou valor) ocorre no conjunto de dados (uma amostra ou população)\footnote{{\bf Lembrando:} {\bf população} é o conjunto de todos os elementos que apresentam uma ou mais características em comum. Quando o estudo é realizado com toda a população de interesse, chamaremos este estudo de {\bf censo}. Por motivos de tempo, custo, logística, entre outros, geralmente não é possível realizar um censo. Nestes casos, estudamos apenas uma parcela da população, que chamamos de {\bf amostra}. Amostra é qualquer fração de uma população. Como sua finalidade é representar a população, deseja-se que a amostra escolhida apresente as mesmas características da população de origem, isto é, que seja uma amostra {\bf ``representativa''} ou {\bf ``não tendenciosa''}.}. ## Dados nominais {.allowframebreaks} - Para organizar os dados nominais em uma tabela de distribuição de frequências escreva, na __primeira coluna__, o __nome da variável__ em estudo e logo abaixo, na mesma coluna, as categorias (ou seja, os valores) da variável. - Na __segunda coluna__, escreva __"Frequência"__, e logo abaixo as frequências das respectivas categorias. \framebreak - __Exemplo:__ reveja o exemplo do grupo de 15 empregados da seção de orçamentos da Companhia MB. + Anotamos o número de solteiros e casados para organizar os dados em uma tabela de frequências. + Para isso, devemos escrever o nome da variável (_Estado civil_) e, em coluna, as categorias (_solteiro_, _casado_). + As frequências são 8 empregados solteiros e 7 empregados casados que, somadas, dão um total de 15 empregados. \framebreak ```{r, echo=FALSE, message=FALSE, warning=FALSE, purl=FALSE} civil <- c(rep("Solteiro", 8), rep("Casado", 7)) library(summarytools) civil.tab <- as.data.frame(na.omit(summarytools::freq(civil, order = "freq")))["Freq"] civil.tab <- data.frame("estado_civil"= row.names(civil.tab), "freq" = civil.tab$Freq) knitr::kable(civil.tab, col.names = c("Estado civil", "Frequência")) ``` \framebreak ### Observações 1. É comum utilizar a última linha da tabela para expressar o total. Em geral, este deve coincidir com o tamanho do conjunto de dados. Em alguns casos, a variável não foi observada/coletada (_dados ausentes_) para uma ou mais unidades, e portanto, o total deve ser menor que o tamanho do conjunto de dados. 2. Usaremos a \structure{notação $n_i$} para indicar a frequência (absoluta) cada classe, ou categoria, da variável. ## Dados nominais {.allowframebreaks} ### Exercício - Construa a tabela de distribuição de frequências da variável _Região de procedência_ do exemplo do grupo de 15 empregados da seção de orçamentos da Companhia MB. ## Dados ordinais {.allowframebreaks} - Dados ordinais devem ser organizados em tabelas de distribuição de frequências. - Escreva, na primeira coluna, o nome da variável em estudo e, logo abaixo, os nomes das categorias em __ordem crescente__\footnote{Nos referimos a ordem das categorias e não das suas frequências.}. - As frequências devem estar em outra coluna, mas nas linhas das respectivas categorias. ## Dados ordinais {.allowframebreaks} - Retornando ao exemplo do grupo de 15 empregados da seção de orçamentos da Companhia MB, considere a variável _Grau de instrução_. + O nome da variável e suas categorias foram escritos na primeira coluna e, na segunda coluna, as respectivas frequências. ```{r, echo=FALSE, message=FALSE, warning=FALSE, purl=FALSE} escola <- factor(x = c(rep("Ensino fundamental", 9), rep("Ensino médio", 5), "Superior")) escola.tab <- as.data.frame(na.omit(summarytools::freq(escola)))["Freq"] escola.tab <- data.frame("escola"= row.names(escola.tab), "freq" = escola.tab$Freq) knitr::kable(escola.tab, col.names = c("Grau de instrução", "Frequência ($n_i$)")) ``` ## Dados discretos {.allowframebreaks} - Dados discretos também são organizados em tabelas de distribuição de frequências. - Para isso, os valores que a variável pode assumir são colocados na primeira coluna, em __ordem crescente__. - O número de vezes que cada valor se repete (a frequência) é escrito em outra coluna, nas linhas respectivas aos valores. \framebreak - Mais uma vez, retorne ao exemplo da seção de orçamentos da Companhia MB. + O número de filhos dos empregados da seção é apresentado a seguir na distribuição de frequências. ```{r, echo=FALSE, message=FALSE, warning=FALSE, purl=FALSE} filhos <- c(rep(0, 6), rep(1, 4), rep(2, 4), 3) filhos.tab <- as.data.frame(na.omit(summarytools::freq(filhos)))["Freq"] filhos.tab <- data.frame("filhos"= row.names(filhos.tab), "freq" = filhos.tab$Freq) knitr::kable(filhos.tab, col.names = c("Número de filhos", "Frequência ($n_i$)")) ``` ## Para casa 1. Resolver os exercícios 1, 2 e 3 do Capítulo 3.5 do livro __Fundamentos de Estatística__\footnote{Vieira, S. {\bf Fundamentos de Estatística}, Atlas, 2019, pg. 37-38.} (disponível no Sabi+). 2. Para os dados nominais, ordinais e discretos do seu levantamento estatístico, construa tabelas de frequências e compartilhe no Fórum Geral do Moodle. ## Próxima aula - Distribuição de frequências __(dados contínuos)__. ## Por hoje é só! \begin{center} {\bf Bons estudos!} \end{center} ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='50%', out.height='50%', paged.print=FALSE} knitr::include_graphics(here::here('images', 'Statistically-Insignificant-forecast.jpg')) ``` <file_sep>## ----echo=FALSE, message=FALSE, warning=FALSE, results='asis', fig.align='center', out.width="80%"---------------- library(fGarch) r <- rsnorm(1000, xi = 5) layout(mat = matrix(c(1, 2), 2, 1, byrow = TRUE), height = c(1, 8)) par(mar = c(0, 3.1, 1.1, 2.1)) boxplot(r, horizontal = TRUE, ylim = c(-2,5), xaxt = "n" , col = rgb(0.8,0.8,0,0.5) , frame = F) par(mar=c(4, 3.1, 1.1, 2.1)) hist(r, xlab = "x", ylab = "Frequência", col = rgb(0,0.25,0.25,0.5), border = "white", main = "", xlim = c(-2,5)) abline(v = mean(r), lty = 2, col = "red", lwd = 2) text(0.3, 200, "Média") ## ----echo=FALSE, message=FALSE, warning=FALSE, results='asis', fig.align='center', out.width="80%"---------------- library(fGarch) set.seed(2010) r <- rsnorm(1000, xi = -5) layout(mat = matrix(c(1, 2), 2, 1, byrow = TRUE), height = c(1, 8)) par(mar = c(0, 3.1, 1.1, 2.1)) boxplot(r, horizontal = TRUE, ylim = c(-5,2), xaxt = "n" , col = rgb(0.8,0.8,0,0.5) , frame = F) par(mar=c(4, 3.1, 1.1, 2.1)) hist(r, xlab = "x", ylab = "Frequência", col = rgb(0,0.25,0.25,0.5), border = "white", main = "", xlim = c(-5,2)) abline(v = mean(r), lty = 2, col = "red", lwd = 2) text(-0.3, 200, "Média") ## ----echo=FALSE, message=FALSE, warning=FALSE, results='asis', fig.align='center', out.width="80%"---------------- set.seed(1020) x <- sample(x = iris$Petal.Width[iris$Species == "setosa"], size = 30, replace = FALSE) layout(mat = matrix(c(1, 2), 2, 1, byrow = TRUE), height = c(1, 8)) par(mar = c(0, 3.1, 1.1, 2.1)) boxplot(x, horizontal = TRUE, ylim = c(0.1,0.6), xaxt = "n" , col = rgb(0.8,0.8,0,0.5) , frame = F) par(mar=c(4, 3.1, 1.1, 2.1)) hist(x, xlab = "x", ylab = "Frequência", col = rgb(0,0.25,0.25,0.5), border = "white", main = "", xlim = c(0.1,0.6)) abline(v = mean(x), lty = 2, col = "red", lwd = 2) text(0.3, 15, "Média") ## ----echo=FALSE, message=FALSE, warning=FALSE, results='asis', fig.align='center', out.width="100%", fig.cap='Uma distribuição leptocúrtica.'---- library(rmutil) set.seed(2010) m <- rnorm(1000) p <- rt(1000, df = 8) l <- rlaplace(1000, s = 0.25) hist(l, xlab = "x", ylab = "Frequência", col = rgb(0,0.25,0.25,0.5), border = "white", main = "", breaks = 30, xlim = c(-3,3)) ## ----echo=FALSE, message=FALSE, warning=FALSE, results='asis', fig.align='center', out.width="100%", fig.cap='Uma distribuição platicúrtica.'---- hist(p, xlab = "x", ylab = "Frequência", col = rgb(0,0.25,0.25,0.5), border = "white", main = "", breaks = 30, xlim = c(-3,3)) ## ----echo=FALSE, message=FALSE, warning=FALSE, results='asis', fig.align='center', out.width="100%", fig.cap='Uma distribuição mesocúrtica.'---- hist(m, xlab = "x", ylab = "Frequência", col = rgb(0,0.25,0.25,0.5), border = "white", main = "", breaks = 30, xlim = c(-3,3)) ## ----echo=FALSE, message=FALSE, warning=FALSE, results='asis', fig.align='center', out.width="80%"---------------- set.seed(1020) x <- sample(x = iris$Petal.Length[iris$Species == "setosa"], size = 30, replace = FALSE) layout(mat = matrix(c(1, 2), 2, 1, byrow = TRUE), height = c(1, 8)) par(mar = c(0, 3.1, 1.1, 2.1)) boxplot(x, horizontal = TRUE, ylim = c(1,2), xaxt = "n" , col = rgb(0.8,0.8,0,0.5) , frame = F) par(mar=c(4, 3.1, 1.1, 2.1)) hist(x, xlab = "x", ylab = "Frequência", col = rgb(0,0.25,0.25,0.5), border = "white", main = "", xlim = c(1,2)) abline(v = mean(x), lty = 2, col = "red", lwd = 2) text(1.6, 12, "Média") ## ----echo=FALSE, message=FALSE, warning=FALSE--------------------------------------------------------------------- library(SemiPar) library(knitr) data(pig.weights) kable(t(pig.weights$weight[pig.weights$num.weeks == 1][1:5]), col.names = paste("Ovelha",1:5), format.args = list(decimal.mark = ",")) ## ----echo=FALSE, message=FALSE, warning=FALSE, results='asis', fig.align='center', out.width="80%"---------------- library(SemiPar) data(pig.weights) hist(pig.weights$weight[pig.weights$num.weeks == 1], xlab = "Peso de 48 ovelhas", ylab = "Frequência", col = rgb(0,0,1,0.5), border = "white", main = "") abline(v = mean(pig.weights$weight[pig.weights$num.weeks == 1]), lty = 2, col = "red", lwd = 2) text(28, 15, "Média = 25 kg\n s = 2,47 kg") ## ----echo=FALSE, message=FALSE, warning=FALSE, results='asis', fig.align='center', out.width="80%"---------------- hist(pig.weights$weight[pig.weights$num.weeks == 1] - 8, xlab = "Peso de 48 ovelhas depois da tosa", ylab = "Frequência", col = rgb(1,0,0,0.5), border = "white", main = "") abline(v = mean(pig.weights$weight[pig.weights$num.weeks == 1] - 8), lty = 2, col = "red", lwd = 2) text(20, 15, "Média = 17 kg\n s = 2,47 kg") ## ----echo=FALSE, message=FALSE, warning=FALSE, results='asis', fig.align='center', out.width="80%"---------------- hist(pig.weights$weight[pig.weights$num.weeks == 1] - 8, xlab = "Peso de 48 ovelhas", ylab = "Frequência", col = rgb(1,0,0,0.5), border = "white", main = "", xlim = c(8, 34)) hist(pig.weights$weight[pig.weights$num.weeks == 1], col = rgb(0,0,1,0.5), border = "white", add = TRUE) abline(v = c(mean(pig.weights$weight[pig.weights$num.weeks == 1] - 8), mean(pig.weights$weight[pig.weights$num.weeks == 1])), lty = 2, col = "red", lwd = 2) legend("topright", fill = c(rgb(1,0,0,0.5), rgb(0,0,1,0.5)), border = "white", c("Depois da tosa", "Antes da tosa"), bty = "n") ## ----echo=FALSE, message=FALSE, warning=FALSE, results='asis', fig.align='center', out.width="80%"---------------- hist(pig.weights$weight[pig.weights$num.weeks == 1]*1.5, xlab = "Peso de 48 ovelhas em gestação", ylab = "Frequência", col = rgb(0,1,0,0.5), border = "white", main = "") abline(v = mean(pig.weights$weight[pig.weights$num.weeks == 1]*1.5), lty = 2, col = "red", lwd = 2) text(40, 10, "Média = 37,5 kg\n s = 3,7 kg") ## ----echo=FALSE, message=FALSE, warning=FALSE, results='asis', fig.align='center', out.width="80%"---------------- hist(pig.weights$weight[pig.weights$num.weeks == 1]*1.5, xlab = "Peso de 48 ovelhas", ylab = "Frequência", col = rgb(0,1,0,0.5), border = "white", main = "", xlim = c(18, 52)) hist(pig.weights$weight[pig.weights$num.weeks == 1], col = rgb(0,0,1,0.5), border = "white", add = TRUE) abline(v = c(mean(pig.weights$weight[pig.weights$num.weeks == 1]), mean(pig.weights$weight[pig.weights$num.weeks == 1]*1.5)), lty = 2, col = "red", lwd = 2) legend("topright", fill = c(rgb(0,0,1,0.5), rgb(0,1,0,0.5)), border = "white", c("Antes da gestação", "Na gestação"), bty = "n") ## ----carrega-dados0, echo=TRUE, eval=FALSE, warning=FALSE, message=FALSE------------------------------------------ ## # install.packages("readxl") library(readxl) dados <- read_excel(path = "companhia_mb.xlsx") ## ----carrega-dados2, warning=FALSE, message=FALSE----------------------------------------------------------------- class(dados) # classe do objeto dados dim(dados) # dimensão do objeto dados ## ----carrega-dados3, warning=FALSE, message=FALSE----------------------------------------------------------------- head(dados) # apresenta as primeiras linhas do objeto dados ## ----exetremos, warning=FALSE, message=FALSE---------------------------------------------------------------------- # install.packages("e1071") library(e1071) skewness(dados$Idade) kurtosis(dados$Idade) skewness(dados$`Salario (x Sal Min)`) kurtosis(dados$`Salario (x Sal Min)`) skewness(dados$`N de Filhos`, na.rm = TRUE) kurtosis(dados$`N de Filhos`, na.rm = TRUE) <file_sep>## ----carrega-dados1, echo=FALSE, warning=FALSE, message=FALSE------------------------------------------------------------ # install.packages("readxl") library(readxl) library(stringr) dados <- read_excel(path = here::here("data", "companhia_mb.xlsx")) set.seed(123) dados$`Grau de Instrução`[dados$`Grau de Instrução` == "ensino fundamental"] <- sample(x = c("fundamental incompleto", "fundamental completo"), size = length(dados$`Grau de Instrução`[dados$`Grau de Instrução` == "ensino fundamental"]), replace = T) dados$`Grau de Instrução`[dados$`Grau de Instrução` == "ensino médio"] <- sample(x = c("médio incompleto", "médio completo"), size = length(dados$`Grau de Instrução`[dados$`Grau de Instrução` == "ensino médio"]), replace = T) dados$`Grau de Instrução`[dados$`Grau de Instrução` == "superior"] <- sample(x = c("superior incompleto", "superior completo"), size = length(dados$`Grau de Instrução`[dados$`Grau de Instrução` == "superior"]), replace = T) dados$`Estado Civil` <- str_to_title(dados$`Estado Civil`) dados$`Grau de Instrução` <- str_to_title(dados$`Grau de Instrução`) dados$`Região de Procedência` <- str_to_title(dados$`Região de Procedência`) dados$`Grau de Instrução` <- factor(dados$`Grau de Instrução`, levels = c("Fundamental Incompleto", "Fundamental Completo", "Médio Incompleto", "Médio Completo", "Superior Incompleto", "Superior Completo")) ## ----fig-barras1, echo=FALSE, warning=FALSE, message=FALSE, fig.align='center', out.width='75%'-------------------------- library(ggplot2) p.barras <- ggplot(data = dados, mapping = aes(x = `Grau de Instrução`)) + geom_bar(stat = "count", width = 0.5, aes(fill = I("steelblue"))) + labs(x = "Grau de Instrução", y = "Frequência", title = "Escolaridade dos empregados da seção de orçamentos.", caption = "Fonte: Companhia MB.") + theme_bw() + theme(axis.text.x = element_text(angle = 45, hjust = 1)) p.barras ## ----fig-barras2, echo=FALSE, warning=FALSE, message=FALSE, out.width="80%", fig.align='center'-------------------------- p.barras <- ggplot(data = dados, mapping = aes(x = `Grau de Instrução`)) + geom_bar(stat = "count", width = 0.5, aes(y = (..count..)/sum(..count..), fill = I("lightsalmon"))) + labs(x = "Grau de Instrução", y = "Frequência relativa", title = "Escolaridade dos empregados da seção de orçamentos.", caption = "Fonte: Companhia MB.") + theme_bw() + theme(axis.text.x = element_text(angle = 45, hjust = 1)) p.barras ## ----fig-barras3, echo=FALSE, warning=FALSE, message=FALSE, out.width="80%", fig.align='center'-------------------------- p.barras <- ggplot(data = dados, mapping = aes(x = `Grau de Instrução`)) + geom_bar(stat = "count", width = 0.5, aes(y = (..count..)/sum(..count..), fill = I("#77DD77"))) + geom_text(aes(label = scales::percent( (..count..)/sum(..count..)), y = (..count..)/sum(..count..) ), stat = "count", vjust = -.5) + scale_y_continuous(limits = c(0, 0.35), labels = scales::percent) + labs(x = "Grau de Instrução", y = "Porcentagem", title = "Escolaridade dos empregados da seção de orçamentos.", caption = "Fonte: Companhia MB.") + theme_bw() + theme(axis.text.x = element_text(angle = 45, hjust = 1)) p.barras ## ----fig-barras4, echo=FALSE, warning=FALSE, message=FALSE, out.width="65%", out.height='65%', fig.align='center'-------- p.barras <- ggplot(data = dados, mapping = aes(x = `Grau de Instrução`)) + geom_bar(stat = "count", width = 0.5, aes(y = (..count..)/sum(..count..), fill = I("#DA70D6"))) + geom_text(aes(label = scales::percent( (..count..)/sum(..count..)), y = (..count..)/sum(..count..) ), stat = "count", hjust = -.5) + scale_y_continuous(limits = c(0, 0.35), labels = scales::percent) + labs(x = "Grau de Instrução", y = "Porcentagem", title = "Escolaridade dos empregados da seção de orçamentos.", caption = "Fonte: Companhia MB.") + coord_flip() + theme_bw() p.barras ## ----fig-barras5, echo=FALSE, warning=FALSE, message=FALSE, out.width="100%", fig.align='center'------------------------- library(dplyr) df_barras <- dados %>% group_by(`Grau de Instrução`) %>% summarise(n = n()) %>% mutate(freq = 100 * (n / sum(n))) p.barras <- ggplot(data = df_barras, mapping = aes(y = `Grau de Instrução`, x = freq, label = paste0(round(freq, 0), "%"))) + geom_segment(aes(x = 0, y = `Grau de Instrução`, xend = freq, yend = `Grau de Instrução`), color = "grey50") + geom_point(size = 7, color = "#FF5349") + geom_text(color = "white", size = 2) + labs(y = "Grau de Instrução", x = "Porcentagem", title = "Escolaridade dos empregados da seção de orçamentos.", caption = "Fonte: Companhia MB.") + theme_bw() p.barras ## ---- echo=FALSE, message=FALSE, warning=FALSE--------------------------------------------------------------------------- library(janitor) df_regiao <- dados %>% group_by(`Região de Procedência`) %>% summarise(n = n()) %>% mutate(freq = round(100 * (n / sum(n)), 0)) %>% adorn_totals("row") knitr::kable(df_regiao, col.names = c("Região de Procedência", "Frequência ($n_i$)", "Porcentagem"), align = c('l', 'c', 'c'), digits = c(0,0,1)) ## ----fig-variacoes-setores, echo=FALSE, warning=FALSE, message=FALSE, out.width="90%", fig.align='center'---------------- # # p.setores <- ggplot(data = df_regiao, aes(x = "", y = freq, fill = `Região de Procedência`)) + # geom_bar(stat = "identity", width = 1) + # coord_polar("y", start = 0) + # theme_void() # remove background, grid, numeric labels p1 <- ggplot(df_regiao[1:3, ], aes(x = 2, freq, fill = `Região de Procedência`)) + geom_bar(width = 1, size = 1, color = "white", stat = "identity") + coord_polar("y") + geom_text(aes(label = paste0(round(freq), "%")), position = position_stack(vjust = 0.5)) + labs(x = NULL, y = NULL, fill = NULL, title = "Região de Procedência") + guides(fill = guide_legend(reverse = TRUE)) + scale_fill_manual(values = c("#ffd700", "#254290", "#bcbcbc")) + theme_classic() + theme(axis.line = element_blank(), axis.text = element_blank(), axis.ticks = element_blank(), plot.title = element_text(hjust = 0.5, color = "#666666")) + xlim(0.5, 2.5) p2 <- ggplot(dados, aes(y = "", fill = factor(`Região de Procedência`))) + geom_bar(width = 1, size = 0.1, color = "white", position = "fill") + scale_fill_manual(values = c("#ffd700", "#254290", "#bcbcbc")) + # geom_text(data = NULL, aes(label = paste(df_regiao$freq[1:3], "%"), # x = df_regiao$freq[1:3]), hjust = -.5) + scale_x_continuous(labels = scales::percent) + labs(fill = "Procedência", x = "") + theme_classic() + theme(legend.position = 'bottom', legend.text = element_text(size = 8), axis.title.y = element_blank(), axis.ticks.y = element_blank(), axis.line.y = element_blank(), axis.text.y = element_blank()) library(waffle) library(hrbrthemes) p3 <- ggplot(data = df_regiao[1:3,], aes(fill = `Região de Procedência`, values = n)) + geom_waffle(n_rows = 10, size = 0.33, colour = "white", flip = TRUE) + scale_fill_manual( name = "Região de Procedência", values = c("#ffd700", "#254290", "#bcbcbc"), labels = c("Capital", "Interior", "Outra") ) + coord_equal() + # theme_ipsum_rc(grid = "") + theme_enhance_waffle() library(cowplot) grid1 <- plot_grid(p1, p2, labels = c('A', 'B'), label_size = 10) plot_grid(grid1, p3, labels = c('', 'C'), label_size = 10, ncol = 1) ## ----echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='50%', out.height='50%', paged.print=FALSE---- knitr::include_graphics(here::here('images', 'Statistically-Insignificant-capediem.jpg')) <file_sep>--- title: "MAT02018 - Estatística Descritiva" subtitle: "Medidas de tendência central" fontsize: 10pt author: | | <NAME> | `<EMAIL>` institute: | | \textsc{Universidade Federal do Rio Grande do Sul} | \textsc{Instituto de Matemática e Estatística} | \textsc{Departamento de Estatística} date: | | Porto Alegre, 2022 bibliography: estatistica-descritiva.bib csl: associacao-brasileira-de-normas-tecnicas-ufrgs-initials.csl link-citations: yes --- # Introdução ## Introdução {.allowframebreaks} - As \structure{medidas de tendência central} (ou \structure{de locação} ou também \structure{de posição}) são \structure{valores} calculados com o objetivo de representar os dados de uma forma ainda mais condensada do que usando uma tabela. - Quando o desejo é representar, por meio de um valor único, determinado conjunto de informações que variam, parece razoável escolher um __valor central__, mesmo que esse valor seja uma abstração. \framebreak ```{r, cache=TRUE, message=FALSE, echo=FALSE, out.width="20%", purl=FALSE, fig.align='right'} knitr::include_graphics(here::here('images', 'Revisao-de-Prova.jpg')) ``` - Assim, se um aluno realizou quatro provas objetivas com 20 questões cada uma, e o número de acertos, em cada prova, foi $$ (14, 19, 16, 17) $$ o professor poderá querer registrar o desempenho do aluno por um valor "central", a \structure{média aritmética}, por exemplo. - A média aritmética de tais valores é \structure{$16,5$}. - Embora seja uma quantidade de acertos que __não pode ocorrer na realidade__, ela está mostrando que o aluno __apresentou em geral um bom desempenho__. \framebreak - Há várias medidas de tendência central. - As mais utilizadas em análise estatística são a \structure{média aritmética}, a \structure{mediana} e a \structure{moda}. - Nestas notas apresentamos a definição destas medidas, e através de exemplos, como calculá-las e interpretá-las. # Média aritmética ## Média aritmética {.allowframebreaks} - A \structure{média aritmética}, ou simplesmente \structure{média}, é a medida de tendência central mais utilizada. - Isto se deve, em parte, por ser uma medida fácil de calcular, que tem interpretação familiar e propriedades estatísticas que a tornam muito útil nas comparações entre populações. - Quando calculada para a população, também é chamada de \structure{valor esperado} da variável, ou \structure{esperança matemática}. - Pode-se também imaginar a média como \structure{centro de gravidade} de uma distribuição. - Assim, na figura a seguir, os blocos azuis representam os valores observados para uma certa variável\footnote{Pense que estes blocos possuem um peso, de tal forma que a barra amarela se desequilibra conforme os blocos se movem em cima dela.}. ## Média aritmética {.allowframebreaks} - Note que conforme estes valores estão posicionados (distribuídos), a média \textcolor{red}{(triângulo em vermelho)}, se desloca, de tal forma que este valor mantém o equilíbrio da distribuição \textcolor{yellow}{(representada pela barra amarela)}. ```{r fig-media, fig.align='center', cache=TRUE, echo=FALSE, out.width="50%", purl=FALSE, out.height='50%'} options(knitr.kable.NA = '-') knitr::include_graphics(here::here('images', 'media_centro_gravidade2.png')) ``` \framebreak - Se um valor se afasta dos demais valores da distribuição, como ocorre na figura abaixo, a média também se deslocada para manter o equilíbrio da distribuição\footnote{{\bf Para pensar:} neste caso, a média é uma boa representação sumária da distribuição?}. ```{r fig-media2, fig.align='center', cache=TRUE, echo=FALSE, out.width="50%", purl=FALSE, out.height='50%'} knitr::include_graphics(here::here('images', 'media_centro_gravidade.png')) ``` ## Média aritmética {.allowframebreaks} - Agora vamos definir a média aritmética. - Seja \structure{$x$} uma variável de interesse e \structure{$x_1, x_2, \ldots, x_n$} observações de \structure{$x$} em um conjunto de dados (amostra ou população) de tamanho \structure{$n$}. - A média amostral é denotada por \structure{$\overline{x}$}, enquanto que a média populacional é, geralmente, denotada por \structure{$\mu$}\footnote{Na população, o número de elementos é presentado por $N$.}. - Para dados que __não estão__ agrupados, a média é simplesmente a soma de todos os valores observados da variável dividido pelo número de observações\footnote{A letra grega $\Sigma$ (sigma) é usada como símbolo para indicar uma soma. Assim, $\sum_{i=1}^n{x_i}$ indica o ``somatório de $x$ índice $i$, $i$ variando de $1$ a $n$''. Ou seja, estamos somando os $n$ elementos do conjunto $\{x_i; i = 1,\ldots, n\}$. Cada $x_i$ representa o valor da variável $x$ com respeito ao $i$-ésimo indivíduo. Por exemplo, se ``Harry'' apresentou o valor 19 anos para a variável idade (representada por $x$), e Harry foi o entrevistado de número 48 em um certo inquérito, temos que $x_{48} = 19$.} $$ \overline{x} = \frac{1}{n}\sum_{i=1}^n{x_i} = \frac{x_1 + x_2 + \ldots + x_n}{n}. $$ ## Média aritmética (exemplo) {.allowframebreaks} - Suponha que, ao estudar a quantidade de albumina no plasma de pessoas com determinada doença, um pesquisador obtenha, em 25 indivíduos, os seguintes valores (em g/100 ML): ```{r, echo=FALSE, message=FALSE, warning=FALSE, purl=FALSE} library(knitr) kable(x = matrix(data = c(5.1, 4.9, 4.9, 5.1, 4.7, 5.0, 5.0, 5.0, 5.1, 5.4, 5.2, 5.2, 4.9, 5.3, 5.0, 4.5, 5.4, 5.1, 4.7, 5.5, 4.8, 5.1, 5.3, 5.3, 5.0), ncol = 5, byrow = T), format = "pandoc", escape = FALSE, align = "c", format.args = list(decimal.mark = ",") ) ``` \framebreak - Considere que $x$ representa a variável __quantidade de albumina no plasma__, e portanto, $x_1 = 5,1; x_2 = 4,9; \ldots; x_{25} = 5,0$. A média, conforme a sua definição, é calculada $$ \overline{x} = \frac{1}{25}\sum_{i=1}^{25}{x_i} = \frac{5,1 + 4,9 + \ldots + 5,0}{25} = \frac{126,5}{25} = 5,06. $$ \framebreak - Assim, temos que o valor médio da __quantidade de albumina no plasma__ neste grupo de indivíduos é \structure{$5,06$ g/100 mL}. - Note que a média é uma característica da distribuição, e não de um ou outro indivíduo/observação em particular. - As observações estão distribuídas em torno deste valor\footnote{Faça um diagrama de pontos com os valores do exemplo, e avalie se a média é o ponto de equilíbrio esta distribuição}. - Note que a média \structure{é influenciada pelos valores extremos} da distribuição. + Se no lugar de \structure{$x_{20} = 5,5$} __(hipoteticamente)__ observássemos o valor \structure{$6,8$}, então teríamos que média seria \structure{$5,11$}. ## Média aritmética (exercício) {.allowframebreaks} __Sua vez!__ (largura da pétala de íris): calcule a média para o seguinte conjunto de dados. ```{r, echo=FALSE, message=FALSE, warning=FALSE, purl=FALSE} set.seed(1309) petal.width.sample <- sample(iris$Petal.Width, 10, replace = F) kable(x = matrix(petal.width.sample, ncol = 5, byrow = T), format = "pandoc", align = "c", format.args = list(decimal.mark = ",")) ``` # Cálculo da média para dados em agrupamento simples ## Média para dados em agrupamento simples {.allowframebreaks} - Para dados que são apresentados em agrupamentos simples\footnote{Imagine que você não possui acesso a planilha de dados brutos, logo você não tem a informação a nível da observação. Mas, digamos que você tenha acesso a uma tabela de frequências (uma forma já resumida/agregada) da variável de interesse.}, - calcula-se a média do seguinte modo: $$ \overline{x} = \frac{\sum_i{n_ix_i}}{\sum_i{n_i}}, $$ em que \structure{$n_i$} é a frequência absoluta do valor \structure{$x_i$}. ## Média para dados em agrupamento simples {.allowframebreaks} - Nota-se que, no caso de haver um agrupamento de dados, cada valor de \structure{$x$} deve ser multiplicado pelo \structure{número de vezes em que ele ocorre}, para depois se obter a soma. - Podemos utilizar uma calculadora, fórmulas de planilhas eletrônicas, ou ainda funções de um _software_ estatístico para nos auxiliar neste procedimento. \framebreak - \structure{Exemplo (número de carburadores):} suponha que, em uma amostra de 32 diferentes modelos de automóveis, coletamos a informação com respeito ao número de carburadores e organizamos os dados em uma tabela de frequência. ```{r, echo=FALSE, message=FALSE, warning=FALSE, purl=FALSE} library(knitr) mtcars_pe <- mtcars[,-3] freq_table_carb <- as.data.frame(table(mtcars_pe$carb)) freq_table_carb[,1] <- as.character(freq_table_carb[,1]) aux <- data.frame(Var1 = as.character("Total"), Freq = sum(freq_table_carb$Freq)) freq_table_carb <- rbind(freq_table_carb, aux) names(freq_table_carb) <- c("Número de carburadores ($x_i$)", "Frequência ($n_i$)") kable(freq_table_carb, align = c('l','c')) ``` \framebreak - Multiplicando a primeira coluna (valores da variável \structure{$x$}) pela segunda coluna (frequências de \structure{$x$}) obtemos os elementos \structure{$n_ix_i$}. ```{r, echo=FALSE, message=FALSE, warning=FALSE, purl=FALSE} freq_table_carb$"$n_ix_i$" <- c(as.numeric(freq_table_carb[-length(freq_table_carb[,1]),1]) * freq_table_carb[-length(freq_table_carb[,1]),2], sum(as.numeric(freq_table_carb[-length(freq_table_carb[,1]),1]) * freq_table_carb[-length(freq_table_carb[,1]),2])) freq_table_carb %>% kable(align = c('l','c', 'c'), format.args = list(decimal.mark = ",")) ``` \framebreak - E assim temos que o número médio de carburadores neste grupo de automóveis estudado é $$ \overline{x} = \frac{(7\times 1 + 10 \times 2 + \ldots + 8 \times 1)}{(7 + 10 + \ldots + 8)} = \frac{(7 + 20 + \ldots + 8)}{(7 + 10 + \ldots + 8)} = \frac{90}{32} = 2,8. $$ - Note que o número de carburadores, em cada carro, é um valor inteiro, porém, a média não precisa ser necessariamente um número inteiro\footnote{Lembramos novamente aqui que a média é uma característica da distribuição (do grupo e não de um indivíduo/unidade).}. ## Média para dados em agrupamento simples {.allowframebreaks} - Uma forma alternativa para calcular a média, no caso de agrupamentos simples, consiste em notar que $1/\sum_i{n_i}$ é uma constante, e portanto, podemos reescrever $$ \overline{x} = \frac{1}{\sum_{i=1}{n_i}}\sum_{i=1}{n_ix_i}= \sum_{i=1}{x_i\frac{n_i}{\sum_{i=1}{n_i}}}. $$ - Como $\sum_i{n_i} = n$\footnote{Salve o caso em temos dados ausentes. Neste caso $n$ é o número de elementos com dados observados.} o cálculo da média é expresso em função dos seus valores e suas frequências relativas ($f_i$) $$ \overline{x} = \frac{1}{\sum_{i=1}{n_i}}\sum_{i=1}{n_ix_i}= \sum_{i=1}{x_i\frac{n_i}{\sum_{i=1}{n_i}}} = \sum_{i=1}{x_i\frac{n_i}{n}} = \sum_{i=1}{x_if_i}. $$ ## Média para dados em agrupamento simples {.allowframebreaks} - Utilizando esta forma alternativa para o caso do exemplo dos carburadores, calculamos as frequências relativas, e em seguida multiplicamos as colunas \structure{$x_i$} e \structure{$f_i$}. - A soma da coluna resultante é o valor da média do número de carburadores. ```{r, echo=FALSE, message=FALSE, warning=FALSE, purl=FALSE} freq_table_carb[, 3] <- NULL freq_table_carb$"$f_i$" <- freq_table_carb[,2] / sum(freq_table_carb[,2][-length(freq_table_carb[,2])]) freq_table_carb$"$f_ix_i$" <- c(as.numeric(freq_table_carb[-length(freq_table_carb[,1]),1]) * freq_table_carb[-length(freq_table_carb[,1]),3], sum(as.numeric(freq_table_carb[-length(freq_table_carb[,1]),1]) * freq_table_carb[-length(freq_table_carb[,1]),3])) freq_table_carb %>% kable(align = c('l','c', 'c', 'c'), digits = c(0,0,2,2), format.args = list(decimal.mark = ",")) ``` # Cálculo da média para dados em agrupamento por intervalo de classe ## Média para dados em agrupamento por intervalo de classe - Quando os dados estão organizados em uma \structure{tabela com intervalos de classe}, é preciso haver um valor que represente cada intervalo. - Este valor é o \structure{ponto médio} do intervalo de classe, denotado por \structure{$M$}\footnote{Lembre que já utilizamos o ponto médio (ou ponto central) do intervalo de classe na construção do {\bf polígono de frequências}.}. - __Relembrando:__ o ponto médio é a média aritmética dos dois extremos de classe $$ M = \frac{\mbox{limite inf. do int. de classe} + \mbox{limite sup. do int. de classe}}{2}. $$ ## Média para dados em agrupamento por intervalo de classe {.allowframebreaks} - A média é calculada da mesma forma que no caso do agrupamento simples, substituindo \structure{$x_i$} por \structure{$M_i$}: $$ \overline{x} = \frac{\sum_i{n_iM_i}}{\sum_i{n_i}} = \sum_i{M_i\frac{n_i}{n}} = \sum_i{M_if_i}, $$ em que \structure{$M_i$}, \structure{$n_i$} e \structure{$f_i$} representam, respectivamente, o \structure{ponto médio}, a \structure{frequência absoluta} e a \structure{frequência relativa} da \structure{$i$}-ésima classe. \framebreak \structure{Exemplo (milhas por galão):} considere mais uma vez o exemplo do levantamento estatístico de 32 modelos de automóveis. Os dados referentes a variável _milhas por galão_, que é uma medida do desempenho do carro, foram organizados na tabela de frequências de intervalos de classe apresentada a seguir. ```{r, echo=FALSE, message=FALSE, warning=FALSE, purl=FALSE} freq_table_carb <- as.data.frame(table(cut(x = mtcars$mpg, breaks = nclass.Sturges(mtcars$mpg), labels = c("10,4 $\\vdash$ 14,3", "14,3 $\\vdash$ 18,2", "18,2 $\\vdash$ 22,1", "22,1 $\\vdash$ 26,1", "26,1 $\\vdash$ 30,0", "30,0 $\\vdash$ 33,9"), right = FALSE))) freq_table_carb[,1] <- as.character(freq_table_carb[,1]) aux <- data.frame(Var1 = as.character("Total"), Freq = sum(freq_table_carb$Freq)) freq_table_carb <- rbind(freq_table_carb, aux) names(freq_table_carb) <- c("Milhas por galão", "$n_i$") freq_table_carb$"$f_i$" <- freq_table_carb$"$n_i$"/sum(freq_table_carb$"$n_i$"[-length(freq_table_carb[,2])]) freq_table_carb %>% kable(align = c('l', 'c', 'c'), digits = c(0, 0, 2), format.args = list(decimal.mark = ",")) ``` \framebreak - Para obter a média da distribuição da variável __milhas por galão__, calculamos os pontos médios (\structure{$M_i$}) e multiplicamos estes pelas suas respectivas frequências relativas (\structure{$f_i$}). - Logo após, somamos esta coluna (\structure{$M_if_i$}). + O resultado é a média de milhas por galão neste conjunto de 32 automóveis. ```{r, echo=FALSE, message=FALSE, warning=FALSE, purl=FALSE} freq_table_carb$"$M_i$" <- c(12.35, 16.25, 20.15, 24.1, 28.05, 31.95, NA) freq_table_carb$"$M_if_i$" <- freq_table_carb$"$M_i$" * freq_table_carb$"$f_i$" freq_table_carb$"$M_if_i$"[7] <- sum(freq_table_carb$"$M_if_i$"[-7]) freq_table_carb %>% kable(align = c('l', 'c', 'c', 'c', 'c'), digits = c(0, 0, 2, 2, 2), format.args = list(decimal.mark = ",")) ``` \framebreak \structure{Sua vez! (Teste de Desempenho Escolar):} calcule a média para os dados agrupados em intervalos de classe para o exemplo de desempenho escolar (TDE) referente a 27 alunos. ```{r, echo=FALSE, message=FALSE, warning=FALSE, purl=FALSE} tde <- c(7, 18, 111, 25, 101, 85, 81, 75, 100, 95, 98, 108, 100, 94, 34, 99, 84, 90, 95, 102, 96, 105, 100, 107, 117, 96, 17) tde.cat <- cut(x = tde, breaks = c(7, 29, 51, 73, 95, 117), labels = c("7 $\\vdash$ 29", "29 $\\vdash$ 51", "51 $\\vdash$ 73", "73 $\\vdash$ 95", "95 $\\vdash$ 117"), include.lowest = F, right = FALSE) tde.tab <- as.data.frame(na.omit(summarytools::freq(tde.cat)))["Freq"] tde.tab <- data.frame("tde"= row.names(tde.tab), "freq" = tde.tab$Freq) knitr::kable(tde.tab, col.names = c("Classe TDE", "Frequência ($n_i$)")) ``` ## Para casa 1. Resolver os exercícios 1 a 3 do Capítulo 8.5 do livro __Fundamentos de Estatística__\footnote{Vieira, S. {\bf Fundamentos de Estatística}, Atlas, 2019, p. 135-136.} (disponível no Sabi+). 2. Para o seu levantamento estatístico, calcule médias, modas e medianas, de acordo com a classificação das variáveis. Compartilhe no Fórum Geral do Moodle. ## Próxima aula - Mediana e moda. - Médias ponderada, geométrica e harmônica. - Complementa`R`. ## Por hoje é só! \begin{center} {\bf Bons estudos!} \end{center} ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='50%', out.height='50%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'Statistically-Insignificant-barras05.jpg')) ``` <file_sep>--- # title: "Estatística Descritiva" title: "Distribuição de Frequências" author: "<NAME>, Dep. de Estatística - UFRGS" date: '`r paste(stringr::str_to_title(format(Sys.Date(), "%B")), format(Sys.Date(), "%Y"), sep = " de ")`' output: tufte::tufte_handout: citation_package: natbib latex_engine: xelatex tufte::tufte_html: self_contained: true tufte::tufte_book: citation_package: natbib latex_engine: xelatex bibliography: estatistica-descritiva.bib csl: associacao-brasileira-de-normas-tecnicas-ufrgs-initials.csl link-citations: yes --- ```{r setup, include=FALSE, purl=FALSE} library(tufte) # invalidate cache when the tufte version changes knitr::opts_chunk$set(tidy = FALSE, cache.extra = packageVersion('tufte')) options(htmltools.dir.version = FALSE) ``` # Introdução Uma contribuição importante da estatística no manejo das informações foi a criação de procedimentos para a organização e o resumo de grandes quantidades de dados. A descrição das variáveis é imprescindível como passo prévio para a adequada interpretação dos resultados de uma investigação, e a metodologia empregada faz parte da estatística descritiva. Os dados podem ser organizados em __tabelas__ ou __gráficos__. Nestas notas de aula, vamos apresentar como organizar a informação em __tabelas de frequências__. # Distribuição de Frequências Dados nominais, ordinais e discretos, depois de apurados, devem ser organizados em __tabelas de distribuição de frequências__. - __Frequência de uma categoria (ou valor)__ é o número de vezes que essa categoria (ou valor) ocorre no conjunto de dados (uma amostra ou população)^[__Lembrando:__ __população__ é o conjunto de todos os elementos que apresentam uma ou mais características em comum. Quando o estudo é realizado com toda a população de interesse, chamemos este estudo de __censo__. Por motivos de tempo, custo, logística, entre outros, geralmente não é possível realizar um censo. Nestes casos, estudamos apenas uma parcela da população, que chamamos de __amostra__. Amostra é qualquer fração de uma população. Como sua finalidade é representar a população, deseja-se que a amostra escolhida apresente as mesmas características da população de origem, isto é, que seja uma amostra __"representativa"__ ou __"não-tendenciosa__.]. - __Distribuição de frequências__ é a maneira de apresentar categorias (ou intervalos, ou valores) dos dados apurados com as respectivas frequências. ## Dados nominais Para organizar os dados nominais em uma tabela de distribuição de frequências escreva, na __primeira coluna__, o __nome da variável__ em estudo e logo abaixo, na mesma coluna, as categorias (ou seja, os valores) da variável. Na __segunda coluna__, escreva __"Frequência"__, e logo abaixo as frequências das respectivas categorias. __Exemplo:__ reveja o exemplo do grupo de 15 empregados da seção de orçamentos da Companhia MB. Anotamos o número de solteiros e casados para organizar os dados em uma tabela de frequências. Para isso, devemos escrever o nome da variável (_Estado civil_) e, em coluna, as categorias (_solteiro_, _casado_). As frequências são 8 empregados solteiros e 7 empregados casados que, somadas, dão um total de 15 empregados. ```{r, echo=FALSE, message=FALSE, warning=FALSE, purl=FALSE} civil <- c(rep("Solteiro", 8), rep("Casado", 7)) library(summarytools) civil.tab <- as.data.frame(na.omit(summarytools::freq(civil, order = "freq")))["Freq"] civil.tab <- data.frame("estado_civil"= row.names(civil.tab), "freq" = civil.tab$Freq) knitr::kable(civil.tab, col.names = c("Estado civil", "Frequência")) ``` __Observações:__ 1. É comum utilizar a última linha da tabela para expressar o total. Em geral, este deve coincidir com o tamanho do conjunto de dados. Em alguns casos, a variável não foi observada/coletada (_dados ausentes_) para uma ou mais unidades, e portanto, o total deve ser menor que o tamanho do conjunto de dados. 2. Usaremos a __notação__ $n_i$ para indicar a frequência (absoluta) cada classe, ou categoria, da variável. __Exercício:__ - Construa a tabela de distribuição de frequências da variável _Região de procedência_ do exemplo do grupo de 15 empregados da seção de orçamentos da Companhia MB. ## Dados ordinais Dados ordinais devem ser organizados em tabelas de distribuição de frequências. Escreva, na primeira coluna, o nome da variável em estudo e, logo abaixo, os nomes das categorias em __ordem crescente__^[Nos referimos a ordem das categorias e não das suas frequências.]. As frequências devem estar em outra coluna, mas nas linhas das respectivas categorias. Retornando ao exemplo do grupo de 15 empregados da seção de orçamentos da Companhia MB, considere a variável _Grau de instrução_. O nome da variável e suas categorias foram escritos na primeira coluna e, na segunda coluna, as respectivas frequências. ```{r, echo=FALSE, message=FALSE, warning=FALSE, purl=FALSE} escola <- factor(x = c(rep("Ensino fundamental", 9), rep("Ensino médio", 5), "Superior")) escola.tab <- as.data.frame(na.omit(summarytools::freq(escola)))["Freq"] escola.tab <- data.frame("escola"= row.names(escola.tab), "freq" = escola.tab$Freq) knitr::kable(escola.tab, col.names = c("Grau de instrução", "Frequência ($n_i$)")) ``` ## Dados discretos Dados discretos também são organizados em tabelas de distribuição de frequências. Para isso, os valores que a variável pode assumir são colocados na primeira coluna, em __ordem crescente__. O número de vezes que cada valor se repete (a frequência) é escrito em outra coluna, nas linhas respectivas aos valores. Mais uma vez, retorne ao exemplo da seção de orçamentos da Companhia MB. O número de filhos dos empregados da seção é apresentado a seguir na distribuição de frequências. ```{r, echo=FALSE, message=FALSE, warning=FALSE, purl=FALSE} filhos <- c(rep(0, 6), rep(1, 4), rep(2, 4), 3) filhos.tab <- as.data.frame(na.omit(summarytools::freq(filhos)))["Freq"] filhos.tab <- data.frame("filhos"= row.names(filhos.tab), "freq" = filhos.tab$Freq) knitr::kable(filhos.tab, col.names = c("Número de filhos", "Frequência ($n_i$)")) ``` ## Dados contínuos Dados contínuos podem assumir __diversos valores diferentes__^[Aqui chamamos mais uma vez a atenção para a importância de distinguirmos os diferentes tipos de variáveis. Uma variável _quantitativa contínua_ é uma __variável__! E portanto, __pode variar__ de um indivíduo para outro! No entanto, a variável _quantitativa contínua_ possui um conjunto de valores possíveis __infinito__ (um intervalo da reta real), e assim, podemos observar um número de unidades com valores distintos para uma certa variável contínua maior que no caso de uma variável nominal. __Exercício:__ compare os valores possíveis para as variáveis __altura__ e __estado civil__.], mesmo em amostras pequenas. Por essa razão, a menos que sejam em grande número, são apresentados na forma como foram coletados. Considere, como exemplo, que o pesquisador resolveu organizar as idades dos empregados da seção de orçamentos da Companhia MB em uma tabela. Pode escrever os dados na ordem em que foram coletados, como segue: ```{r, echo=FALSE, message=FALSE, warning=FALSE, purl=FALSE} idade <- c(26, 32, 36, 20, 40, 28, 41, 43, 34, 23, 33, 27, 37, 44, 30) idade.tab <- matrix(data = idade, nrow = 3) knitr::kable(idade.tab) ``` Quando em grande número, os dados contínuos podem ser organizados, para apresentação, em uma tabela de distribuição de frequências. Vamos entender como isso é feito por meio de novo exemplo. Foram propostas muitas maneiras de avaliar a capacidade de uma criança para o desempenho escolar. Algumas crianças estão "prontas" para aprender a escrever aos cinco anos, outras, aos oito anos. Imagine que um professor aplicou o _Teste de Desempenho Escolar_ (TDE) a 27 alunos da 1ª série do Ensino Fundamental. Os dados obtidos pelo professor estão apresentados em seguida. ```{r, echo=FALSE, message=FALSE, warning=FALSE, purl=FALSE} tde <- c(7, 18, 111, 25, 101, 85, 81, 75, 100, 95, 98, 108, 100, 94, 34, 99, 84, 90, 95, 102, 96, 105, 100, 107, 117, 96, 17) tde.tab <- matrix(data = tde, nrow = 3) knitr::kable(tde.tab) ``` Para __conhecer o comportamento__ do desempenho escolar desses alunos, o professor deve organizar uma __distribuição de frequências__. No entanto, para isso, é preciso __agrupar os dados em faixas__, ou __classes__^[Note que se procedermos da mesma forma que procedemos para os casos anteriores, a nossa tabela de distribuição de frequências apresentaria um grande número de valores com baixas frequências. Isso nos daria tanta informação quanto a tabela de dados brutos, e portanto, não nos ajudaria a conhecer o comportamento da variável.]. Em quantas faixas ou classes podem ser agrupados os dados? Uma __regra prática__ é a seguinte: o número de classes deve ser aproximadamente igual à raiz quadrada do tamanho da amostra. $$ \mbox{Número de classes} = \sqrt{n}. $$ No exemplo, são 27 alunos. O tamanho da amostra é, portanto, $n = 27$. A raiz quadrada de 27 está entre $5 (\sqrt{25})$ e $6 (\sqrt{36})$. Portanto, podem ser organizadas __cinco classes__. Mas como? Observe cuidadosamente o conjunto de dados. Ache o __valor mínimo__, o __valor máximo__ e a __amplitude__. - __Valor mínimo__ é o menor valor de um conjunto de dados. - __Valor máximo__ é o maior valor de um conjunto de dados. - __Amplitude__ é a diferença entre o valor máximo e o valor mínimo. Para os valores obtidos pelos 27 alunos no Teste de Desempenho Escolar, temos: - Valor mínimo $= 7$; - Valor máximo $= 117$; - Amplitude $= 117 - 7 = 110$. Uma vez obtida a amplitude do conjunto de dados, é preciso calcular a __amplitude das classes__. - __Amplitude de classe__ é dada pela divisão da amplitude do conjunto de dados pelo número de classes. Para os dados do TDE, a amplitude ($110$) deve ser dividida pelo número de classes que já foi calculado ($5$): $$ 110 \div 5 = 22. $$ A __amplitude de classe__ será, então, $22$. Isso significa que: - a primeira classe vai do valor mínimo, $7$ até $7 + 22 = 29$; - a segunda classe vai de $29$ a $29 + 22 = 51$; - a terceira classe vai de $51$ a $51 + 22 = 73$; - a quarta classe vai de $73$ a $73 + 22 = 95$; - a quinta classe vai de $95$ a $95 + 22 = 117$, inclusive. Os valores que delimitam as classes são denominados __extremos__. - __Extremos de classe__ são os valores que delimitam as classes. Uma questão importante é saber __como__ as classes devem ser escritas. Alguém pode pensar em escrever as classes como segue: \begin{eqnarray*} 7\ &-& 28\\ 29\ &-& 51, \mbox{etc.}\\ \end{eqnarray*} No entanto, essa notação traz dúvidas. Como saber, por exemplo, para qual classe vai o valor $28,5$? Esse tipo de dúvida é evitado indicando as classes como segue: \begin{eqnarray*} 7\ &\vdash& 28\\ 29\ &\vdash& 51, \mbox{etc.}\\ \end{eqnarray*} Usando essa notação, fica claro que o intervalo é __fechado__ à esquerda e __aberto__ à direita. Então, na classe $7\vdash 29$ estão __incluídos__ os valores iguais ao extremo inferior da classe, que é $7$ (o intervalo é fechado à esquerda), mas __não estão incluídos__ os valores iguais ao extremo superior da classe, que é $29$ (o intervalo é aberto à direita). A indicação de que o intervalo é fechado é dada pelo lado esquerdo do traço vertical do símbolo $\vdash$. A indicação de intervalo aberto é dada pela ausência de traço vertical no lado direito do símbolo $\vdash$. Uma alternativa a esta notação é dada por __colchetes__ e __parênteses__. Considere $ei$ e $es$ os extremos inferior e superior de uma classe qualquer, respectivamente. - "$(ei; es]$", ou "$\dashv$" é um intervalo aberto à esquerda e fechado à direita; - "$[ei; es)$", ou "$\vdash$" é um intervalo aberto à direita e fechado à esquerda; - "$(ei; es)$", ou "$]ei; es[$", ou "--" é um intervalo aberto; - "$[ei; es]$", ou "$\vdash\dashv$" é um intervalo fechado. Estabelecidas as classes, é preciso obter as __frequências__. Para isso, contam-se quantos alunos estão na classe de $7$ a $29$ (exclusive), quantos estão na classe de $29$ a $51$ (exclusive), e assim por diante^[Aqui uma abordagem poderia ser a criação de uma "nova variável" (transformada) de idade em classes na planilha de dados brutos, e então proceder com a apuração desta "nova variável" como no caso de uma variável qualitativa. Afinal de contas, as classes de idade são categorias. Neste caso, categorias de uma variável qualitativa nominal.]. A distribuição de frequências pode então ser organizada como segue. ```{r, echo=FALSE, message=FALSE, warning=FALSE, purl=FALSE} tde.cat <- cut(x = tde, breaks = c(7, 29, 51, 73, 95, 117), labels = c("7 $\\vdash$ 29", "29 $\\vdash$ 51", "51 $\\vdash$ 73", "73 $\\vdash$ 95", "95 $\\vdash$ 117"), include.lowest = F, right = FALSE) tde.tab <- as.data.frame(na.omit(summarytools::freq(tde.cat)))["Freq"] tde.tab <- data.frame("tde"= row.names(tde.tab), "freq" = tde.tab$Freq) knitr::kable(tde.tab, col.names = c("Classe TDE", "Frequência ($n_i$)")) ``` __OBSERVAÇÕES__ Embora a __regra prática__ apresentada aqui para a determinação do número de classes seja útil, ela não é a única forma de determinar classes em uma tabela de frequências para dados contínuos. O pesquisador pode especificar as classes de acordo com "convenções". É comum vermos as frequências da variável idade serem apresentadas em classes de amplitude 5 ou 10 anos. Ainda, podem ser especificadas classes com amplitudes distintas (Idade de 0 a 19 anos, 20 a 59 anos, 60 a 79 anos, 80 anos ou mais). Outro ponto importante é que nem sempre existe interesse em apresentar todas as classes possíveis. Em aluns casos, a primeira classe pode incluir todos os elementos menores que determinado valor. Diz-se, então, que o extremo inferior da primeira classe não está definido. Como exemplo, veja a distribuição de frequências das pessoas conforme a altura, com as seguintes classes: \begin{eqnarray*} && \mbox{Menos de } 150 \mbox{ cm}\\ && 150\ \vdash 160 \mbox{cm}\\ && 160\ \vdash 170 \mbox{cm, etc.}\\ \end{eqnarray*} Do mesmo modo, todos os elementos iguais ou maiores que determinado valor podem ser agrupados na última classe. Diz-se, então, que o extremo superior da última classe não está definido. Muitos dados de idade publicados pelo __Instituto Brasileiro de Geografia e Estatística__ (__IBGE__) estão em tabelas de distribuição de frequências com intervalos de classes diferentes (em relação a amplitude) e não possuem extremo superior definido. Veja o exemplo a seguir. ```{r fig-censo, fig.align='center', fig.cap = "Distribuição da população residente, segundo grupos de idade no Brasil (Censo 2010). Disponível em https://censo2010.ibge.gov.br/sinopse/index.php?dados=12.", cache=TRUE, echo=FALSE, out.width="30%", purl=FALSE} knitr::include_graphics(here::here('images', 'ibge_idade_censo2010.png')) ``` # Frequências relativa, acumulada, relativa acumula e porcentagem ## Frequência relativa É fácil entender as informações apresentadas em distribuições de frequências [A distribuição de frequências nos apresenta quantos indivíduos apresentaram determinada característica (valor da variável) no conjunto de dados que estamos observando.]. Entretanto, as frequências dependem do __tamanho da amostra:__ um em dez, é mais importante que um em um milhão. Para ter visão do tamanho de uma categoria __em relação__ ao tamanho da amostra, calculamos a frequência relativa. - __Frequência relativa__ de uma categoria é o resultado da divisão da frequência dessa categoria pelo número de dados (tamanho) da amostra. $$ \mbox{Frequência relativa} = \frac{\mbox{Frequência da categoria}}{\mbox{Tamanho da amostra}}. $$ __Observações:__ 1. Usaremos a __notação__ $f_i = \frac{n_i}{n}$ para indicar a frequência relativa de cada classe, ou categoria, da variável. 2. A soma das frequências relativas em uma distribuição de frequências é, obrigatoriamente, igual a 1^[É fácil ver que $\sum_i{f_i} = \sum_i{\frac{n_i}{n}} = \frac{1}{n}\sum_i{n_i} = \frac{1}{n}n = 1$, em que $\sum_i{}$ representa a soma (somatório).]. 3. Se a tabela de frequências absolutas estiver em uma planilha eletrônica é possível utilizar o recurso da fórmula para dividir os valores de uma coluna (as frequências) por uma constante (o tamanho da amostra) para obter as frequências relativas. No `R` a ideia é semelhante (veja a Seção Complementa`R`). ## Porcentagem - __Porcentagem da categoria__ é a frequência relativa dessa categoria multiplicada por 100. $$ \mbox{Porcentagem} = \mbox{Frequência relativa} \times 100. $$ Porcentagem é a razão expressa como fração de 100. Você não deve confundir __porcentagem__ com __por cento__. __Porcentagem__ significa uma parcela ou uma porção; não é, portanto, acompanhada de número. Por exemplo: a porcentagem de alunos reprovados em matemática foi pequena. __Por cento__ é a expressão que acompanha um número específico e é indicado com o símbolo %. Por exemplo: só 2% dos alunos foram reprovados em matemática. Vamos ver como calcular as frequências relativas e a porcentagem para o exemplo dos empregados da seção de orçamentos da Companhia MB. ```{r, echo=FALSE, message=FALSE, warning=FALSE, purl=FALSE} civil <- c(rep("Solteiro", 8), rep("Casado", 7)) civil.tab <- as.data.frame(na.omit(summarytools::freq(civil, order = "freq")))["Freq"] civil.tab <- data.frame("estado_civil"= row.names(civil.tab), "freq" = civil.tab$Freq) civil.tab$freqrel <- c("$\\frac{8}{15} = 0,533$", "$\\frac{7}{15} = 0,467$", "1,000") civil.tab$porc <- c("$0,533 \\times 100 = 53,3\\%$", "$0,467 \\times 100 = 46,7\\%$", "100,0\\%") knitr::kable(civil.tab, col.names = c("Estado civil", "Frequência ($n_i$)", "Frequência relativa ($f_i$)", "Porcentagem"), align = c('l', 'c', 'c', 'c')) ``` __Observação:__ as frequências relativas, e as porcentagens, de forma mais convencional, nos permitem fazer comparações entre grupos.Por exemplo, 30% dos alunos da Turma A preferem consultar o arquivo das notas de aula no formato PDF, enquanto que 50% dos alunos da Turma B preferem consultar o as notas de aula no formato PDF. ## Frequência acumulada - __Frequência acumulada__ da categoria é a frequência dessa categoria somada às frequências de todas as anteriores. Mais uma vez retomamos o exemplo da Companhia MB para apresentarmos como é calculada a frequência acumulada. ```{r, echo=FALSE, message=FALSE, warning=FALSE, purl=FALSE} filhos <- c(rep(0, 6), rep(1, 4), rep(2, 4), 3) filhos.tab <- as.data.frame(na.omit(summarytools::freq(filhos)))["Freq"] filhos.tab <- data.frame("filhos"= row.names(filhos.tab), "freq" = filhos.tab$Freq) filhos.tab$freqcum <- c("6", "$6 + 4 = 10$", "$6 + 4 + 4 = 14$", "$6 + 4 + 4 + 1= 15$", "-") knitr::kable(filhos.tab, col.names = c("Nº de filhos", "Frequência ($n_i$)", "Frequência acumulada"), align = c('l', 'c', 'c')) ``` Assim, é possível concluir que 14 empregados da seção de orçamento tem __2 filhos ou menos__ (até dois filhos). __Observações:__ 1. A frequência acumulada é apropriada para variáveis qualitativas ordinais, quantitativas discretas e contínuas. No entanto, não faz sentido apresentar a frequência acumulada de uma variável qualitativa nominal. 2. A frequência acumulada da primeira classe é sempre igual à frequência dessa classe, por não existem classes anteriores à primeira. 3. A última classe tem frequência acumulada igual ao total porque, para obter a frequência acumulada da última classe, somam-se as frequências de todas as outras classes. 4. Se a tabela de frequências absolutas estiver em uma planilha eletrônica é possível utilizar o recurso da fórmula para somar recursivamente os valores de uma coluna (as frequências) para obter as frequências acumuladas. No `R` a ideia é semelhante (veja a Seção Complementa`R`). ## Frequência relativa acumulada - __Frequência relativa acumulada__ da categoria é a frequência relativa dessa categoria somada às frequências relativas de todas as anteriores. No exemplo da Companhia MB, temos: ```{r, echo=FALSE, message=FALSE, warning=FALSE, purl=FALSE} options(knitr.kable.NA = '-') filhos <- c(rep(0, 6), rep(1, 4), rep(2, 4), 3) filhos.tab <- as.data.frame(na.omit(summarytools::freq(filhos)))["Freq"] filhos.tab <- data.frame("filhos"= row.names(filhos.tab), "freq" = filhos.tab$Freq) filhos.tab$freqrel <- filhos.tab$freq/15 filhos.tab$freqrelcum <- c(cumsum(filhos.tab$freqrel[-length(filhos.tab$freqrel)]), NA) knitr::kable(filhos.tab, col.names = c("Nº de filhos", "Frequência ($n_i$)", "Freq. relativa ($f_i$)", "Freq. relativa acumulada"), align = c('l', 'c', 'c', 'c'), digits = 3, ) ``` E assim, é possível concluir que 93% dos empregados da seção de orçamento tem __2 filhos ou menos__ (até dois filhos)^[__Exercício:__ qual a porcentagem de empregados da seção de orçamentos com mais de um filho?]. # Exercícios Faça uma pequena coleta de dados incluindo pelo menos uma variável de cada tipo (_qualitativa nominal_, _qualitativa ordinal_, _quantitativa discreta_ e _quantitativa contínua_). 1. Organize uma planilha (física ou eletrônica) para o registro dos dados coletados. 2. Faça a coleta e preencha a planilha para obter os dados brutos. 3. Faça a apuração dos dados. 4. Construa tabelas de frequências para cada uma das variáveis e comente brevemente sobre os resultados encontrados. 5. Faça os exercícios da Lista de Exercícios I (disponível no Moodle). # Complementa`R` Esta seção é complementar. São apresentadas algumas poucas funções em `R` relacionadas a discussão da aula. Para tal, vamos utilizar o exemplo original de [@morettin_estatistica_2017] sobre os dados dos empregados da seção de orçamentos da Companhia MB. A planilha eletrônica correspondente encontra-se no arquivo `companhia_mb.xlsx`. Vamos começar carregando os dados para o `R`. Existem várias formas de se carregar __arquivos de dados__ em diferentes no `R`. Como arquivo de interesse encontra-se no formato do Excel (xlsx), vamos utilizar a função `read_excel` do pacote `readxl`^[Caso você não tenha o pacote, instale-o:`install.packages("readxl")`.]. ```{r carrega-dados0, echo=TRUE, eval=FALSE, warning=FALSE, message=FALSE} # install.packages("readxl") library(readxl) dados <- read_excel(path = "companhia_mb.xlsx") ``` ```{r carrega-dados1, echo=FALSE, warning=FALSE, message=FALSE, purl=FALSE} # install.packages("readxl") library(readxl) dados <- read_excel(path = here::here("data", "companhia_mb.xlsx")) ``` ```{r carrega-dados2, warning=FALSE, message=FALSE} class(dados) # classe do objeto dados dim(dados) # dimensão do objeto dados ``` Note que o objeto `dados` é uma tabela de dados bruto. ```{r carrega-dados3, warning=FALSE, message=FALSE} head(dados) # apresenta as primeiras linhas do objeto dados ``` A função `table` retorna contagens dos valores de cada variável, e portanto, podemos utilizar esta função para a apuração dos dados, bem como para computar as frequências. ```{r freqs, warning=FALSE, message=FALSE} table(dados$`Estado Civil`) table(dados$`Grau de Instrução`) table(dados$`N de Filhos`) ``` A função `cut` pode ser utilizada para criar uma nova variável que expressa a antiga variável em classes. ```{r freqs2, warning=FALSE, message=FALSE} dados$Idade.classes <- cut(x = dados$Idade, breaks = c(20, 29, 39, 49), include.lowest = TRUE, right = FALSE) table(dados$Idade.classes) ``` Uma forma de calcular as frequência relativas é dividindo o `vetor` de frequências pelo tamanho da amostra (ou conjunto de dados). ```{r freqs3, warning=FALSE, message=FALSE} table(dados$`Estado Civil`) / 36 table(dados$`Grau de Instrução`) / length(dados$`Grau de Instrução`) ``` Uma outra forma de se obter as frequências relativas é utilizando a função `prop.table`. ```{r freqs4, warning=FALSE, message=FALSE} prop.table(x = table(dados$`N de Filhos`)) ``` Para obter as porcentagens, basta multiplicar as frequências relativas por 100. ```{r porcentagem, warning=FALSE, message=FALSE} prop.table(x = table(dados$Idade.classes)) * 100 ``` Se você quiser, pode arredondar os resultados com a função `round`. ```{r porcentagem2, warning=FALSE, message=FALSE} round(x = prop.table(x = table(dados$Idade.classes)) * 100, digits = 2) ``` As frequências acumuladas podem ser obtidas com uma função de somas cumulativas, a função `cumsum`. ```{r freqcum, warning=FALSE, message=FALSE} cumsum(x = table(dados$`Grau de Instrução`)) cumsum(x = prop.table(x = table(dados$`Grau de Instrução`))) cumsum(x = prop.table(x = table(dados$`N de Filhos`)) * 100) cumsum(round(x = prop.table(x = table(dados$Idade.classes)) * 100, digits = 2)) ``` Você pode juntar as frequências absolutas, relativas, acumuladas e porcentagens em `data.frame` para apresentar em forma de tabela. ```{r freqtab, warning=FALSE, message=FALSE} df.freq <- data.frame(Idade = unique(dados$Idade.classes), Freq = as.numeric(table(dados$Idade.classes)), FreqRel = as.numeric(prop.table(table(dados$Idade.classes))), Porcentagem = as.numeric(prop.table(table(dados$Idade.classes)) * 100), FreqAcumulada = as.numeric(cumsum(table(dados$Idade.classes))), FreqRelAcumulada = as.numeric(cumsum(prop.table(table(dados$Idade.classes))))) df.freq ``` Existem outras formas de construir uma tabela de frequências. Uma delas é utilizando a função `freq` do pacote `summarytools`. ```{r freqtab2, warning=FALSE, message=FALSE} # install.packages("summarytools") summarytools::freq(dados$`Grau de Instrução`) ```<file_sep>--- title: "MAT02018 - Estatística Descritiva" subtitle: "Conceitos Básicos" fontsize: 10pt author: | | <NAME> | `<EMAIL>` institute: | | \textsc{Universidade Federal do Rio Grande do Sul} | \textsc{Instituto de Matemática e Estatística} | \textsc{Departamento de Estatística} date: | | Porto Alegre, 2022 --- # Conceitos básicos ## Dados e variáveis {.allowframebreaks} ::: {.block} ### Dados São as informações obtidas de uma unidade experimental ou observacional. ::: - __Ex:__ "Vitor tem 25 anos e é fumante". Os dados são "25 anos" e "fumante". \framebreak ::: {.block} ### Variável É toda característica que, observada em uma unidade (experimental ou observacional), pode variar de um indivíduo para outro. ::: - __Ex:__ idade, sexo, altura, nível de hemoglobina no sangue, espaçamento entre plantas, doses de um medicamento, tipo de medicamento, cultivares, número de caracteres, velocidade da rede, tempo gasto na rede social, nível de monóxido de carbono em emissões do escape de automóveis, etc. ## Tipos de variáveis \footnotesize - É importante __identificar que tipo de variável__ está sendo estudada, uma vez que são recomendados __procedimentos estatísticos diferentes__ em cada situação. ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='80%', out.height='70%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'classe_var.png')) ``` ## Variáveis quantitativas \footnotesize - A __variável quantitativa__ é expressa por números. ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='90%', out.height='80%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'var_quanti.png')) ``` ## Variáveis quantitativas discretas \footnotesize - A __variável discreta__ resulta do processo de contagem. ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='60%', out.height='80%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'var_discreta.jpg')) ``` ## Variáveis quantitativas contínuas \footnotesize - A __variável contínua__ resulta do processo de medição. ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='70%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'var_continua.jpg')) ``` ## Variáveis qualitativas \footnotesize - A __variável quantitativa__ é expressa por palavras. ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='100%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'var_quali.png')) ``` ## Variáveis qualitativas ordinais \footnotesize - A __variável ordinal__ tem duas ou mais categorias que são, necessariamente, organizadas segundo uma lógica. ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='100%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'var_ordinal.jpg')) ``` ## Variáveis qualitativas nominais \footnotesize - A __variável nominal__ tem duas ou mais categorias, que podem ser apresentadas em qualquer ordem. ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='70%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'var_nominal.jpg')) ``` ## Exemplos (1) ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='90%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'cor_predio2.jpg')) ``` ## Exemplos (1) ### Variáveis quantitativas - 3 andares - 14,85 metros de altura ### Variáveis qualitativas - Multicolorido - Cheira "bem" ## Exemplos (2) ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='90%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'rolling-stones.jpg')) ``` ## Exemplos (2) ### Variáveis quantitativas - 4 integrantes - 60 anos ### Variáveis qualitativas - Inglaterra - Rock ## População {.allowframebreaks} ::: {.block} ### População ou universo Esse termo é usado em estatística com um sentido bem mais amplo do que na linguagem coloquial. É entendido aqui como o __conjunto de todos os elementos__ que apresentam uma ou mais características __em comum__. ::: - __Exemplo 1:__ a população de colegiais de oito anos de Belo Horizonte. + Estes colegiais têm em comum a idade e o local onde vivem. - __Exemplo 2:__ a população de indústrias brasileiras. + Estas indústrias têm em comum o fato de que foram criadas no Brasil. \framebreak - Este conjunto por vezes é denominado por $U$ (de __conjunto universo__). - O __tamanho da população__ é a sua quantidade de elementos, que anotamos por $N$. - Uma população pode ser __finita__ (limita em tamanho; $N < \infty$) ou __infinita__ ($N =\infty$). + __Exemplo de pop. finita:__ torcedores do São Raimundo de Santarém, residentes de Porto Alegre. + __Exemplo de pop. infinita:__ equipamentos (de um certo tipo) fabricados em série. ## Censo e amostra {.allowframebreaks} - Quando o estudo é realizado com toda a população de interesse, chamemos este estudo de __censo__. - Por motivos de tempo, custo, logística, entre outros, geralmente não é possível realizar um censo. + Nestes casos, estudamos apenas uma parcela da população, que chamamos de __amostra__. \framebreak ### Censo vs. amostra À primeira vista, uma coleta de dados realizada em toda a população é preferível a uma realizada apenas numa parte da população. Na prática, entretanto, o oposto é frequentemente verdadeiro porque: 1. Um censo é impossível quando a população é infinita. 2. Os ensaios (testes) podem ser destrutivos \structure{(como nos testes de segurança dos carros)}. 3. Rapidez: estudar toda a população pode despender de muito tempo, não sendo compatível com a urgência do estudo \structure{(como quando estudamos os casos de um surto de uma nova doença)}. Para uma consideração mais completa ver Vargas (2000)\footnote{<NAME>. \emph{Estatística: uma linguagem para dialogar com a incerteza}, Cadernos de matemática e estatística. Série B, 2000.}. ## Amostra ::: {.block} ### Amostra É qualquer fração de uma população. ::: - Como sua finalidade é representar a população, deseja-se que a amostra escolhida apresente as mesmas características da população de origem, isto é, que seja uma amostra __"representativa"__ ou __"não-tendenciosa"__. - Tanto o número de indivíduos selecionados para a amostra quanto a técnica de seleção são extremamente importantes para que os resultados obtidos no estudo sejam generalizados para a população. ## Amostra representativa ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='65%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'Gato_caindo.jpg')) ``` - Ver a discussão sobre __representatividade da amostra__ na [apresentação](https://www.youtube.com/watch?v=TGGGDpb04Yc&t=592s) do __Prof. <NAME>__. ## Amostragem - A seleção da amostra pode ser feita de várias maneiras. - Esta dependerá: + Do grau de conhecimento que temos da população. + Da quantidade de recursos disponíveis. - A seleção da amostra tenta fornecer um subconjunto de valores o __mais parecido possível__ com a população que lhe dá origem. + __Amostra representativa__ da população. ## Amostra aleatória simples - A amostragem mais usada é a __amostra casual simples__ (ou aleatória simples). + Os indivíduos (unidades) da amostra são selecionados ao acaso, __com__ ou __sem reposição__. ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='60%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'simpleSample.png')) ``` ## Amostra estratificada - Eventualmente, se tivermos informações adicionais a respeito da população de interesse, podemos utilizar outros esquemas de amostragem mais sofisticados. + __Amostragem estratificada__ ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='95%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'estratificada.png')) ``` ## Amostra sistemática - Em outros casos, pode existir uma relação numerada dos itens da população que nos permitiria utilizar a chamada __amostragem sistemática__ em que selecionamos os indivíduos de forma pré-determinada. ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='80%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'SystematicSampling.jpg')) ``` ## Amostragem - Outros esquemas de amostragem poderiam ser citados e todos fazem parte da chamada __teoria da amostragem__, cujos detalhes não serão aprofundados. ## Parâmetros, estatísticas e estimativas {.allowframebreaks} ::: {.block} ### Parâmetro É um valor que resume, na população, a informação relativa a uma variável. ::: - __Ex:__ média populacional, prevalência populacional, coeficiente de variação populacional, taxa de mortalidade populacional, etc. ::: {.block} ### Estatística (além de ser o nome da ciência/área do conhecimento) é a denominação dada a uma quantidade, calculada com base nos elementos de uma amostra, que descreve a informação contida nesse conjunto de dados. ::: - __Ex:__ A média, a porcentagem, o desvio padrão, o coeficiente de correlação, calculados em uma amostra, são estatísticas. ## Parâmetros, estatísticas e estimativas - Os parâmetros são difíceis de se obter, pois implicam o estudo de toda a população e costumam ser substituídos por valores calculados em amostras representativas da população-alvo. + Se tivesse sido examinada uma amostra de 10 estudantes matriculados na disciplina MAT02218, e 40% fossem de torcedores do América Mineiro, esse valor constituiria uma estimativa do parâmetro "percentual de torcedores do América Mineiro matriculados naquela disciplina". \framebreak ::: {.block} ### Estimativa É um valor numérico de uma estatística, usado para realizar inferências sobre o parâmetro. ::: - Da mesma forma, o valor numérico da média para a estatura desses 10 alunos, digamos 173 cm, é uma estimativa para a média de altura populacional. - __P:__ neste exemplo, quem é a população (alvo)? ## Para casa <!-- 1. Com base na \structure{questão de pesquisa} elaborada no "para casa" anterior: --> <!-- - Liste as variáveis que você teria interesse em coletar e analisar para responder a sua questão de pesquisa. --> <!-- - Classifique as variáveis de acordo com a classificação discutida na aula de hoje. --> <!-- - Discuta a respeito das suas variáveis com os colegas \structure{(no Fórum Geral do Moodle)}. --> <!-- 2. Leia o \structure{Capítulo 3 - ``Fases do levantamento estatístico''} do livro \structure{Estatística descritiva I}\footnote{<NAME>. {\bf Estatística descritiva I}, Cadernos de matemática e estatística. Série B, 1994.}. --> - Assistir o vídeo: \structure{Statistical Thinking for Data Science} (no Moodle ou em <https://youtu.be/TGGGDpb04Yc>; você pode configurar o vídeo para apresentar legendas traduzidas para o português). + Leia a notícia sobre **quedas de gatos** na íntegra (Moodle). ## Próxima aula - Fases do levantamento estatístico. ## Por hoje é só! \begin{center} {\bf Bons estudos!} \end{center} ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='50%', out.height='50%', paged.print=FALSE} knitr::include_graphics(here::here('images', 'Statistically-Insignificant-pizza.jpg')) ``` <file_sep>--- title: "MAT02018 - Estatística Descritiva" subtitle: "Introdução à Estatística" fontsize: 10pt author: | | <NAME> | `<EMAIL>` institute: | | \textsc{Universidade Federal do Rio Grande do Sul} | \textsc{Instituto de Matemática e Estatística} | \textsc{Departamento de Estatística} date: | | Porto Alegre, 2022 --- # Introdução ## Dados $\leadsto$ Conhecimento ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='100%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'dicing_with_death.jpg')) ``` ## Dados $\leadsto$ Conhecimento - Em alguma fase de seu trabalho, o pesquisador depara-se com o problema de __analisar__ e __entender__ um __conjunto de dados__ relevante ao seu particular objeto de estudos. - Ele necessitará trabalhar os dados para __transformá-los em informações__, para compará-los com outros resultados, ou ainda para __julgar sua adequação__ a __alguma teoria__. <!-- ## Dados $\leadsto$ Conhecimento --> <!-- ### Uma representação --> <!-- ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='100%', out.height='80%', paged.print=FALSE, purl=FALSE} --> <!-- library(cowplot) --> <!-- library(ggplot2) --> <!-- p1 <- ggdraw() + draw_image(here::here('images', 'model.jpg'), scale = 0.9) --> <!-- p2 <- ggdraw() + draw_image(here::here('images', 'decisionloops2.jpg'), scale = 0.9) --> <!-- plot_grid(p1, p2) --> <!-- ``` --> <!-- ## Dados $\leadsto$ Conhecimento --> <!-- ### Uma representação mais ousada! --> <!-- ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='100%', paged.print=FALSE, purl=FALSE} --> <!-- knitr::include_graphics(here::here('images', 'Data-Wisdom.jpg')) --> <!-- ``` --> ## O Método Científico {.allowframebreaks} - De modo bem geral, podemos dizer que a essência da Ciência é a __observação__ e que seu objetivo básico é a __inferência__. - Os cientistas (sociais ou físicos) geralmente fazem uso do \structure{método científico} nas suas tentativas de compreender o mundo. ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='60%', out.height='60%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'metodo.png')) ``` \framebreak Suponha que estamos interessados em descrever e explicar o __padrão dos casos de câncer__ em uma área metropolitana. 1. Observação/registro dos casos; 2. Descrição do padrão por meio da apresentação dos casos em um mapa. ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='50%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'mapa_casos.jpg')) ``` \framebreak 3. O que explica o resultado observado? ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='50%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'mapa_clusters.jpg')) ``` 4. Formulação de hipóteses/modelos explicativos. \framebreak (Exemplo) *Hipótese:* o padrão de casos de câncer está relacionado à distância das usinas de energia locais. ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='50%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'cancer_distancia.png')) ``` 5. Os dados fornecem evidências para avaliarmos as hipóteses formuladas. 6. A partir desta avaliação, modelos e hipóteses podem ser reconsiderados, ou conclusões teóricas podem ser elaboradas. \framebreak - Os métodos estatísticos ocupam um papel central no método científico, como visto no exemplo dos casos de câncer, pois nos permitem __sugerir__ e __testar__ hipóteses. <!-- ## O Método Científico --> <!-- - De modo bem geral, podemos dizer que a essência do Aprendizado (da Evolução). --> <!-- ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='50%', out.height='70%', paged.print=FALSE, purl=FALSE} --> <!-- knitr::include_graphics(here::here('images', 'metodo_cientifico_bebes.png')) --> <!-- ``` --> # A Estatística ## O que é Estatística? - Essa pergunta já vem sendo feita (e diversas vezes) há muito tempo. - A persistência da pergunta e a variedade das respostas durante os anos sugerem que a Estatística não se caracteriza como um objeto singular. - Ainda, a Estatística apresenta diferentes faces para diferentes áreas da ciência. ## Uma perspectiva histórica - A Estatística mudou drasticamente desde os primeiros dias até o presente, passando de uma profissão que reivindicou uma objetividade extrema que os estatísticos apenas coletariam dados (e não os analisam) para uma profissão que busca parceria com cientistas em todas as etapas da investigação, do planejamento à análise. - Primeiros censos ocorrem por volta do ano zero da era cristã. + Por muito tempo, o aspecto descritivo da Estatística manteve-se como a única faceta desta ciência . - No século XVII, ocorrem as primeiras interpretações de dados. + Em 1693, foram publicados pela primeira vez, em Londres, os totais anuais de falecimentos, estratificados por sexo. + Primeiros estudos formais da teoria das probabilidades. ## Uma perspectiva histórica __Pascal-Fermat (Séc. XVII)__ ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='100%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'pascal-fermat-mail-2.jpg')) ``` ## Uma perspectiva histórica __<NAME> (Séc. XIX)__ ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='100%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'florence-chart-2.jpg')) ``` ## Uma perspectiva histórica __Galton-Pearson (Séc. XIX e XX)__ ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='100%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'pearson-galton.jpg')) ``` ## Uma perspectiva histórica __<NAME>, o _Student_ (Séc. XX)__ ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='100%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'gosset-2.jpg')) ``` ## Uma perspectiva histórica __<NAME> (Séc. XX)__ ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='100%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'Fisher-2.jpg')) ``` ## Uma perspectiva histórica \begin{center} {\bf Essa história continua!} Para saber mais, veja: \end{center} ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='100%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'livros-hist.jpg')) ``` ## O papel da estatística na pesquisa - No \structure{planejamento}, auxilia na escolha de situações experimentais e na determinação da quantidade de indivíduos a serem examinados. - Na \structure{análise}, indica técnicas para resumir e apresentar as informações, bem como para comparar as situações experimentais. - Na \structure{elaboração das conclusões}, os vários métodos estatísticos permitem generalizar a partir dos resultados obtidos. - De modo geral, não existe certeza sobre a correção das conclusões científicas; no entanto, os métodos estatísticos permitem determinar a margem de erro associada às conclusões, com base no conhecimento da variabilidade observada nos resultados. ## O que é a estatística? - A __estatística__\footnote{Do grego \emph{statistós}, de \emph{statízo}, \textbf{``estabelecer''}, \textbf{``verificar''}, acrescido do sufixo \emph{ica}.} é a ciência que tem por objetivo orientar a coleta, o resumo, a apresentação, a análise e a interpretação de dados. - Podem ser identificadas duas grandes áreas de atuação desta ciência: + a __estatística descritiva__, envolvida com o resumo e a apresentação dos dados. + a __estatística inferencial__, que ajuda a concluir sobre conjuntos maiores de dados (populações) quando apenas partes desses conjuntos (as amostras) foram estudadas. <!-- - Mais do que uma sequência de métodos, a estatística é uma forma de pensar ou de ver a realidade variável, já que seu conhecimento não apenas fornece um conjunto de técnicas de análise de dados, mas condiciona toda uma postura crítica sobre sua interpretação e a elaboração de conclusões sobre os dados. --> ## O que é a estatística? ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='100%', out.height='80%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'Descritiva_Inferencia.png')) ``` # A Estatística Descritiva ## O que é a estatística descritiva? - A __Estatística Descritiva__ corresponde aos procedimentos relacionados com a \structure{coleta}, \structure{elaboração}, \structure{tabulação}, \structure{análise}, \structure{interpretação} e \structure{apresentação} dos \structure{dados}. - Isto é, inclui as técnicas que dizem respeito à sintetização e à descrição de dados numéricos. - Estas técnicas podem ser utilizadas em pelo menos dois contextos + Análise da \structure{consistência dos dados}. + \structure{Análise Exploratória de Dados} (_Exploratory Data Analysis_ - EDA)\footnote{<NAME>. \emph{Exploratory data analysis}, Reading:Addison-Wesley, 1977.}. - Tais métodos tanto podem ser gráficos como envolver análise computacional. ## Alguns exemplos \footnotesize Descriptive Statistics tobacco **N:** 1000 ```{r echo=FALSE, message=FALSE, warning=FALSE, purl=FALSE, results='asis'} library(summarytools) descr(tobacco, style = 'rmarkdown', headings = F) ``` ## Alguns exemplos ```{r echo=FALSE, message=FALSE, warning=FALSE, purl=FALSE, results='asis'} freq(tobacco$gender, style = 'rmarkdown', headings = F) ``` ## Alguns exemplos ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='95%', paged.print=FALSE} # Considerações finais: exemplos # install.packages("jpeg") # install.packages("grid") library(jpeg) library(grid) library(gapminder) library(dplyr) library(ggplot2) gapminder <- gapminder %>% mutate(pop_m = pop/1e6) gapminder07 <- gapminder %>% filter(year == 2007) img <- readJPEG(here::here("images", "hans_rosling.jpg")) # start plotting p <- ggplot(data = gapminder07, mapping = aes(x = gdpPercap, y = lifeExp, color = continent, size = pop_m)) + annotation_custom(rasterGrob(img, width = unit(1, "npc"), height = unit(1, "npc")), -Inf, Inf, -Inf, Inf) + scale_y_continuous(expand = c(0,0), limits = c(min(gapminder07$lifeExp) * 0.9, max(gapminder07$lifeExp) * 1.05)) + geom_point() + labs(x = "Renda per capita (US$)", y = "Expectativa de vida (anos)", color = "Continente", size = "População/1 milhão") + theme_bw() + theme(text = element_text(color = "gray20"), legend.position = c("top"), # posição da legenda legend.direction = "horizontal", legend.justification = 0.1, # ponto de ancora para legend.position. legend.text = element_text(size = 11, color = "gray10"), axis.text = element_text(face = "italic"), axis.title.x = element_text(vjust = -1), axis.title.y = element_text(vjust = 2), axis.ticks.y = element_blank(), # element_blank() é como removemos elementos axis.line = element_line(color = "gray40", size = 0.5), axis.line.y = element_blank(), panel.grid.major = element_line(color = "gray50", size = 0.5), panel.grid.major.x = element_blank() ) p ``` # Conceitos básicos: introdução aos delineamentos de estudos ## Unidades experimentais e observacionais - __Unidade experimental__ ou __unidade de observação__ é a menor unidade a fornecer informação. + __Ex:__ alunos, pacientes, animais, plantas, carros, hospitais, escolas, cidades, universidades, países, _tweets_, etc. ### Crash course de inferência causal __Qual o melhor tratamento para o choque séptico?__ Dois tipos de estudo podem ser conduzidos para responder a esta questão de pesquisa: 1. Em um \structure{experimento aleatorizado} (_randomized trial_), uma moeda justa é lançada repetidamente para designar o tratamento de cada paciente. 2. Um \structure{estudo observacional} é uma investigação empírica em que o objetivo é elucidar relações de causa e efeito, em que não é factível o uso de experimentação controlada, no sentido de ser capaz de impor procedimentos ou tratamentos cujos os efeitos se deseja descobrir. ## Experimentos: exemplo - "O chá servido sobre o leite parecia ficar com gosto diferente do que apresentava ao receber o leite sobre ele"\footnote{Salsburg, D. \emph{Uma senhora toma chá $\ldots$ como a estatística revolucionou a ciência no século XX}, Zahar, 2009.}. ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='70%', out.height='60%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'uma_senhora_toma_cha.jpg')) ``` ## Estudos observacionais: exemplo - "O __Ministério da Saúde__ adverte: __fumar pode causar câncer de pulmão__”\footnote{Salsburg, D. \emph{Uma senhora toma chá $\ldots$ como a estatística revolucionou a ciência no século XX}, Zahar, 2009.}. ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='70%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'smokingAndLungCancer2.jpg')) ``` ## Para casa - Ler o capítulo 1 do livro _"Uma Senhora Toma Chá"_ \structure{(Moodle)}. <!-- 1. Elabore uma questão de pesquisa de seu interesse (como você imagine ser possível de responder através da coleta/organização/análise de dados). --> <!-- 2. Apresente a sua questão no Fórum Geral do Moodle. --> <!-- 3. Discuta a respeito da sua questão de pesquisa com os colegas. Discuta as questões apresentadas pelos colegas. --> ## Próxima aula - Introdução e conceitos básicos de Estatística (continuação). ## Por hoje é só! \begin{center} {\bf Bons estudos!} \end{center} ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='50%', out.height='50%', paged.print=FALSE} knitr::include_graphics(here::here('images', 'Statistically-Insignificant-ff.jpg')) ``` <file_sep>--- title: "MAT02018 - Estatística Descritiva" subtitle: "Distribuições bidimensionais" fontsize: 10pt author: | | <NAME> | `<EMAIL>` institute: | | \textsc{Universidade Federal do Rio Grande do Sul} | \textsc{Instituto de Matemática e Estatística} | \textsc{Departamento de Estatística} date: | | Porto Alegre, 2021 bibliography: estatistica-descritiva.bib csl: associacao-brasileira-de-normas-tecnicas-ufrgs-initials.csl link-citations: yes header-includes: - \titlegraphic{\hfill\includegraphics[height=1.5cm]{logos/Logo-40-anos-estatistica.png}} --- ```{r setup, include=FALSE, purl=FALSE} options(knitr.kable.NA = '-') library(dplyr) library(knitr) ``` # Apresentação {.allowframebreaks} - Até o presente momento vimos como organizar, resumir e apresentar informações referentes a uma única variável. - Muito do interesse em se coletar diversas variáveis em um levantamento estatístico está em analisar o __comportamento conjunto__ de duas ou mais variáveis. - Algumas questões de pesquisa, relacionadas a este objetivo, que podem ser listadas: - As variáveis estão relacionadas (associadas, correlacionadas)? - Como caraterizar esta realação? - Qual a força desta relação? \framebreak - Nestas breves notas de aula vamos apresentar formas de organização e apresentação de distribuições bidimensionais^[Distribuições de duas variáveis. Nestas notas de aula nos concentraremos no caso de duas variáveis, mas tais ideias podem ser generalizados para o caso de mais duas variáveis.] de frequências, assim como o cálculo e interpretação de medidas resumo. # Introdução {.allowframebreaks} - Quando consideramos duas variáveis^[Ou ainda, dois grupos em que as mesmas variáveis foram mensuradas, formando dois conjuntos de dados. Exemplo: a atividade física é mensurada (por algum instrumento de medida: questionário de hábitos de vida; acelerômetro) em dois grupos de indivíduos: fumantes e não-fumantes.], podemos ter três situações: - As duas variáveis são qualitativas; - As duas variáveis são quantitativas; - Uma variável é qualitativa e outra é quantitativa. ## Introdução {.allowframebreaks} - As técnicas de análise de dados nas três situações são diferentes. - Quando as variáveis são qualitativas, os dados são resumidos e apresentados em __tabelas de dupla entrada__^[Também conhecidas como __tabelas de contingência__.]. - Quando as duas variáveis são quantitativas __gráficos de dispersão__ são apropriados. - Quando temos uma variável qualitativa e outra quantitativa, em geral, analisamos o que acontece com a variável quantitativa agrupadas em classes^[Ou seja, a variável qualitativa é interpretada como uma variável de grupo de observações.]. ## Introdução {.allowframebreaks} - Contudo, em todas as situações, o objetivo é encontrar as possíveis relações (associações) entre as duas variáveis. - Essas relações podem ser detectadas por meio de métodos gráficos e medidas resumo. - Interpretaremos a existência de associação como uma "_mudança_" de opinião sobre o comportamento de uma variável na presença de informação sobre a segunda variável. - Exemplificando, os clientes de um serviço de __Streaming__ têm a __comédia__ como gênero preferido de filme. + Se estratificamos os clientes entre _jovens_ e _idosos_, esta preferência se mantém a mesma nos dois grupos? + Se a preferência por gênero de filme muda entre as faixas etárias, então temos uma associação entre as variáveis idade e gênero de filme. + Tal informação pode ser utilizada para a definição de campanhas de _marketing_ específicas para cada faixa etária, com sugestões "mais precisas". # Variáveis qualitativas {.allowframebreaks} - Considere como exemplo o conjunto de dados coletados de empregados da seção de orçamentos da Companhia MB [@bussab_estatistica_2017]. Suponha que queiramos analisar o comportamento conjunto das variáveis _grau de instrução_ e _região de procedência_. \footnotesize ```{r mb, echo=FALSE, warning=FALSE, message=FALSE} library(dplyr) library(readxl) library(knitr) mb_df <- read_excel(path = here::here("data", "companhia_mb.xlsx")) mb_df %>% select(N ,`Região de Procedência`, `Grau de Instrução`) %>% rename("ID" = "N") %>% # slice_head(n = 10) %>% kable(caption = "Tabela de dados brutos.", format = "pandoc") ``` \framebreak \normalsize - A __distribuição conjunta de frequências__ é apresentada logo a seguir, na tabela de dupla entrada: \footnotesize ```{r tab_dupla, echo=FALSE, warning=FALSE, message=FALSE} library(kableExtra) tab <- mb_df %>% select(`Região de Procedência`, `Grau de Instrução`) %>% table() %>% addmargins() row.names(tab)[4] <- "Total" colnames(tab)[4] <- "Total" kable(tab, caption = "Distribuição conjunta das frequências das variáveis grau de instrução e região de procedência.") %>% add_header_above(c("Região de Procedência", "Grau de Instrução" = 3, " ")) ``` \normalsize \framebreak - Note que cada elemento do corpo da tabela fornece a frequência observada das realizações simultâneas de _Região de Procedência_ ($V$) e _Grau de Instrução_ ($Y$). - Assim, observamos quatro indivíduos da capital com ensino fundamental, sete do interior com ensino médio, etc. - A linha dos totais fornece a distribuição (unidimensional) da variável _Grau de Instrução_, ao passo que a coluna dos totais fornece a distribuição da variável _Região de Procedência_. - As distribuições assim obtidas são chamadas tecnicamente de __distribuições marginais__, enquanto a tabela acima constitui a __distribuição conjunta__ de $Y$ e $V$^[Podemos concluir que a partir da distribuição conjunta das variáveis é possível obter as distribuições marginais de cada uma das variáveis, somando os elementos da linha, ou da coluna. Por outro lado, não é possível obter a distribuição conjunta a partir das distribuições marginais.]. ## Variáveis qualitativas {.allowframebreaks} - Assim como no caso unidimensional, podemos ter interesse não só em frequências absolutas, mas também em frequências relativas e porcentagens. - Mas aqui existem três possibilidades de expressarmos a proporção de cada casela: - Em relação ao total geral; - Em relação ao total de cada linha; - Em relação ao total de cada coluna. - De acordo com o objetivo do problema em estudo, uma delas será a mais conveniente. \framebreak - A tabela a seguir apresenta a distribuição conjunta das frequências relativas, expressas como proporções do total geral. - Ou seja, cada elemento da tabela abaixo é obtido pela divisão da frequência absoluta (apresenta na tabela anterior) pelo total de observações, $n = 36$ (e multiplicação por $100$). \footnotesize ```{r percent_tot_geral, echo=FALSE, warning=FALSE, message=FALSE} prop.tab <- mb_df %>% select(`Região de Procedência`, `Grau de Instrução`) %>% table() %>% prop.table() %>% addmargins() * 100 row.names(prop.tab)[4] <- "Total" colnames(prop.tab)[4] <- "Total" kable(prop.tab, digits = 0, caption = "Distribuição conjunta das frequências relativas (em porcentagem) em relação ao total geral das variáveis grau de instrução e região de procedência.") %>% add_header_above(c("Região de Procedência", "Grau de Instrução" = 3, " ")) ``` \normalsize \framebreak - Podemos, então, afirmar que 11% dos empregados vêm da capital e têm o ensino fundamental. - Os totais nas margens fornecem as distribuições unidimensionais de cada uma das variáveis. + Por exemplo, 31% dos indivíduos vêm da capital, 33% do interior e 36% de outras regiões. \framebreak - A tabela seguinte apresenta a distribuição das proporções em relação ao total das colunas. - Os elementos da coluna de _ensino fundamental_ foram obtidos por dividir as frequências absolutas ($4$, $3$ e $5$) por $12$, o total desta coluna. \footnotesize ```{r percent_tot_coluna, echo=FALSE, warning=FALSE, message=FALSE} prop.tab <- mb_df %>% select(`Região de Procedência`, `Grau de Instrução`) %>% table() %>% prop.table(margin = 2) %>% addmargins() * 100 row.names(prop.tab)[4] <- "Total" colnames(prop.tab)[4] <- "Total" kable(prop.tab, digits = 0, caption = "Distribuição conjunta das frequências relativas (em porcentagem) em relação aos totais de colunas das variáveis grau de instrução e região de procedência.") %>% add_header_above(c("Região de Procedência", "Grau de Instrução" = 3, " ")) ``` \normalsize \framebreak - Podemos dizer que, entre os empregados com instrução até o ensino fundamental, 33% vêm da capital, ao passo que entre os empregados com ensino médio, 28% vêm da capital. - Esse tipo de tabela serve para comparar a distribuição da procedência dos indivíduos conforme o grau de instrução. - Se tivéssemos interesse em comparar a distribuição do grau de instrução dos indivíduos conforme a procedência, então calcularíamos as frequências relativas em relação aos totais das linhas^[__Sua vez:__ construa a distribuição conjunta de frequências relativas (em porcentagem) em relação aos totais de linhas.]. ## Variáveis qualitativas {.allowframebreaks} - Uma forma alternativa de apresentação da distribuição conjunta de duas variáveis qualitativas é feita por meio de gráficos. - Em geral, utiliza-se o gráfico de barras. \framebreak ```{r barras, echo=FALSE, warning=FALSE, message=FALSE, fig.align='center', out.width="100%"} library(ggplot2) library(viridis) library(reshape2) mb_gg <- mb_df %>% select(`Região de Procedência`, `Grau de Instrução`) %>% table() %>% prop.table(margin = 2) %>% melt() p <- ggplot(data = mb_gg, mapping = aes(x = `Grau de Instrução`, fill = `Região de Procedência`, y = value)) + geom_bar(position = "fill", stat = "identity") + scale_fill_viridis(discrete = T) + scale_y_continuous(labels = scales::percent) + theme_bw() + ylab("Frequências relativas") + theme(legend.position = "bottom") p ``` \framebreak - Uma pergunta frequente de pesquisadores e usuários de Estatística é sobre a associação entre duas variáveis. - Buscar explicar como se comporta uma variável em função da distribuição de outra tem sido o objetivo de vários estudos que utilizam a Estatística como ferramenta auxiliar. - Em outras palavras, a distribuição de frequências da variável $Y$ muda de acordo com o nível (categoria) da variável $X$? - Em caso afirmativo, diremos que as variáveis são __associadas__, ou dependem uma da outra. - Caso contrário, diremos que as variáveis são __independentes__, e portanto, não há associação entre as variáveis. \framebreak - __Exemplo:__ em setembro de 2019, o jornalismo esportivo divulgava os resultados das partidas disputas pelo Grêmio. + Uma questão era observada pelos especialistas: sem o jogador Maicon, o Grêmio tinha apresentado um desempenho pior. + Na tabela a seguir são apresentadas as frequências relativas (em porcentagem) de 52 partidas disputadas até aquele momento. \footnotesize ```{r gremio, echo=FALSE, warning=FALSE, message=FALSE} tab <- matrix(c(10, 9, 4, 17, 7, 5), byrow = T, ncol = 3, dimnames = list(c("Sem Maicon", "Com Maicon"), c("Vitórias", "Empates", "Derrotas"))) prop.tab <- addmargins(prop.table(addmargins(tab, margin = 1), margin = 1), margin = 2) * 100 row.names(prop.tab)[3] <- "Total" colnames(prop.tab)[4] <- "Total" kable(prop.tab, digits = 2, caption = "Resultados dos jogos do Grêmio em 2019.") ``` \normalsize \framebreak - Note que as frequências são com relação a linha. - Assim, observamos que sem considerar que Maicon jogou, o jogo resulta em vitória do Grêmio em aproximadamente 52% das vezes. - Mas, quando Maicon está em campo esta porcentagem muda para aproximadamente 59%. - Quando ele não está em campo, a porcentagem de vitórias cai para 43%. - Assim, poderíamos concluir que a presença de Maicon no jogo foi importante para o desempenho do time do Grêmio no ano de 2019. - Em outras palavras, as variáveis _resultado do jogo do Grêmio_ e _escalação do time do Grêmio_ são associadas (ou dependentes), pois a distribuição de frequências da variável _resultado do jogo do Grêmio_ muda conforme o nível (categoria) da variável _escalação do time do Grêmio_^[Um caminho natural a partir deste resultado seria quantificar o grau de dependência entre estas variáveis. A medida resumo mais utilizada é __coeficiente de contingência__, mais conhecido como o $\chi^2$ de Pearson. Não apresentaremos nestas notas o coeficiente de contingência, mas recomendamos a leitura complementar deste.]. ## Próxima aula - Distribuições bivariadas: variáveis quantitativas. ## Por hoje é só! \begin{center} {\bf Bons estudos!} \end{center} ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='50%', out.height='50%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'Statistically-Insignificant-final02.jpg')) ``` <file_sep>## ----mb, echo=FALSE, warning=FALSE, message=FALSE--------------------------------------------- library(dplyr) library(readxl) library(knitr) mb_df <- read_excel(path = here::here("data", "companhia_mb.xlsx")) mb_df %>% select(N ,`Região de Procedência`, `Grau de Instrução`) %>% rename("ID" = "N") %>% # slice_head(n = 10) %>% kable(caption = "Tabela de dados brutos.", format = "pandoc") ## ----tab_dupla, echo=FALSE, warning=FALSE, message=FALSE-------------------------------------- library(kableExtra) tab <- mb_df %>% select(`Região de Procedência`, `Grau de Instrução`) %>% table() %>% addmargins() row.names(tab)[4] <- "Total" colnames(tab)[4] <- "Total" kable(tab, caption = "Distribuição conjunta das frequências das variáveis grau de instrução e região de procedência.", align = "cccc", format = "latex") %>% add_header_above(c("Região de Procedência", "Grau de Instrução" = 3, " ")) ## ----percent_tot_geral, echo=FALSE, warning=FALSE, message=FALSE------------------------------ prop.tab <- mb_df %>% select(`Região de Procedência`, `Grau de Instrução`) %>% table() %>% prop.table() %>% addmargins() * 100 row.names(prop.tab)[4] <- "Total" colnames(prop.tab)[4] <- "Total" kable(prop.tab, digits = 0, caption = "Distribuição conjunta das frequências relativas (em porcentagem) em relação ao total geral das variáveis grau de instrução e região de procedência.", align = "cccc", format = "latex") %>% add_header_above(c("Região de Procedência", "Grau de Instrução" = 3, " ")) ## ----percent_tot_coluna, echo=FALSE, warning=FALSE, message=FALSE----------------------------- prop.tab <- mb_df %>% select(`Região de Procedência`, `Grau de Instrução`) %>% table() %>% prop.table(margin = 2) %>% addmargins() * 100 row.names(prop.tab)[4] <- "Total" colnames(prop.tab)[4] <- "Total" kable(prop.tab, digits = 0, caption = "Distribuição conjunta das frequências relativas (em porcentagem) em relação aos totais de colunas das variáveis grau de instrução e região de procedência.", align = "cccc", format = "latex") %>% add_header_above(c("Região de Procedência", "Grau de Instrução" = 3, " ")) ## ----barras, echo=FALSE, warning=FALSE, message=FALSE, fig.align='center', out.width="90%"---- library(ggplot2) library(viridis) library(reshape2) mb_gg <- mb_df %>% select(`Região de Procedência`, `Grau de Instrução`) %>% table() %>% prop.table(margin = 1) %>% melt() mb_gg <- mb_gg %>% group_by(`Região de Procedência`) %>% mutate(value_pos = cumsum(value) - (0.5 * value)) %>% mutate(value_lab = round(value * 100, 1)) p <- ggplot(data = mb_gg, mapping = aes(x = `Região de Procedência`, y = value)) + geom_bar(mapping = aes(fill = rev(`Grau de Instrução`)), stat = "identity") + geom_text(mapping = aes(y = value_pos, label = value_lab), col = "white", vjust = 0) + scale_fill_viridis(discrete = T) + scale_y_continuous(labels = scales::percent) + labs(y = "Frequências relativas", fill = "Grau de Instrução") + theme_bw() + theme(legend.position = "bottom") p ## ----gremio, echo=FALSE, warning=FALSE, message=FALSE----------------------------------------- tab <- matrix(c(10, 9, 4, 17, 7, 5), byrow = T, ncol = 3, dimnames = list(c("Sem Maicon", "Com Maicon"), c("Vitórias", "Empates", "Derrotas"))) prop.tab <- addmargins(prop.table(addmargins(tab, margin = 1), margin = 1), margin = 2) * 100 row.names(prop.tab)[3] <- "Total" colnames(prop.tab)[4] <- "Total" kable(prop.tab, digits = 2, caption = "Resultados dos jogos do Grêmio em 2019.", align = "cccc", format = "latex", format.args = list(decimal.mark = ",")) <file_sep>--- title: "MAT02018 - Estatística Descritiva" subtitle: "Conceitos Básicos" fontsize: 10pt author: | | <NAME> | `<EMAIL>` institute: | | \textsc{Universidade Federal do Rio Grande do Sul} | \textsc{Instituto de Matemática e Estatística} | \textsc{Departamento de Estatística} date: | | Porto Alegre, 2020 header-includes: - \titlegraphic{\hfill\includegraphics[height=1.5cm]{logos/Logo-40-anos-estatistica.png}} --- # Introdução ## Dados $\leadsto$ Conhecimento - Em alguma fase de seu trabalho, o pesquisador depara-se com o problema de __analisar__ e __entender__ um __conjunto de dados__ relevante ao seu particular objeto de estudos. - Ele necessitará trabalhar os dados para __transformá-los em informações__, para compará-los com outros resultados, ou ainda para __julgar sua adequação__ a __alguma teoria__. ## Dados $\leadsto$ Conhecimento ### Uma representação ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='100%', out.height='80%', paged.print=FALSE, purl=FALSE} library(cowplot) library(ggplot2) p1 <- ggdraw() + draw_image(here::here('images', 'model.jpg'), scale = 0.9) p2 <- ggdraw() + draw_image(here::here('images', 'decisionloops2.jpg'), scale = 0.9) plot_grid(p1, p2) ``` ## Dados $\leadsto$ Conhecimento ### Uma representação mais ousada! ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='100%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'Data-Wisdom.jpg')) ``` ## O Método Científico - De modo bem geral, podemos dizer que a essência da Ciência é a __observação__ e que seu objetivo básico é a __inferência__. ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='70%', out.height='70%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'metodo.png')) ``` ## O Método Científico - De modo bem geral, podemos dizer que a essência do Aprendizado (da Evolução). ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='50%', out.height='70%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'metodo_cientifico_bebes.png')) ``` # Conceitos básicos ## O que é a estatística? - A __estatística__\footnote{Do grego \emph{statistós}, de \emph{statízo}, \textbf{``estabelecer''}, \textbf{``verificar''}, acrescido do sufixo \emph{ica}.} é a ciência que tem por objetivo orientar a coleta, o resumo, a apresentação, a análise e a interpretação de dados. - Podem ser identificadas duas grandes áreas de atuação desta ciência: + a __estatística descritiva__, envolvida com o resumo e a apresentação dos dados. + a __estatística inferencial__, que ajuda a concluir sobre conjuntos maiores de dados (populações) quando apenas partes desses conjuntos (as amostras) foram estudadas. <!-- - Mais do que uma sequência de métodos, a estatística é uma forma de pensar ou de ver a realidade variável, já que seu conhecimento não apenas fornece um conjunto de técnicas de análise de dados, mas condiciona toda uma postura crítica sobre sua interpretação e a elaboração de conclusões sobre os dados. --> ## O que é a estatística? ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='100%', out.height='80%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'Descritiva_Inferencia.png')) ``` ## O que é a estatística descritiva? - A __Estatística Descritiva__ corresponde aos procedimentos relacionados com a \structure{coleta}, \structure{elaboração}, \structure{tabulação}, \structure{análise}, \structure{interpretação} e \structure{apresentação} dos \structure{dados}. - Isto é, inclui as técnicas que dizem respeito à sintetização e à descrição de dados numéricos. - Estas técnicas podem ser utilizadas em pelo menos dois contextos + Análise da \structure{consistência dos dados}. + \structure{Análise Exploratória de Dados} (_Exploratory Data Analysis_ - EDA)\footnote{<NAME>. \emph{Exploratory data analysis}, Reading:Addison-Wesley, 1977.}. - Tais métodos tanto podem ser gráficos como envolver análise computacional. ## Estatística descritiva: alguns exemplos \footnotesize ```{r echo=FALSE, message=FALSE, warning=FALSE, purl=FALSE, results='asis'} library(summarytools) descr(tobacco, style = 'rmarkdown') ``` ## Estatística descritiva: alguns exemplos ```{r echo=FALSE, message=FALSE, warning=FALSE, purl=FALSE, results='asis'} freq(tobacco$gender, style = 'rmarkdown', headings = F) ``` ## Estatística descritiva: alguns exemplos ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='95%', paged.print=FALSE} # Considerações finais: exemplos # install.packages("jpeg") # install.packages("grid") library(jpeg) library(grid) library(gapminder) library(dplyr) gapminder <- gapminder %>% mutate(pop_m = pop/1e6) gapminder07 <- gapminder %>% filter(year == 2007) img <- readJPEG(here::here("images", "hans_rosling.jpg")) # start plotting p <- ggplot(data = gapminder07, mapping = aes(x = gdpPercap, y = lifeExp, color = continent, size = pop_m)) + annotation_custom(rasterGrob(img, width = unit(1, "npc"), height = unit(1, "npc")), -Inf, Inf, -Inf, Inf) + scale_y_continuous(expand = c(0,0), limits = c(min(gapminder07$lifeExp) * 0.9, max(gapminder07$lifeExp) * 1.05)) + geom_point() + labs(x = "Renda per capita (US$)", y = "Expectativa de vida (anos)", color = "Continente", size = "População/1 milhão") + theme_bw() + theme(text = element_text(color = "gray20"), legend.position = c("top"), # posição da legenda legend.direction = "horizontal", legend.justification = 0.1, # ponto de ancora para legend.position. legend.text = element_text(size = 11, color = "gray10"), axis.text = element_text(face = "italic"), axis.title.x = element_text(vjust = -1), axis.title.y = element_text(vjust = 2), axis.ticks.y = element_blank(), # element_blank() é como removemos elementos axis.line = element_line(color = "gray40", size = 0.5), axis.line.y = element_blank(), panel.grid.major = element_line(color = "gray50", size = 0.5), panel.grid.major.x = element_blank() ) p ``` ## Unidades experimentais e observacionais - __Unidade experimental__ ou __unidade de observação__ é a menor unidade a fornecer informação. + __Ex:__ alunos, pacientes, animais, plantas, carros, hospitais, escolas, cidades, universidades, países, _tweets_, etc. ### Crash course de inferência causal __Qual o melhor tratamento para o choque séptico?__ Dois tipos de estudo podem ser conduzidos para responder a esta questão de pesquisa: 1. Em um \structure{experimento aleatorizado} (_randomized trial_), uma moeda justa é lançada repetidamente para designar o tratamento de cada paciente. 2. Um \structure{estudo observacional} é uma investigação empírica em que o objetivo é elucidar relações de causa e efeito, em que não é factível o uso de experimentação controlada, no sentido de ser capaz de impor procedimentos ou tratamentos cujos os efeitos se deseja descobrir. ## Experimentos: exemplo - "O chá servido sobre o leite parecia ficar com gosto diferente do que apresentava ao receber o leite sobre ele"\footnote{Salsburg, D. \emph{Uma senhora toma chá $\ldots$ como a estatística revolucionou a ciência no século XX}, Zahar, 2009.}. ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='70%', out.height='60%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'uma_senhora_toma_cha.jpg')) ``` ## Estudos observacionais: exemplo - "O __Ministério da Saúde__ adverte: __fumar pode causar câncer de pulmão__”\footnote{Salsburg, D. \emph{Uma senhora toma chá $\ldots$ como a estatística revolucionou a ciência no século XX}, Zahar, 2009.}. ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='70%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'smokingAndLungCancer2.jpg')) ``` ## Exercício 1. Elabore uma questão de pesquisa de seu interesse (anote a sua questão em algum lugar). 2. Discuta a respeito da sua questão de pesquisa com os colegas. ## Dados e variáveis ::: {.block} ### Dados São as informações obtidas de uma unidade experimental ou observacional. \ - __Ex:__ "Vitor tem 25 anos e é fumante". Os dados são "25 anos" e "fumante". ::: ::: {.block} ### Variável É toda característica que, observada em uma unidade (experimental ou observacional), pode variar de um indivíduo para outro. \ - __Ex:__ idade, sexo, altura, nível de hemoglobina no sangue, espaçamento entre plantas, doses de um medicamento, tipo de medicamento, cultivares, número de caracteres, velocidade da rede, tempo gasto na rede social, nível de monóxido de carbono em emissões do escape de automóveis, etc. ::: É importante __identificar que tipo de variável__ está sendo estudada, uma vez que são recomendados __procedimentos estatísticos diferentes__ em cada situação. ## Tipos de variáveis ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='90%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'classe_var.png')) ``` ## Variáveis quantitativas ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='100%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'var_quanti.png')) ``` ## Variáveis quantitativas discretas ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='60%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'var_discreta.jpg')) ``` ## Variáveis quantitativas contínuas ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='70%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'var_continua.jpg')) ``` ## Variáveis qualitativas ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='100%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'var_quali.png')) ``` ## Variáveis qualitativas ordinais ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='100%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'var_ordinal.jpg')) ``` ## Variáveis qualitativas nominais ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='70%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'var_nominal.jpg')) ``` ## Exemplos (1) ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='90%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'cor_predio2.jpg')) ``` ## Exemplos (1) ### Variáveis quantitativas - 3 andares - 14,85 metros de altura ### Variáveis qualitativas - Multicolorido - Cheira "bem" ## Exemplos (2) ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='90%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'rolling-stones.jpg')) ``` ## Exemplos (2) ### Variáveis quantitativas - 4 integrantes - 56 anos ### Variáveis qualitativas - Inglaterra - Rock ## Exercício 1. Com base na questão de pesquisa elaborada no exercício anterior, liste variáveis que você teria interesse em coletar e analisar para responder a sua questão de pesquisa. 2. Classifique as variáveis de acordo com a classificação discutida anteriormente. 3. Discuta a respeito das suas variáveis com os colegas. ## População - __População__ ou __universo__: esse termo é usado em estatística com um sentido bem mais amplo do que na linguagem coloquial. - É entendido aqui como o __conjunto de todos os elementos__ que apresentam uma ou mais características __em comum__. - __Exemplo 1:__ a população de colegiais de oito anos de Belo Horizonte. + Estes colegiais têm em comum a idade e o local onde vivem. - __Exemplo 2:__ a população de indústrias brasileiras. + Estas indústrias têm em comum o fato de que foram criadas no Brasil. - Este conjunto por vezes é denominado por $U$ (de __conjunto universo__). - O __tamanho da população__ é a sua quantidade de elementos, que anotamos por $N$. - Uma população pode ser __finita__ (limita em tamanho; $N < \infty$) ou __infinita__ ($N =\infty$). + __Exemplo de pop. finita:__ torcedores do São Raimundo de Santarém, residentes de Porto Alegre. + __Exemplo de pop. infinita:__ equipamentos (de um certo tipo) fabricados em série. ## Censo e amostra - Quando o estudo é realizado com toda a população de interesse, chamemos este estudo de __censo__. - Por motivos de tempo, custo, logística, entre outros, geralmente não é possível realizar um censo. + Nestes casos, estudamos apenas uma parcela da população, que chamamos de __amostra__. ### Censo vs. amostra À primeira vista, uma coleta de dados realizada em toda a população é preferível a uma realizada apenas numa parte da população. Na prática, entretanto, o oposto é frequentemente verdadeiro porque: 1. Um censo é impossível quando a população é infinita. 2. Os ensaios (testes) podem ser destrutivos \structure{(como nos testes de segurança dos carros)}. 3. Rapidez: estudar toda a população pode despender de muito tempo, não sendo compatível com a urgência do estudo \structure{(como quando estudamos os casos de um surto de uma nova doença)}. Para uma consideração mais completa ver Vargas (2000)\footnote{<NAME>. \emph{Estatística: uma linguagem para dialogar com a incerteza}, Cadernos de matemática e estatística. Série B, 2000.}. ## Amostra - __Amostra__ é qualquer fração de uma população. + Como sua finalidade é representar a população, deseja-se que a amostra escolhida apresente as mesmas características da população de origem, isto é, que seja uma amostra __"representativa"__ ou __"não-tendenciosa"__. - Tanto o número de indivíduos selecionados para a amostra quanto a técnica de seleção são extremamente importantes para que os resultados obtidos no estudo sejam generalizados para a população. ## Amostra representativa ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='65%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'Gato_caindo.jpg')) ``` - Ver a discussão sobre __representatividade da amostra__ na [apresentação](https://www.youtube.com/watch?v=TGGGDpb04Yc&t=592s) do __Prof. <NAME>__. ## Amostragem - A seleção da amostra pode ser feita de várias maneiras. - Esta dependerá: + Do grau de conhecimento que temos da população. + Da quantidade de recursos disponíveis. - A seleção da amostra tenta fornecer um subconjunto de valores o __mais parecido possível__ com a população que lhe dá origem. + __Amostra representativa__ da população. ## Amostra aleatória simples - A amostragem mais usada é a __amostra casual simples__ (ou aleatória simples). + Os indivíduos (unidades) da amostra são selecionados ao acaso, __com__ ou __sem reposição__. ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='60%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'simpleSample.png')) ``` ## Amostra estratificada - Eventualmente, se tivermos informações adicionais a respeito da população de interesse, podemos utilizar outros esquemas de amostragem mais sofisticados. + __Amostragem estratificada__ ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='95%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'estratificada.png')) ``` ## Amostra sistemática - Em outros casos, pode existir uma relação numerada dos itens da população que nos permitiria utilizar a chamada __amostragem sistemática__ em que selecionamos os indivíduos de forma pré-determinada. ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='80%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'SystematicSampling.jpg')) ``` ## Amostragem - Outros esquemas de amostragem poderiam ser citados e todos fazem parte da chamada __teoria da amostragem__, cujos detalhes não serão aprofundados. ## Parâmetros, estatísticas e estimativas - __Parâmetro__ é um valor que resume, na população, a informação relativa a uma variável. + __Ex:__ média populacional, prevalência populacional, coeficiente de variação populacional, taxa de mortalidade populacional, etc. - __Estatística__ (além de ser o nome da ciência/área do conhecimento) é a denominação dada a uma quantidade, calculada com base nos elementos de uma amostra, que descreve a informação contida nesse conjunto de dados. + __Ex:__ A média, a porcentagem, o desvio padrão, o coeficiente de correlação, calculados em uma amostra, são estatísticas. ## Parâmetros, estatísticas e estimativas - Os parâmetros são difíceis de se obter, pois implicam o estudo de toda a população e costumam ser substituídos por valores calculados em amostras representativas da população-alvo. + Se tivesse sido examinada uma amostra de 10 estudantes matriculados na disciplina MAT02218, e 40% fossem do torcedores do América Mineiro, esse valor constituiria uma estimativa do parâmetro "percentual de torcedores do América Mineiro matriculados naquela disciplina". - A __estimativa__ é um valor numérico de uma estatística, usado para realizar inferências sobre o parâmetro. + Da mesma forma, o valor numérico da média para a estatura desses 10 alunos, digamos 173 cm, é uma estimativa para a média de altura populacional. - __P:__ neste exemplo, quem é a população (alvo)? ## Próxima aula - Organização dos dados <!-- - Distribuição de frequências --> ## Para casa \begin{columns}[c] \column{2.3in} \begin{figure}[!h] \begin{center} \includegraphics[width=0.9\columnwidth]{images/stats_cats.jpg} \end{center} \end{figure} \column{2.3in} \begin{itemize}\setlength{\itemsep}{+2mm} \item Conhecer o Moodle da disciplina. \item Ler os Cap. 1 e 2 de "Estatística Descritiva I" de Fernandez. \end{itemize} \end{columns} ## Por hoje é só! Bons estudos! ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='100%', out.height='80%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'lofi_01.jpg')) ``` <file_sep>--- title: "MAT02018 - Estatística Descritiva" subtitle: "Distribuição de Frequências" fontsize: 10pt author: | | <NAME> | `<EMAIL>` institute: | | \textsc{Universidade Federal do Rio Grande do Sul} | \textsc{Instituto de Matemática e Estatística} | \textsc{Departamento de Estatística} date: | | Porto Alegre, 2022 --- # Introdução ## Introdução {.allowframebreaks} - Uma contribuição importante da estatística no manejo das informações foi a criação de procedimentos para a organização e o resumo de grandes quantidades de dados. - A descrição das variáveis é imprescindível como passo prévio para a adequada interpretação dos resultados de uma investigação, e a metodologia empregada faz parte da estatística descritiva. - Os dados podem ser organizados em \structure{tabelas} ou \structure{gráficos}. Nestas notas de aula, vamos apresentar como organizar a informação em \structure{tabelas de frequências}. # Distribuição de Frequências ## Distribuição de Frequências {.allowframebreaks} - Dados nominais, ordinais e discretos, depois de apurados, devem ser organizados em \structure{tabelas de distribuição de frequências}. - \structure{Frequência de uma categoria (ou valor)} é o número de vezes que essa categoria (ou valor) ocorre no conjunto de dados (uma amostra ou população)\footnote{{\bf Lembrando:} {\bf população} é o conjunto de todos os elementos que apresentam uma ou mais características em comum. Quando o estudo é realizado com toda a população de interesse, chamaremos este estudo de {\bf censo}. Por motivos de tempo, custo, logística, entre outros, geralmente não é possível realizar um censo. Nestes casos, estudamos apenas uma parcela da população, que chamamos de {\bf amostra}. Amostra é qualquer fração de uma população. Como sua finalidade é representar a população, deseja-se que a amostra escolhida apresente as mesmas características da população de origem, isto é, que seja uma amostra {\bf ``representativa''} ou {\bf ``não tendenciosa''}.}. ## Dados nominais {.allowframebreaks} - Para organizar os dados nominais em uma tabela de distribuição de frequências escreva, na __primeira coluna__, o __nome da variável__ em estudo e logo abaixo, na mesma coluna, as categorias (ou seja, os valores) da variável. - Na __segunda coluna__, escreva __"Frequência"__, e logo abaixo as frequências das respectivas categorias. \framebreak - __Exemplo:__ reveja o exemplo do grupo de 15 empregados da seção de orçamentos da Companhia MB. + Anotamos o número de solteiros e casados para organizar os dados em uma tabela de frequências. + Para isso, devemos escrever o nome da variável (_Estado civil_) e, em coluna, as categorias (_solteiro_, _casado_). + As frequências são 8 empregados solteiros e 7 empregados casados que, somadas, dão um total de 15 empregados. \framebreak ```{r, echo=FALSE, message=FALSE, warning=FALSE, purl=FALSE} civil <- c(rep("Solteiro", 8), rep("Casado", 7)) library(summarytools) civil.tab <- as.data.frame(na.omit(summarytools::freq(civil, order = "freq")))["Freq"] civil.tab <- data.frame("estado_civil"= row.names(civil.tab), "freq" = civil.tab$Freq) knitr::kable(civil.tab, col.names = c("Estado civil", "Frequência")) ``` \framebreak ### Observações 1. É comum utilizar a última linha da tabela para expressar o total. Em geral, este deve coincidir com o tamanho do conjunto de dados. Em alguns casos, a variável não foi observada/coletada (_dados ausentes_) para uma ou mais unidades, e portanto, o total deve ser menor que o tamanho do conjunto de dados. 2. Usaremos a \structure{notação $n_i$} para indicar a frequência (absoluta) cada classe, ou categoria, da variável. ## Dados nominais {.allowframebreaks} ### Exercício - Construa a tabela de distribuição de frequências da variável _Região de procedência_ do exemplo do grupo de 15 empregados da seção de orçamentos da Companhia MB. ## Dados ordinais {.allowframebreaks} - Dados ordinais devem ser organizados em tabelas de distribuição de frequências. - Escreva, na primeira coluna, o nome da variável em estudo e, logo abaixo, os nomes das categorias em __ordem crescente__\footnote{Nos referimos a ordem das categorias e não das suas frequências.}. - As frequências devem estar em outra coluna, mas nas linhas das respectivas categorias. ## Dados ordinais {.allowframebreaks} - Retornando ao exemplo do grupo de 15 empregados da seção de orçamentos da Companhia MB, considere a variável _Grau de instrução_. + O nome da variável e suas categorias foram escritos na primeira coluna e, na segunda coluna, as respectivas frequências. ```{r, echo=FALSE, message=FALSE, warning=FALSE, purl=FALSE} escola <- factor(x = c(rep("Ensino fundamental", 9), rep("Ensino médio", 5), "Superior")) escola.tab <- as.data.frame(na.omit(summarytools::freq(escola)))["Freq"] escola.tab <- data.frame("escola"= row.names(escola.tab), "freq" = escola.tab$Freq) knitr::kable(escola.tab, col.names = c("Grau de instrução", "Frequência ($n_i$)")) ``` ## Dados discretos {.allowframebreaks} - Dados discretos também são organizados em tabelas de distribuição de frequências. - Para isso, os valores que a variável pode assumir são colocados na primeira coluna, em __ordem crescente__. - O número de vezes que cada valor se repete (a frequência) é escrito em outra coluna, nas linhas respectivas aos valores. \framebreak - Mais uma vez, retorne ao exemplo da seção de orçamentos da Companhia MB. + O número de filhos dos empregados da seção é apresentado a seguir na distribuição de frequências. ```{r, echo=FALSE, message=FALSE, warning=FALSE, purl=FALSE} filhos <- c(rep(0, 6), rep(1, 4), rep(2, 4), 3) filhos.tab <- as.data.frame(na.omit(summarytools::freq(filhos)))["Freq"] filhos.tab <- data.frame("filhos"= row.names(filhos.tab), "freq" = filhos.tab$Freq) knitr::kable(filhos.tab, col.names = c("Número de filhos", "Frequência ($n_i$)")) ``` ## Dados contínuos {.allowframebreaks} - Dados contínuos podem assumir __diversos valores diferentes__\footnote{Aqui chamamos mais uma vez a atenção para a importância de distinguirmos os diferentes tipos de variáveis. Uma variável \emph{quantitativa contínua} é uma {\bf variável}! E portanto, {\bf pode variar} de um indivíduo para outro! No entanto, a variável \emph{quantitativa contínua} possui um conjunto de valores possíveis {\bf infinito} (um intervalo da reta real), e assim, podemos observar um número de unidades com valores distintos para uma certa variável contínua maior que no caso de uma variável nominal. {\bf Exercício:} compare os valores possíveis para as variáveis {\bf altura} e {\bf estado civil}.}, mesmo em amostras pequenas. - Por essa razão, a menos que sejam em grande número, são apresentados na forma como foram coletados. ## Dados contínuos {.allowframebreaks} - Considere, como exemplo, que o pesquisador resolveu organizar as idades dos empregados da seção de orçamentos da Companhia MB em uma tabela. - Pode escrever os dados na ordem em que foram coletados, como segue: ```{r, echo=FALSE, message=FALSE, warning=FALSE, purl=FALSE} idade <- c(26, 32, 36, 20, 40, 28, 41, 43, 34, 23, 33, 27, 37, 44, 30) idade.tab <- matrix(data = idade, nrow = 3) knitr::kable(idade.tab, format = "pandoc") ``` \framebreak - Quando em grande número, os dados contínuos podem ser organizados, para apresentação, em uma tabela de distribuição de frequências. - Vamos entender como isso é feito por meio de novo exemplo. \framebreak - Foram propostas muitas maneiras de avaliar a capacidade de uma criança para o desempenho escolar. - Algumas crianças estão "prontas" para aprender a escrever aos cinco anos, outras, aos oito anos. - Imagine que um professor aplicou o _Teste de Desempenho Escolar_ (TDE) a 27 alunos da 1ª série do Ensino Fundamental. - Os dados obtidos pelo professor estão apresentados em seguida. ```{r, echo=FALSE, message=FALSE, warning=FALSE, purl=FALSE} tde <- c(7, 18, 111, 25, 101, 85, 81, 75, 100, 95, 98, 108, 100, 94, 34, 99, 84, 90, 95, 102, 96, 105, 100, 107, 117, 96, 17) tde.tab <- matrix(data = tde, nrow = 3) knitr::kable(tde.tab, format = "pandoc") ``` \framebreak - Para __conhecer o comportamento__ do desempenho escolar desses alunos, o professor deve organizar uma __distribuição de frequências__. - No entanto, para isso, é preciso __agrupar os dados em faixas__, ou __classes__\footnote{Note que se procedermos da mesma forma que procedemos para os casos anteriores, a nossa tabela de distribuição de frequências apresentaria um grande número de valores com baixas frequências. Isso nos daria tanta informação quanto a tabela de dados brutos, e portanto, não nos ajudaria a conhecer o comportamento da variável.}. + Em quantas faixas ou classes podem ser agrupados os dados? ## Dados contínuos {.allowframebreaks} - Uma __regra prática__ é a seguinte: \structure{o número de classes deve ser aproximadamente igual à raiz quadrada do tamanho da amostra.} $$ \mbox{Número de classes} = \sqrt{n}. $$ - No exemplo, são 27 alunos. + O tamanho da amostra é, portanto, $n = 27$. + A raiz quadrada de 27 está entre $5 (\sqrt{25})$ e $6 (\sqrt{36})$. Portanto, podem ser organizadas __cinco classes__. - Mas como? \framebreak - Observe cuidadosamente o conjunto de dados. - Ache o __valor mínimo__, o __valor máximo__ e a __amplitude__. ### - __Valor mínimo__ é o menor valor de um conjunto de dados. - __Valor máximo__ é o maior valor de um conjunto de dados. - __Amplitude__ é a diferença entre o valor máximo e o valor mínimo. ## Dados contínuos {.allowframebreaks} - Para os valores obtidos pelos 27 alunos no Teste de Desempenho Escolar, temos: - Valor mínimo $= 7$; - Valor máximo $= 117$; - Amplitude $= 117 - 7 = 110$. - Uma vez obtida a amplitude do conjunto de dados, é preciso calcular a \structure{amplitude das classes}. \framebreak - \structure{Amplitude de classe} é dada pela divisão da amplitude do conjunto de dados pelo número de classes. - Para os dados do TDE, a amplitude ($110$) deve ser dividida pelo número de classes que já foi calculado ($5$): $$ 110 \div 5 = 22. $$ \framebreak - A __amplitude de classe__ será, então, $22$. Isso significa que: - a primeira classe vai do valor mínimo, $7$ até $7 + 22 = 29$; - a segunda classe vai de $29$ a $29 + 22 = 51$; - a terceira classe vai de $51$ a $51 + 22 = 73$; - a quarta classe vai de $73$ a $73 + 22 = 95$; - a quinta classe vai de $95$ a $95 + 22 = 117$, inclusive. - Os valores que delimitam as classes são denominados \structure{extremos}. \framebreak - \structure{Extremos de classe} são os valores que delimitam as classes. - Uma questão importante é saber __como__ as classes devem ser escritas. Alguém pode pensar em escrever as classes como segue: \begin{eqnarray*} 7 &-& 28\\ 29 &-& 51, \mbox{etc.}\\ \end{eqnarray*} - No entanto, essa notação traz dúvidas. \framebreak - Como saber, por exemplo, para qual classe vai o valor $28,5$? - Esse tipo de dúvida é evitado indicando as classes como segue: \begin{eqnarray*} 7 &\vdash& 28\\ 29 &\vdash& 51, \mbox{etc.}\\ \end{eqnarray*} - Usando essa notação, fica claro que o intervalo é \structure{fechado} à esquerda e \structure{aberto} à direita. \framebreak - Então, na classe $7\vdash 29$ estão \structure{incluídos} os valores iguais ao extremo inferior da classe, que é $7$ (o intervalo é fechado à esquerda), mas \structure{não estão incluídos} os valores iguais ao extremo superior da classe, que é $29$ (o intervalo é aberto à direita). - A indicação de que o intervalo é fechado é dada pelo lado esquerdo do traço vertical do símbolo $\vdash$. - A indicação de intervalo aberto é dada pela ausência de traço vertical no lado direito do símbolo $\vdash$. - Uma alternativa a esta notação é dada por \structure{colchetes} e \structure{parênteses}. \framebreak - Considere \structure{$ei$} e \structure{$es$} os \structure{extremos inferior} e \structure{superio}r de uma classe qualquer, respectivamente. - "$(ei; es]$", ou "$\dashv$" é um intervalo aberto à esquerda e fechado à direita; - "$[ei; es)$", ou "$\vdash$" é um intervalo aberto à direita e fechado à esquerda; - "$(ei; es)$", ou "$]ei; es[$", ou "--" é um intervalo aberto; - "$[ei; es]$", ou "$\vdash\dashv$" é um intervalo fechado. \framebreak - Estabelecidas as classes, é preciso obter as \structure{frequências}. - Para isso, contam-se quantos alunos estão na classe de $7$ a $29$ \structure{(exclusive)}\footnote{Ou, seja, sem incluir o extremo direito do intervalo de classe; neste caso, o valor 29.}, quantos estão na classe de $29$ a $51$ \structure{(exclusive)}, e assim por diante. ### Apuração - Aqui uma abordagem poderia ser a criação de uma "nova variável" (transformada) de idade em classes na planilha de dados brutos, e então proceder com a apuração desta "nova variável" como no caso de uma variável qualitativa. - Afinal de contas, as classes de idade são categorias. + Neste caso, categorias de uma variável qualitativa ordinal. ## Dados contínuos {.allowframebreaks} - A distribuição de frequências pode então ser organizada como segue. ```{r, echo=FALSE, message=FALSE, warning=FALSE, purl=FALSE} tde.cat <- cut(x = tde, breaks = c(7, 29, 51, 73, 95, 117), labels = c("7 $\\vdash$ 29", "29 $\\vdash$ 51", "51 $\\vdash$ 73", "73 $\\vdash$ 95", "95 $\\vdash$ 117"), include.lowest = F, right = FALSE) tde.tab <- as.data.frame(na.omit(summarytools::freq(tde.cat)))["Freq"] tde.tab <- data.frame("tde"= row.names(tde.tab), "freq" = tde.tab$Freq) knitr::kable(tde.tab, col.names = c("Classe TDE", "Frequência ($n_i$)"), align = "lc") ``` ## Observações {.allowframebreaks} - Embora a __regra prática__ apresentada aqui para a determinação do número de classes seja útil, ela não é a única forma de determinar classes em uma tabela de frequências para dados contínuos. - O pesquisador pode especificar as classes de acordo com "convenções". - É comum vermos as frequências da variável idade serem apresentadas em classes de amplitude 5 ou 10 anos. - Ainda, podem ser especificadas classes com amplitudes distintas (Idade de 0 a 19 anos, 20 a 59 anos, 60 a 79 anos, 80 anos ou mais). \framebreak - Outro ponto importante é que nem sempre existe interesse em apresentar todas as classes possíveis. - Em aluns casos, a primeira classe pode incluir todos os elementos menores que determinado valor. - Diz-se, então, que o extremo inferior da primeira classe não está definido. - Como exemplo, veja a distribuição de frequências das pessoas conforme a altura, com as seguintes classes: \begin{eqnarray*} && \mbox{Menos de } 150 \mbox{ cm}\\ && 150\ \vdash 160 \mbox{cm}\\ && 160\ \vdash 170 \mbox{cm, etc.}\\ \end{eqnarray*} \framebreak - Do mesmo modo, todos os elementos iguais ou maiores que determinado valor podem ser agrupados na última classe. - Diz-se, então, que o extremo superior da última classe não está definido. - Muitos dados de idade publicados pelo __Instituto Brasileiro de Geografia e Estatística__ (__IBGE__) estão em tabelas de distribuição de frequências com intervalos de classes diferentes (em relação a amplitude) e não possuem extremo superior definido. - Veja o exemplo a seguir. \framebreak ```{r fig-censo, fig.align='center', fig.cap = "População residente, segundo grupos de idade no Brasil (Censo 2010; https://censo2010.ibge.gov.br/sinopse/index.php?dados=12).", cache=TRUE, echo=FALSE, out.height="70%", out.width='30%', purl=FALSE} knitr::include_graphics(here::here('images', 'ibge_idade_censo2010.png')) ``` ## Para casa 1. Resolver os exercícios 1 a 6 do Capítulo 3.5 do livro __Fundamentos de Estatística__\footnote{Vieira, S. {\bf Fundamentos de Estatística}, Atlas, 2019, pg. 37-38.} (disponível no Sabi+). 2. Para os dados nominais, ordinais, discretos econtínuos do seu levantamento estatístico, construa tabelas de frequências e compartilhe no Fórum Geral do Moodle. Discuta como você definiu as classes e suas amplitudes. ## Próxima aula - Distribuição de frequências: __frequências relativa, acumulada, relativa acumulada e porcentagem__. ## Por hoje é só! \begin{center} {\bf Bons estudos!} \end{center} ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='50%', out.height='50%', paged.print=FALSE} knitr::include_graphics(here::here('images', 'Statistically-Insignificant-errorbar.jpg')) ``` <file_sep>--- title: "MAT02018 - Estatística Descritiva" subtitle: "Números índices" fontsize: 10pt author: | | <NAME> | `<EMAIL>` institute: | | \textsc{Universidade Federal do Rio Grande do Sul} | \textsc{Instituto de Matemática e Estatística} | \textsc{Departamento de Estatística} date: | | Porto Alegre, 2022 bibliography: estatistica-descritiva.bib csl: associacao-brasileira-de-normas-tecnicas-ufrgs-initials.csl link-citations: yes --- ```{r setup, include=FALSE, purl=FALSE} options(knitr.kable.NA = '-') library(dplyr) library(knitr) ``` # Apresentação - Neste conjunto de notas de aulas, faremos uma breve introdução ao tema de __números índices__, geralmente utilizados para descrever a situação econômica ao longo do tempo. - Veremos que a construção dos números índices está fortemente ligada a conceitos de estatística descritiva já apresentados neste curso. # Introdução {.allowframebreaks} - Por **índice**, às vezes, quer-se dizer coisas bem diferentes. - Em \structure{Estatística}, como em muitas outras áreas, é sinônimo de **variação relativa** na variável de interesse. - Em \structure{Economia}, há índices de preços, quantidades e valor dos bens, de custo de vida, de (des)emprego, de bolsas de valores, de concentração dos mercados, de monopólio de empresas, de importação e exportação. - Em \structure{Administração}, índices de produção, de liquidez (corrente e seco), velocidade de vendas, lucratividade e endividamento possibilitam avaliar a saúde financeira das empresas. - Em \structure{Administração Pública}, diversos índices permitem avaliar a qualidade de vida, a permanência ou evasão escolar, o nível de criminalidade e o padrão de saúde das populações. - E há mais, bem mais, em \structure{Engenharia}, \structure{Física}, \structure{Medicina} (índices de fertilidade, natalidade, morbidez, mortalidade etc.), nas chamadas ciências do comportamento (\structure{Psicologia}, \structure{Sociologia} etc.) e em \structure{Educação} (quociente de inteligência, coeficiente de aprovação etc.). \framebreak - No sentido mais simples do termo, podemos dizer que um __número índice__ é um quociente que expressa uma dada quantidade em comparação a uma __quantidade base__. - Em outras palavras, são __valores relativos__. - No entanto devemos considerar dois casos: 1. Quando o objetivo de comparação refere-se a __um único__ produto ou serviço \structure{(índice simples/elementar)}. 2. Quando se refere a um __conjunto__ de produtos e de serviços \structure{(índice agregativo/geral)}. \framebreak - No primeiro caso não temos propriamente um problema de números índices, já que não envolve a **questão da agregação** de bens e serviços. - Trata-se somente de uma forma alternativa de se fazer comparações em termos relativos. \framebreak - __Exemplo (único produto):__ a evolução das compras mensais de arroz (em kg), bem como do preço pago por kg, por parte de um supermercado, é apresentada na tabela a seguir. \footnotesize ```{r serie_arroz, echo=FALSE, warning=FALSE, message=FALSE} library(dplyr) library(lubridate) library(readxl) library(knitr) library(kableExtra) arroz_df <- read_excel(path = here::here("data", "CEPEA_20201116161703.xls"), skip = 3) arroz_df$Data <- dmy(arroz_df$Data) arroz_res <- arroz_df %>% group_by(year(Data), month(Data)) %>% summarize(preco = mean(`À vista R$`)) %>% rename(Ano = `year(Data)`, Mes = `month(Data)`, Preco = preco) %>% filter(Ano %in% c(2020) & Mes %in% 3:6) %>% transform(Preco_kg = Preco/50, Quantidade = c(800, 1000, 900, 1050), Mes = paste("Mês", 0:3)) %>% transform(Valor_total = Quantidade * Preco_kg) %>% select(Mes, Quantidade, Preco_kg, Valor_total) arroz_res %>% kable(escape = F, format = "pandoc", align = 'c', digits = c(0, 0, 2, 2), caption = "Evolução das compras mensais de arroz", col.names = c("Período ($t$)", "Quantidade ($kg$)", "Preço ($u.m./kg$)", "Valor total ($u.m.$)"), format.args = list(decimal.mark = ",")) %>% footnote(general = "u.m. = unidade monetária.", general_title = "Nota: ", footnote_as_chunk = T, title_format = c("italic")) ``` \normalsize \framebreak - Se desejarmos saber qual a evolução da quantidade, do preço e do valor total gasto em arroz com base de comparação o mês 0, basta tomarmos como divisor os respectivos valores do mês zero. ::: {.block} ### Relativos (notação) - Utilizaremos a notação \structure{$p_t$ ($q_t$, $v_t$)} para indicar o \structure{preço (quantidade, valor)} no período \structure{$t$}. + Assim, o __relativo__ do preço __(quantidade, valor)__ pode ser definido como \structure{$p_t/p_0$ ($q_t/q_0$, $v_t/v_0$)} quando o período base for o período \structure{$t = 0$}. - Por convenção, os resultados são multiplicados por 100. ::: \framebreak \footnotesize ```{r serie_relativos, echo=FALSE, warning=FALSE, message=FALSE} arroz_res %>% transform(Quantidade = Quantidade / Quantidade[1] * 100, Preco_kg = Preco_kg / Preco_kg[1] * 100, Valor_total = Valor_total / Valor_total[1] * 100) %>% kable(escape = F, format = "pandoc", align = 'c', digits = c(0, 1, 2, 2), format.args = list(decimal.mark = ","), caption = "Evolução das compras mensais de arroz (relativos ao mês 0)", col.names = c("Período ($t$)", "Quantidade", "Preço", "Valor total")) ``` \normalsize \framebreak A **interpretação** dos números apresentados na tabela acima é direta. Assim, se considerarmos a coluna referente a quantidade: + o número 125 significa que houve 25% de aumento (1,25 - 1,00 = 0,25) na compra de arroz no mês 1 relativamente ao mês 0; + no mês 2 verificamos 12,5% de aumento com relação ao mês 0, e assim por diante. + __sua vez:__ qual a variação percentual do mês 3 em relação ao mês 0? \framebreak - __Exemplo (conjunto de produtos):__ considere cinco produtos usualmente consumidos por uma pessoa. + Os preços vigentes em dois períodos distintos de tempo estão apresentados na tabela a seguir. \footnotesize ```{r cinco_produtos, echo=FALSE, warning=FALSE, message=FALSE} prod <- c("Arroz (kg)", "Leite (L)", "Pão francês (u)", "Cigarro (maço)", "Cerveja (garrafa)") mes0 <- c(1.98, 1.99, 0.9, 7, 5.99) mes1 <- c(2.1, 2.08, 0.95, 7.50, 6.99) cinco_df <- data.frame(prod, mes0, mes1) cinco_df %>% kable(escape = F, format = "pandoc", align = 'c', digits = c(0, 2, 2), format.args = list(decimal.mark = ","), caption = "Preços vigentes de cinco produtos", col.names = c("Produtos", "Mês 0 ($u.m.$)", "Mês 1 ($u.m.$)")) ``` \normalsize - Se desejamos saber qual foi a __variação de preços__ de um período com relação ao outro, duas soluções são possíveis e serão apresentadas nas próximas duas seções. # Índice agregativo simples {.allowframebreaks} - Representando por \structure{$p_0^i$} e \structure{$p_1^i$} os preços do produto \structure{$i$ ($i = 1, 2, \ldots, n$)}, respectivamente, no __período 0 (período-base)__ e __1 (período atual)__^[Se o produto 1 representa o arroz, então $p_0^1 = 1,98$ e $p_1^1 = 2,1$; se o produto 2 é o leite, então $p_0^2 = 1,99$ e $p_1^2 = 2,08$; e assim respectivamente para os demais produtos.], a expressão formal do __índice agregativo simples__ (também conhecido como \structure{Índice de Dutot}) é: $$ I_{01}^{as} = \frac{\sum_{i=1}^n{p_1^i}}{\sum_{i=1}^n{p_0^i}}, $$ ou seja, somamos os preços dos produtos, sem ponderações, tanto para o período-base como para o período atual, e dividimos um pelo outro^[Note que $I_{01}^{as}$ é o __relativo das médias__ de preços do mês 1 com respeito ao mês 0.]. ## Índice agregativo simples {.allowframebreaks} - Aplicando a fórmula do $I^{as}$ aos valores dos preços dos cinco produtos, temos que $\sum_{i=1}^5{p_0^i} = 17,86$ e $\sum_{i=1}^5{p_1^i} = 19,62$, e o portanto, o índice agregativo simples é: $$ I_{01}^{as} = \frac{17,86}{19,62} = 1,10, $$ isto é, os preços do conjunto de cinco produtos apresentados no último exemplo acusaram 10% de aumento no mês atual com relação ao mês-base. \framebreak - Note que o $I^{as}$ é influenciado pela unidade de medida que estão expressos os preços. - Se substituirmos apenas o preço da cerveja em u.m. por meia garrafa, teremos 2,99 u.m. para o mês 0 e 3,49 u.m. para o mês 1. - Mantendo os mesmos preços para os demais produtos, o $I^{as}$ é: $$ I_{01}^{as} = \frac{14,87}{16,13} = 1,08. $$ - Notamos que o aumento apurado é 8% no mês atual com relação ao mês-base. # Índice de preços de Sauerbeck {.allowframebreaks} - A influência pela unidade de medida expressa no preço no índice agregativo simples é sanada pelo __índice de preços de Sauerbeck__. - Este nada mais que a __média (aritmética simples) dos relativos__ de preços. Portanto temos: $$ I_{01}^S = \frac{1}{n}\sum_{i=1}^n{\left(\frac{p_1^i}{p_0^i}\right)}. $$ \framebreak - Na tabela a seguir calculamos os relativos dos preços do mês 1 em relação ao mês 0 para cada um dos cinco produtos do exemplo apresentado anteriormente. \footnotesize ```{r cinco_relativos, echo=FALSE, warning=FALSE, message=FALSE} cinco_df <- cinco_df %>% transform(rel = mes1/mes0) cinco_df %>% kable(escape = F, format = "pandoc", align = 'c', digits = c(0, 2, 2, 3), format.args = list(decimal.mark = ","), caption = "Relativos de preços (cinco produtos)", col.names = c("Produtos", "Mês 0 ($u.m.$)", "Mês 1 ($u.m.$)", "$p_1^i/p_0^i$")) ``` \normalsize \framebreak - Aplicando a fórmula do Índice de preços de Sauerbeck aos relativos de preços da última coluna da tabela acima, obtemos: $$ I_{01}^S = \frac{5,4}{5} = 1,08, $$ isto é, o aumento médio dos preços dos cinco produtos foi da ordem de 8% no mês atual relativamente ao mês-base. \framebreak ### Observações - O índice de preços de Sauerbeck não é afetado pelas unidades de medidas em que estão expressos os preços + __Sua vez:__ recalcule o $I^S_{01}$ utilizando o preço referente a meia garrafa de cerveja. - Todos os produtos têm a mesma importância relativa dentro do conjunto de bens e serviços no cálculo do $I^S_{01}$. - Poderemos obter diferentes resultados se utilizarmos outros conceitos de média. + __Sua vez:__ calcule a média harmônica ($H_{01}$) e a média geométrica ($G_{01}$) dos relativos de preços dos cinco produtos do exemplo. Utilize quatro casas decimais para concluir que $H_{01} \leq G_{01} \leq I^S_{01}$. ## Próxima aula - Principais fórmulas de cálculo de números índices. ## Por hoje é só! \begin{center} {\bf Bons estudos!} \end{center} ```{r echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='50%', out.height='50%', paged.print=FALSE, purl=FALSE} knitr::include_graphics(here::here('images', 'Statistically-Insignificant-final05.jpg')) ``` <file_sep>## ----echo=FALSE, fig.align='center', message=FALSE, warning=FALSE, out.width='50%', out.height='50%', paged.print=FALSE---- knitr::include_graphics(here::here('images', 'lofi_02.jpg')) <file_sep>library(ggplot2) library(MASS) set.seed(1000) x <- data.frame(X = runif(n = 500, min = 0.1, max = 100)) x$Y <- log(x$X) + rnorm(500, sd = 0.5) p2 <- ggplot(data = x, mapping = aes(x = X, y = Y)) + geom_point(alpha = 0.5) + theme_bw() rho <- cbind(c(1, 0), c(0, 1)) x <- as.data.frame(mvrnorm(n = 500, mu = c(0,0), Sigma = rho)) names(x) <- c("X", "Y") p1 <- ggplot(data = x, mapping = aes(x = X, y = Y)) + geom_point(alpha = 0.5) + ylim(-3,3) + xlim(-3,3) + theme_bw() rho <- cbind(c(1, .5), c(.5, 1)) x <- as.data.frame(mvrnorm(n = 500, mu = c(0,0), Sigma = rho)) names(x) <- c("X", "Y") p3 <- ggplot(data = x, mapping = aes(x = X, y = Y)) + geom_point(alpha = 0.5) + ylim(-3,3) + xlim(-3,3) + theme_bw() rho <- cbind(c(1, -.3), c(-.3, 1)) x <- as.data.frame(mvrnorm(n = 500, mu = c(0,0), Sigma = rho)) names(x) <- c("X", "Y") p4 <- ggplot(data = x, mapping = aes(x = X, y = Y)) + geom_point(alpha = 0.5) + ylim(-3,3) + xlim(-3,3) + theme_bw() library(cowplot) plot_grid(p2, p3, p4, p1, labels = letters[1:4], label_size = 12, ncol = 2) library(dplyr) library(lubridate) library(readxl) library(knitr) library(kableExtra) prod <- c("Café", "Açúcar", "Arroz", "Feijão", "Batata", "Cébola") mes0 <- c(136, 89, 102, 186, 49, 68) mes1 <- c(182, 95, 106, 250, 66, 78) quantidade0 <- c(1, 1.5, 2, 3.5, 1.5, 1) quantidade1 <- c(2.5, 1, 3.5, 4.5, 5, 3) vinte_df <- data.frame(prod, mes0, quantidade0, mes1, quantidade1) vinte_df <- vinte_df %>% transform(pq0 = mes0 * quantidade0, pq1 = mes1 * quantidade1) %>% transform(w0 = pq0/sum(pq0), w1 = pq1/sum(pq1)) %>% transform(rel = mes1/mes0, inv_rel = mes0/mes1) %>% transform(relw0 = rel * w0, inv_rel_w1 = inv_rel * w1) vinte_df <- vinte_df[names(vinte_df)[c(1,2,3,8,4,5,9,10,12,11,13)]] vinte_df %>% kable(escape = F, format = "latex", align = c('l', rep('c', 10)), digits = c(0, 0, 1, 2, 0, 1, 2, 3, 3, 3, 3), format.args = list(decimal.mark = ","), caption = "Preços, quantidades, importâncias relativas e relativos de preços de produtos de alimentação", col.names = c("Produtos ($i$)", "$p_0^i$ ($u.m.$)", "$q_0^i$", "$w_0^i$", "$p_1^i$ ($u.m.$)", "$q_1^i$", "$w_1^i$", "$p_1/p_0$", "$(p_1/p_0)w_0$", "$p_0/p_1$", "$(p_0/p_1)w_1$")) dist <- c(2375, 1400, 1250, 2325, 985, 2025) preco <- c(430, 272, 252, 422, 207, 373) plot(dist, preco, xlab = "Distância (em milhas)", ylab = "Preço (em dólares)", pch = 16, col = "purple") abline(v = seq(1000, 2400, by = 200), lty = 2, col = "lightgrey") abline(h = seq(200, 400, by = 50), lty = 2, col = "lightgrey") cor(dist, preco) z_dist <- (dist - mean(dist)) / sd(dist) z_preco <- (preco - mean(preco)) / sd(preco) sum(z_dist * z_preco)/(length(z_dist) - 1) prop.tab <- matrix(data = c(30, 35, 35, 100, 60, 25, 15, 100), nrow = 2, byrow = T) %>% prop.table(margin = 2) %>% addmargins(margin = 1) row.names(prop.tab)[3] <- "Total" colnames(prop.tab)[4] <- c("Total") kable(prop.tab, digits = 0, caption = "Distribuição conjunta das frequências relativas (em porcentagem) em relação ao total geral das variáveis grau de instrução e região de procedência.") %>% add_header_above(c("Região de Procedência", "Grau de Instrução" = 3, " "))
9e8615839d1361b9690b32c59085ffeeccc91b07
[ "Markdown", "R", "RMarkdown" ]
49
RMarkdown
rdosreis/MAT02018
4e8e0ba81bd19de67a6f68ef8866d5389b6f42b8
7dbb658308b75997b14fe010fdc3c029d22819ca
refs/heads/master
<file_sep># Safari extension demo repo Demonstrates UserDefaults in macOS app (in Swift) combined with localStorage in extension. <file_sep>// // SafariExtensionHandler.swift // yeehah_extension // // Created by <NAME> on 22/05/2020. // import SafariServices class SafariExtensionHandler: SFSafariExtensionHandler { override func messageReceived(withName messageName: String, from page: SFSafariPage, userInfo: [String : Any]?) { // This method will be called when a content script provided by your extension calls safari.extension.dispatchMessage("message"). NSLog("The extension received a message (\(messageName)) with userInfo (\(userInfo ?? [:]))") if messageName == "UDGetItem" { if let unwrappedUserInfo = userInfo as? [String : String] { let key = unwrappedUserInfo["key"]! let value = UserDefaults.standard.string(forKey: key) page.dispatchMessageToScript(withName: "UDGetItem", userInfo: ["key": key, "value": value as Any]) NSLog("\(messageName) for \(key)") } } if messageName == "UDSetItem" { if let unwrappedUserInfo = userInfo as? [String : String] { let key = unwrappedUserInfo["key"]! let value = unwrappedUserInfo["value"]! UserDefaults.standard.set(value, forKey: key) page.dispatchMessageToScript(withName: "UDSetItem", userInfo: ["key": key, "value": value as Any]) NSLog("\(messageName) for \(key) with \(value)") } } if messageName == "UDRemoveItem" { if let unwrappedUserInfo = userInfo as? [String : String] { let key = unwrappedUserInfo["key"]! UserDefaults.standard.removeObject(forKey: key) page.dispatchMessageToScript(withName: "UDRemoveItem", userInfo: ["key": key]) NSLog("\(messageName) for \(key)") } } } override func toolbarItemClicked(in window: SFSafariWindow) { // This method will be called when your toolbar item is clicked. NSLog("The extension's toolbar item was clicked") // open url let url = NSURL(string: "https://whotargets.me/en/")! as URL window.openTab(with: url, makeActiveIfPossible: true) // btw, this would open it in the default browser e.g. firefox // NSWorkspace.shared.open(url) } override func validateToolbarItem(in window: SFSafariWindow, validationHandler: @escaping ((Bool, String) -> Void)) { // This is called when Safari's state changed in some way that would require the extension's toolbar item to be validated again. validationHandler(true, "") } override func popoverViewController() -> SFSafariExtensionViewController { return SafariExtensionViewController.shared } }
0a54c7835c6bf36cd7030b0174818e5f5f7efc03
[ "Markdown", "Swift" ]
2
Markdown
skinofstars/yeehah-safari-extension
dc028f77b41022e5f84479bcdfac88967a5bc8e6
d459a37538677a7ba27d0e16eaf45ac71ec19177
refs/heads/master
<repo_name>alvtdev/BoilKettlePi<file_sep>/src/output.cpp /****************************************************************************** * Author: <NAME> * Date : 5/21/2017 * * Output is a state machine that polls all other state machines for data and * outputs them accordingly *****************************************************************************/ #include "task.hpp" #include "output.hpp" #include <iostream> #include <stdlib.h> #include <fstream> Output::Output(int ms, Temperature* t, Pressure* p, Sonar* s, Calcgrav* cg, Heater* h) : Task(ms) { this->t = t; this->p = p; this->s = s; this->cg = cg; this->h = h; pollCountMax = (1000/ms); outputTimeHours = 0; outputTimeMinutes = 0; outputTimeSeconds = 0; } void Output::poll_Data() { temperature = t->get_temperature(); pressure = p->get_pressure(); dist = s->get_distance(); specGravBegin = cg->get_specGravBegin(); timeLeft = h->get_timeLeft_seconds(); } void Output::calc_outputTimes() { unsigned int tempTimeLeft = h->get_timeLeft_seconds(); //std::cout << tempTimeLeft << std::endl; if (tempTimeLeft > 3600) { outputTimeHours = (tempTimeLeft / 3600); tempTimeLeft -= (outputTimeHours * 3600); } else { outputTimeHours = 0; } if (tempTimeLeft > 60) { outputTimeMinutes = (tempTimeLeft / 60); tempTimeLeft -= (outputTimeMinutes * 60); } else { outputTimeMinutes = 0; } outputTimeSeconds = tempTimeLeft; } void Output::output_Data() { if (timeLeft > 0) { /* std::cout << "Total Boil Time: " << h->get_boilTime() << " s \n"; std::cout << "Timer Time: " << h->get_timerSeconds() << " s \n"; */ std::cout << "Boil Time Left: " << outputTimeHours << " hrs, " << outputTimeMinutes << " min, " << outputTimeSeconds << " s" << std::endl; } else if (timeLeft == 0) { std::cout << "Boil Status: Finished." << std::endl; } else if (timeLeft < 0) { //std::cout << "Boil Status: Waiting to start." << std::endl; } std::cout << "Temperature: " << temperature << " F" << std::endl; std::cout << "Pressure: " << pressure << " Pa" << std::endl; std::cout << "Water depth: " << dist << " cm" << std::endl; if (specGravBegin == -1) { std::cout << "Density: N/A" << std::endl; } else { std::cout << "Density: " << specGravBegin << " g/cm^3" << std::endl; } std::cout << std::endl; } void Output::output_to_file() { ofstream outFile("output.txt"); if (outFile.is_open()) { if (timeLeft > 0) { outFile << "Boil Time Left: " << outputTimeHours << " hrs, " << outputTimeMinutes << " min, " << outputTimeSeconds << " s \n"; } else if (timeLeft == 0) { outFile << "Boil Status: Finished \n"; } else if (timeLeft == -1) { if (h->get_fullStatus() == -1) { outFile << "Boil Status: Waiting to be Full \n"; } else if (h->get_fullStatus() == 1) { outFile << "Boil Status: Heating\n"; } } else if (timeLeft < -5) { outFile << "Boil Status: Finished\n"; } outFile << "Temperature: " << temperature << " F \n"; outFile << "Pressure: " << pressure << " Pa \n"; outFile << "Water Depth: " << dist << " cm \n"; outFile << "Density: " << specGravBegin << " g/cm^3 \n"; } else { std::cout << "Error opening output.txt" << std::endl; } } int Output::tick_function() { /* State transitions */ switch(state) { case INIT: state = POLL; break; case POLL: if (pollCount >= pollCountMax-1) { pollCount = 0; state = OUT; } else { state = POLL; } break; case OUT: state = POLL; break; default: state = INIT; break; } /* State actions */ switch(state) { case INIT: break; case POLL: poll_Data(); pollCount++; break; case OUT: calc_outputTimes(); // output_Data(); output_to_file(); break; default: break; } return 0; } <file_sep>/inc/calcgrav.hpp /****************************************************************************** * Author: <NAME> * Date : 5/2/2017 * Calcgrav is a state machine that obtains pressure and depth readings from * the pressure and depth state machines, then uses those values to calculate * the specific gravity of the fluid inside the boil kettle *****************************************************************************/ #ifndef CALCGRAV_HPP #define CALCGRAV_HPP #include "task.hpp" #include "pressure.hpp" #include "sonar.hpp" //TODO: modify class to include depth SM in constructor and as private member class Calcgrav : public Task { public: Calcgrav(int ms, Pressure* pres, Sonar* s); double get_specGravBegin(); double get_specGravEnd(); private: Pressure* pres; Sonar* s; //other class pointers needed: depth double specGravBegin; double specGravEnd; enum States { INIT, WAIT, GRAV_BEGIN, GRAV_END } state; double calc_specific_gravity(); virtual int tick_function(); }; #endif <file_sep>/inc/pressure.hpp /****************************************************************************** * Author: <NAME> * Date : 4/30/2017 * State machine that polls for pressure. *****************************************************************************/ #ifndef PRESSURE_HPP #define PRESSURE_HPP #include "task.hpp" #include <wiringPi.h> class Pressure : public Task { public: Pressure(int ms); double get_pressure(); private: enum States {INIT, WAIT, GP} state; //GP = get pressure double pres; //stores pressure value from reading double poll_pressure(); virtual int tick_function(); }; #endif <file_sep>/src/temperature.cpp #include "task.hpp" #include "temperature.hpp" #include <iostream> #include <wiringPi.h> #include "ads1115.h" Temperature::Temperature(int ms) : Task(ms) { state = INIT; temperature = 0; } double Temperature::get_temperature() { return temperature; } double Temperature::poll_temperature() { double ttemp = analogRead(2222); //TODO: perform conversion from voltage reading to temperature value ttemp = (((ttemp*4.098)/32767.0) - 0.5)*100.0; // temperature in celsius ttemp = ttemp*(9.0/5.0) + 32.0; // convert celsius to fahrenheit return ttemp; } int Temperature::tick_function() { /* State transitions */ switch(state) { case INIT: state = WAIT; break; case WAIT: state = GT; break; case GT: state = WAIT; break; default: state = INIT; break; } /* State actions */ switch(state) { case INIT: break; case WAIT: //test output break; case GT: temperature = poll_temperature(); // std::cout << "Temperature: " << temperature << " F" << endl; break; default: break; } } <file_sep>/inc/temperature.hpp /****************************************************************************** * Author: <NAME> * Date : 4/30/2017 * State machine that polls for temperature *****************************************************************************/ #ifndef TEMPERATURE_HPP #define TEMPERATURE_HPP #include "task.hpp" #include <wiringPi.h> class Temperature : public Task { public: Temperature(int ms); double get_temperature(); private: enum States {INIT, WAIT, GT} state; //GT = get temperature double temperature; //stores temperature value from reading double poll_temperature(); virtual int tick_function(); }; #endif <file_sep>/src/main.cpp /****************************************************************************** * Author: <NAME>, modified by <NAME> * Date : 4/26/2017 * * This main file is meant to be as minimal as possible. All state machine * definitions can be found in their appropriate header and source files. * Initialization of a state machine is handled within the constructor of * each class. *****************************************************************************/ #include "task.hpp" #include "ping.hpp" #include "heater.hpp" #include "pump.hpp" #include "pressure.hpp" #include "sonar.hpp" #include "calcgrav.hpp" #include "output.hpp" #include "timer.hpp" #include "temperature.hpp" #include "timer.h" #include <stdlib.h> #include <iostream> #include <wiringPi.h> #include "ads1115.h" int main(int argc, char* argv[]) { if (argc != 2) { std::cout << "Proper use: ./BoilKettlePi <total boil time>" << std::endl; } else { int bTimeMinutes = atoi(argv[1]); extern int timer_flag; TaskList * T = new TaskList(); if(wiringPiSetup()) return 1; /* Add new tasks here */ /* T->add_task(new Task(period_ms)); */ /* For tasks that rely on other tasks: * * Pressure p = new Pressure(period); * T->add_task(p); * T->add_task(new CalcGrav(period, &p)) ; */ //initialize adc ads1115Setup(2222, 0x48); //T->add_task(new Pressure(1000)); Pressure* p = new Pressure(500); T->add_task(p); //T->add_task(new Sonar(1000)); Sonar* s = new Sonar(500); T->add_task(s); //T->add_task(new Calcgrav(500, p, s)); Calcgrav* cg = new Calcgrav(500, p, s); T->add_task(cg); //T->add_task(new Ping(1000)); Timer* time = new Timer(1000); T->add_task(time); //T->add_task(new Temperature(1000)); Temperature* t = new Temperature(500); T->add_task(t); //T->add_task(new Heater(250, t, time)); Heater* h = new Heater(250, t, time, s, bTimeMinutes); T->add_task(h); Output* o = new Output(50, t, p, s, cg, h); T->add_task(o); if(timer_init(T->get_period_ms())) return 1; for(;;) { T->tick(); while(!timer_flag) ; timer_flag = 0; } } return 1; } <file_sep>/inc/heater.hpp /****************************************************************************** * Author: <NAME> * Date : 4/27/2017 *****************************************************************************/ #ifndef HEATER_HPP #define HEATER_HPP #include "task.hpp" #include "sonar.hpp" #include "timer.hpp" #include "temperature.hpp" #include <wiringPi.h> class Heater : public Task { public: Heater(int ms, Temperature* t, Timer* time, Sonar* s, int minutes); int get_timeLeft_seconds(); int get_boilTime(); int get_timerSeconds(); int get_fullStatus(); private: enum States { INIT, OFF, HEAT, BOIL, MAINTAIN } state; int calc_timeLeft(); void init_boilTime(int hrs, int min, int sec); //helper function for testing hard-coded boiltimes void create_boilText(); double temp; int boilTimeHrs; int boilTimeMins; int boilTimeSeconds; int timerSeconds; int timeLeft; Sonar* dist; Temperature* t; Timer* time; int heatflag; int fullflag; virtual int tick_function(); }; #endif <file_sep>/inc/timer.hpp /****************************************************************************** * Author: <NAME> * Date : 4/27/2017 * Timer is a state machine that constantly counts upward upon starting * execution of a task *****************************************************************************/ #ifndef TIMER_HPP #define TIMER_HPP #include "task.hpp" class Timer : public Task { public: Timer(int ms); void start_timer(); void stop_timer(); int get_hours(); int get_minutes(); int get_seconds(); private: enum States { INIT, OFF, ON } state; int hours; int minutes; int seconds; virtual int tick_function(); }; #endif <file_sep>/src/pressure.cpp #include "task.hpp" #include "pressure.hpp" #include <iostream> #include <wiringPi.h> #include "ads1115.h" Pressure::Pressure(int ms) : Task(ms) { state = INIT; pres = 0; } double Pressure::get_pressure() { return pres; } double Pressure::poll_pressure() { double ptemp = analogRead(2223); //perform conversion from voltage reading to pressure value //double pvol = (ptemp*5.0)/1024.0; // convert to voltage // double ppres = (3.0 * (pvol - 0.47)) * 1000000.0; //convert to voltage in pascals return ptemp; } int Pressure::tick_function() { /* State transitions */ switch(state) { case INIT: state = WAIT; break; case WAIT: state = GP; break; case GP: state = WAIT; break; default: state = INIT; break; } /* State actions */ switch(state) { case INIT: break; case WAIT: //test output break; case GP: pres = poll_pressure(); // std::cout << "Pressure: " << pres << " Pa" << std::endl; break; default: break; } } <file_sep>/main.py import time import serial import os import subprocess from tkinter import * outputFile = "output.txt" mashFile = "mashtun.txt" bmsg = "Waiting for BK" os.system('export WIRINGPI_GPIOMEM=1') #find and remove existing output.txt if (os.path.exists(outputFile)): os.remove(outputFile) #mash communication variables mashIP = "192.168.1.236" mashPort = "8080" global ser ser = None #keg communication variables ttyName = '/dev/ttyACM0' ttyAvailable = 0 #flag for ser #determins if ardino keg is connected if os.path.exists(ttyName): ttyAvailable = 1 ser = serial.Serial('/dev/ttyACM0', 9600) else: ttyAvailable = 0 #set up only if tty is available #mash time var mTime = None mTemp1 = None mTemp2 = None #boil time var bTotalTime = None bTime1 = None bTime2 = None bTime3 = None #process var global proc proc = None global procflag procflag = 0 #Output functions def getOutputs(): ftxt = open(outputFile, "r+") bmsg = ftxt.read() ftxt.close() outmsg.configure(text=bmsg) if (os.path.exists("boil.txt")): parseForReminders() afterid1 = bkui.after(1000, getOutputs) #print(afterid1) #reminder flags and functions def parseForReminders(): global firstReminderFlag global secondReminderFlag ftxt = open("boil.txt", "r+") # boil.txt tells whether or not boil has started boilMsg = ftxt.read() #print("contents of boil.txt: " + boilMsg) if boilMsg == "1": if firstReminderFlag == 1: #start timer #print("setting first timer") bkui.after(int(int(bTime2)*60000), enableFirstReminder) firstReminderFlag = 0 if secondReminderFlag == 1: #start timer #print("setting second timer") bkui.after(int(int(bTime3)*60000), enableSecondReminder) secondReminderFlag = 0 enableMainReminder() ftxt.close() os.remove("boil.txt") #print("boil.txt removed") def disableMainReminder(): mainReminderMsg.config(state=DISABLED) def enableMainReminder(): mainReminderMsg.config(state=ACTIVE) bkui.after(60000, disableMainReminder) def disableFirstReminder(): #print("disabling first reminder") firstReminderMsg.config(state=DISABLED) def enableFirstReminder(): #print("enabling first reminder") firstReminderMsg.config(state=ACTIVE) bkui.after(60000, disableFirstReminder) def disableSecondReminder(): #print("disabling second reminder") secondReminderMsg.config(state=DISABLED) def enableSecondReminder(): #print("enabling second reminder") secondReminderMsg.config(state=ACTIVE) bkui.after(60000, disableSecondReminder); #Mash Tun Menu Functions def getMashData(): #get inputs global mTime global mTemp1 global mTemp2 mTime = mashTimeEntry.get() mTemp1 = mashTemp1Entry.get() mTemp2 = mashTemp2Entry.get() #set stringvar for gui display mTimeString.set(mTime) mTemp1String.set(mTemp1) mTemp2String.set(mTemp2) #write outputs to file if mTime and mTemp1 and mTemp2: file = open(mashFile, 'w+') file.write("%s %s %s" % (mTemp1, mTemp2, mTime)) file.close() #send data to mash using netcat commandString = "cat mashtun.txt | nc -w 3 " + mashIP + " " + mashPort #print(commandString) os.system(commandString) os.remove(mashFile) #Boil Kettle Menu Functions def getBoilTimes(): #get boil times global bTime1 global bTime2 global bTime3 global bTotalTime bTime1 = bkTime1Entry.get() bTime2 = bkTime2Entry.get() bTime3 = bkTime3Entry.get() bTotalTime = int(bTime1) #set stringvars for gui display bTime1String.set(bTime1) bTime2String.set(bTime2) bTime3String.set(bTime3) bTotalTimeString.set(bTotalTime) def startBoil(): global firstReminderFlag global secondReminderFlag file = open(outputFile, 'w+') file.close() os.system('export WIRINGPI_GPIOMEM=1') global proc proc = subprocess.Popen(['./BoilKettlePi', str(bTotalTime)]) pid = proc.pid global procflag procflag = 1 if bTime2: #print("setting first flag") firstReminderFlag = 1 else: firstReminderFlag = 0 if bTime3: #print("setting second flag") secondReminderFlag = 1 else: secondReminderFlag = 0 return #Keg menu functions def sendDrinkName(): drinkNameString = kegDrinkEntry.get() drinkName.set(drinkNameString) if not ser.isOpen(): ser.open() ser.flushInput() ser.flushOutput() #drinkNameString = drinkNameString + "!" time.sleep(4) ser.write(drinkNameString.encode()) #print("sending: " + str(drinkNameString.encode())) time.sleep(2) #test arduino code #drinkNameReceive = ser.readline() #ser.write(drinkNameString.encode()) #ser.write(drinkNameString.encode()) ##print("received " + drinkNameReceive.decode()) #Page navigation helper functions def goToMenuPage(): menu_page.tkraise() def goToBkPage(): bk_page.tkraise() def goToBkConfPage(): getBoilTimes() bkConf_page.tkraise() def goToOutPage(): startBoil() getOutputs() out_page.tkraise() def goToMtPage(): mt_page.tkraise() def goToMtSentPage(): getMashData() mtSent_page.tkraise() def goToKegPage(): keg_page.tkraise() def goToKegSentPage(): sendDrinkName() kegSent_page.tkraise() def exitbk(): if (procflag == 1): proc.terminate() os.remove(outputFile) exit(0) bkui = Tk() bkui.attributes("-fullscreen",True) bkui.title("BoilKettlePi") #init bkui config to account for resizing bkui.grid_columnconfigure(0, weight=1) bkui.grid_rowconfigure(0, weight=1) #declare pages menu_page = Frame(bkui) bk_page = Frame(bkui) bkConf_page = Frame(bkui) out_page = Frame(bkui) mt_page = Frame(bkui) mtSent_page = Frame(bkui) keg_page = Frame(bkui) kegSent_page = Frame(bkui) #init config for all pages for frame in (menu_page, bk_page, bkConf_page, out_page, mt_page, mtSent_page, keg_page, kegSent_page): frame.grid(row=0, column=0, sticky=N+S+E+W) frame.grid_columnconfigure(0, weight=1) frame.grid_rowconfigure(0, weight=1) #MENU PAGE - (menu_page) #PAGE CONFIG colwidth = int(bkui.winfo_screenwidth()/6) menu_page.grid_columnconfigure(0, weight=1) menu_page.grid_columnconfigure(1, weight=1) menu_page.grid_columnconfigure(2, weight=1) menu_page.grid_columnconfigure(3, weight=1) menu_page.grid_columnconfigure(4, weight=1) menu_page.grid_rowconfigure(0, weight=1) menu_page.grid_rowconfigure(1, weight=1) menu_page.grid_rowconfigure(2, weight=1) menu_page.grid_rowconfigure(3, weight=1) menu_page.grid_rowconfigure(4, weight=1) #BUTTONS AND PROMPTS mtConfig = Button(menu_page, text="MashTun Settings", width=colwidth, command=goToMtPage) btConfig = Button(menu_page, text="BoilKettle Settings", width=colwidth, command=goToBkPage) kegConfig = Button(menu_page, text="Keg Settings", width=colwidth, command=goToKegPage) exitMenu = Button(menu_page, text='Exit', width=colwidth, command=exitbk) emptyLabel = Label(menu_page, text=' ', width=colwidth) menuMsg = Label(menu_page, text="ome to BoilKe", font=("TkDefaultFont", 18)) menuMsg1 = Label(menu_page, text = "Welc", font=("TkDefaultFont",18)) menuMsg2 = Label(menu_page, text = "ttlePi", font=("TkDefaultFont", 18)) mtConfig.grid(row=4, column=0, sticky=N+S+E+W) btConfig.grid(row=4, column=1, sticky=N+S+E+W) kegConfig.grid(row=4, column=2, sticky=N+S+E+W) emptyLabel.grid(row=4, column=3, sticky=N+S+E+W) exitMenu.grid(row=4, column=4, sticky=N+S+E+W) menuMsg.grid(row=2, column=2, sticky=N+S+E+W) menuMsg1.grid(row=2, column=1, sticky=N+S+E) menuMsg2.grid(row=2, column=3, sticky=N+S+W) if ttyAvailable == 0: kegConfig.config(state=DISABLED) elif ttyAvailable == 1: kegConfig.config(state=ACTIVE) #BOIL KETTLE PAGE - (bk_page) #PAGE CONFIG bk_page.grid_columnconfigure(0, weight=1) bk_page.grid_columnconfigure(1, weight=1) bk_page.grid_columnconfigure(2, weight=1) bk_page.grid_rowconfigure(0, weight=1) bk_page.grid_rowconfigure(1, weight=1) bk_page.grid_rowconfigure(2, weight=1) bk_page.grid_rowconfigure(3, weight=1) bk_page.grid_rowconfigure(4, weight=1) #prompts and entries bkSettings = Message(bk_page, text="BoilKettle Settings", width = 10000) bkTime1 = Label(bk_page, text="Total Boil Time:") bkTime1Entry = Entry(bk_page) bkTime1Units = Label(bk_page, text="minutes") bkTime2 = Label(bk_page, text="1st reminder at:") bkTime2Entry = Entry(bk_page) bkTime2Units = Label(bk_page, text="minutes") bkTime3 = Label(bk_page, text="2nd reminder at:") bkTime3Entry = Entry(bk_page) bkTime3Units = Label(bk_page, text="minutes") #navigation buttons confirmBK = Button(bk_page, text="Confirm", command=goToBkConfPage) btsBK = Button(bk_page, text='Menu', command=goToMenuPage) exitBK = Button(bk_page, text='Exit', command=exitbk) bkSettings.grid(row=0, column=1, sticky=N+S+E+W) bkTime1.grid(row=1, column=0, sticky=N+S+E+W) bkTime1Entry.grid(row=1, column=1, sticky=N+S+E+W) bkTime1Units.grid(row=1, column=2, sticky=N+S+E+W) bkTime2.grid(row=2, column=0, sticky=N+S+E+W) bkTime2Entry.grid(row=2, column=1, sticky=N+S+E+W) bkTime2Units.grid(row=2, column=2, sticky=N+S+E+W) bkTime3.grid(row=3, column=0, sticky=N+S+E+W) bkTime3Entry.grid(row=3, column=1, sticky=N+S+E+W) bkTime3Units.grid(row=3, column=2, sticky=N+S+E+W) btsBK.grid(row=4, column=0, sticky=N+S+E+W) confirmBK.grid(row=4, column=1, sticky=N+S+E+W) exitBK.grid(row=4, column=2, sticky=N+S+E+W) #BOIL KETTLE CONFIRMATION PAGE (bkConf_page #PAGE CONFIG bkConf_page.grid_columnconfigure(0, weight=1) bkConf_page.grid_columnconfigure(1, weight=1) bkConf_page.grid_columnconfigure(2, weight=1) bkConf_page.grid_rowconfigure(0, weight=1) bkConf_page.grid_rowconfigure(1, weight=1) bkConf_page.grid_rowconfigure(2, weight=1) bkConf_page.grid_rowconfigure(3, weight=1) bkConf_page.grid_rowconfigure(4, weight=1) #BUTTONS AND PROMPTS bTime1String = StringVar() bTime2String = StringVar() bTime3String = StringVar() bTotalTimeString = StringVar() bkConfSettings = Message(bkConf_page, text="Confirm BoilKettle Settings", width = 10000) #bkConfTime1 = Label(bkConf_page, text="Initial Boil:") #bkConfTime1Entry = Label(bkConf_page, textvariable=bTime1String) #bkConfTime1Units = Label(bkConf_page, text="minutes") bkConfTime2 = Label(bkConf_page, text="1st reminder at:") bkConfTime2Entry = Label(bkConf_page, textvariable=bTime2String) bkConfTime2Units = Label(bkConf_page, text="minutes") bkConfTime3 = Label(bkConf_page, text="2nd reminder at:") bkConfTime3Entry = Label(bkConf_page, textvariable=bTime3String) bkConfTime3Units = Label(bkConf_page, text="minutes") bkConfTotalTime = Label(bkConf_page, text="Total Boil Time:") bkConfTotalTimeEntry = Label(bkConf_page, textvariable=bTotalTimeString) bkConfTotalTimeUnits = Label(bkConf_page, text="minutes") #navigation buttons menuBKConf = Button(bkConf_page, text="Back", command=goToBkPage) startBKConf = Button(bkConf_page, text="Start Boil", command=goToOutPage) exitBKConf = Button(bkConf_page, text='Exit', command=exitbk) bkConfSettings.grid(row=0, column=1, sticky=N+S+E+W) #bkConfTime1.grid(row=1, column=0, sticky=N+S+E+W) #bkConfTime1Entry.grid(row=1, column=1, sticky=N+S+E+W) #bkConfTime1Units.grid(row=1, column=2, sticky=N+S+E+W) bkConfTotalTime.grid(row=1, column=0, sticky=N+S+E+W) bkConfTotalTimeEntry.grid(row=1, column=1, sticky=N+S+E+W) bkConfTotalTimeUnits.grid(row=1, column=2, sticky=N+S+E+W) bkConfTime2.grid(row=2, column=0, sticky=N+S+E+W) bkConfTime2Entry.grid(row=2, column=1, sticky=N+S+E+W) bkConfTime2Units.grid(row=2, column=2, sticky=N+S+E+W) bkConfTime3.grid(row=3, column=0, sticky=N+S+E+W) bkConfTime3Entry.grid(row=3, column=1, sticky=N+S+E+W) bkConfTime3Units.grid(row=3, column=2, sticky=N+S+E+W) menuBKConf.grid(row=4, column=0, sticky=N+S+E+W) startBKConf.grid(row=4, column=1, sticky=N+S+E+W) exitBKConf.grid(row=4, column=2, sticky=N+S+E+W) #output page - (out_page) #PAGE CONFIG out_page.grid_columnconfigure(0, weight=1) out_page.grid_columnconfigure(1, weight=2) out_page.grid_columnconfigure(2, weight=1) out_page.grid_rowconfigure(0, weight=1) out_page.grid_rowconfigure(1, weight=1) out_page.grid_rowconfigure(2, weight=1) out_page.grid_rowconfigure(3, weight=1) out_page.grid_rowconfigure(4, weight=1) exitOut = Button(out_page, text='Exit', command=exitbk) outmsg = Message(out_page, text=bmsg, font=("TkDefaultFont", 16), width=10000) mainReminderMsg = Label(out_page, text="ADD FIRST INGREDIENT", state=DISABLED) firstReminderMsg = Label(out_page, text="ADD SECOND INGREDIENT", state=DISABLED) secondReminderMsg = Label(out_page, text="ADD THIRD INGREDIENT", state=DISABLED) outmsg.grid(row=1, column=1, sticky=N+S+E+W) mainReminderMsg.grid(row=2, column=0) firstReminderMsg.grid(row=2, column=1) secondReminderMsg.grid(row=2, column=2) exitOut.grid(row=4, column=2, sticky=N+S+E+W) #MT PAGE - (mt_page) #PAGE CONFIG mt_page.grid_columnconfigure(0, weight=1) mt_page.grid_columnconfigure(1, weight=1) mt_page.grid_columnconfigure(2, weight=1) mt_page.grid_rowconfigure(0, weight=1) mt_page.grid_rowconfigure(1, weight=1) mt_page.grid_rowconfigure(2, weight=1) mt_page.grid_rowconfigure(3, weight=1) mt_page.grid_rowconfigure(4, weight=1) mt_page.grid_rowconfigure(5, weight=1) #prompts and entries mtSettings = Label(mt_page, text="Mash Tun Settings:") mashTime = Label(mt_page, text="Mash Time:") mashTimeEntry = Entry(mt_page) mashTimeUnits = Label(mt_page, text="minutes") mashTemp1 = Label(mt_page, text="Mash Temperature:") mashTemp1Entry = Entry(mt_page) mashTemp1Units = Label(mt_page, text="\xb0F") mashTemp2 = Label(mt_page, text="Sparge Temperature:") mashTemp2Entry = Entry(mt_page) mashTemp2Units = Label(mt_page, text="\xb0F") #navigation buttons btsMT = Button(mt_page, text='Menu', command=goToMenuPage) sendMTData = Button(mt_page, text="Send to Mash Tun", command=goToMtSentPage) exitMT = Button(mt_page, text='Exit', command=exitbk) mtSettings.grid(row=0, column=1, sticky=N+S+E+W) mashTime.grid(row=1, column=0, sticky=N+S+E+W) mashTimeEntry.grid(row=1, column=1, sticky=N+S+E+W) mashTimeUnits.grid(row=1, column=2, sticky=N+S+E+W) mashTemp1.grid(row=2, column=0, sticky=N+S+E+W) mashTemp1Entry.grid(row=2, column=1, sticky=N+S+E+W) mashTemp1Units.grid(row=2, column=2, sticky=N+S+E+W) mashTemp2.grid(row=3, column=0, sticky=N+S+E+W) mashTemp2Entry.grid(row=3, column=1, sticky=N+S+E+W) mashTemp2Units.grid(row=3, column=2, sticky=N+S+E+W) btsMT.grid(row=5, column=0, sticky=N+S+E+W) sendMTData.grid(row=5, column=1, sticky=N+S+E+W) exitMT.grid(row=5, column=2, sticky=N+S+E+W) #MT SENT PAGE - (mtSent_page) #PAGE CONFIG mtSent_page.grid_columnconfigure(0, weight=1) mtSent_page.grid_columnconfigure(1, weight=1) mtSent_page.grid_columnconfigure(2, weight=1) mtSent_page.grid_rowconfigure(0, weight=1) mtSent_page.grid_rowconfigure(1, weight=1) mtSent_page.grid_rowconfigure(2, weight=1) mtSent_page.grid_rowconfigure(3, weight=1) mtSent_page.grid_rowconfigure(4, weight=1) mtSent_page.grid_rowconfigure(5, weight=1) #stringvars to store display user input mTimeString = StringVar() mTemp1String = StringVar() mTemp2String = StringVar() btsMTSent = Button(mtSent_page, text='Menu', command=goToMenuPage) mtSentMsg = Message(mtSent_page, text="MT Info Sent:", width=10000) mtSentTime = Label(mtSent_page, text="Mash Time:") mtSentTimeEntry = Label(mtSent_page, textvariable=mTimeString) mtSentTimeUnits = Label(mtSent_page, text="minutes") mtSentTemp1 = Label(mtSent_page, text="Mash Temperature:") mtSentTemp1Entry = Label(mtSent_page, textvariable=mTemp1String) mtSentTemp1Units = Label(mtSent_page, text="\xb0F") mtSentTemp2 = Label(mtSent_page, text="Mash Temperature:") mtSentTemp2Entry = Label(mtSent_page, textvariable=mTemp2String) mtSentTemp2Units = Label(mtSent_page, text="\xb0F") mtSentMsg.grid(row=0, column=1, sticky=N+S+E+W) mtSentTime.grid(row=1, column=0, sticky=N+S+E+W) mtSentTimeEntry.grid(row=1, column=1, sticky=N+S+E+W) mtSentTimeUnits.grid(row=1, column=2, sticky=N+S+E+W) mtSentTemp1.grid(row=2, column=0, sticky=N+S+E+W) mtSentTemp1Entry.grid(row=2, column=1, sticky=N+S+E+W) mtSentTemp1Units.grid(row=2, column=2, sticky=N+S+E+W) mtSentTemp2.grid(row=3, column=0, sticky=N+S+E+W) mtSentTemp2Entry.grid(row=3, column=1, sticky=N+S+E+W) mtSentTemp2Units.grid(row=3, column=2, sticky=N+S+E+W) btsMTSent.grid(row=5, column=1, sticky=N+S+E+W) #KEG PAGE - keg_page #PAGE CONFIG keg_page.grid_columnconfigure(0, weight=1) keg_page.grid_columnconfigure(1, weight=1) keg_page.grid_columnconfigure(2, weight=1) keg_page.grid_rowconfigure(0, weight=1) keg_page.grid_rowconfigure(1, weight=1) keg_page.grid_rowconfigure(2, weight=1) keg_page.grid_rowconfigure(3, weight=1) keg_page.grid_rowconfigure(4, weight=1) keg_page.grid_rowconfigure(5, weight=1) #BUTTONS AND PROMPTS drinkName = StringVar() menuKeg = Button(keg_page, text="Menu", command=goToMenuPage) kegSettingsPrompt = Label(keg_page, text="Keg Settings") kegDrinkPrompt = Label(keg_page, text="Drink Name:") kegDrinkEntry = Entry(keg_page) kegSendDrinkName = Button(keg_page, text="Send Keg Name", command=goToKegSentPage) kegSettingsPrompt.grid(row=0, column=1, sticky=N+S+E+W) menuKeg.grid(row=5, column=0, sticky=N+S+E+W) kegDrinkPrompt.grid(row=2, column=0, sticky=N+S+E+W) kegDrinkEntry.grid(row=2, column=1, sticky=N+S+E+W) kegSendDrinkName.grid(row=2, column=2, sticky=N+S+E+W) #KEG SENT PAGE - kegSent_page #PAGE CONFIG kegSent_page.grid_columnconfigure(0, weight=1) kegSent_page.grid_columnconfigure(1, weight=1) kegSent_page.grid_columnconfigure(2, weight=1) kegSent_page.grid_rowconfigure(0, weight=1) kegSent_page.grid_rowconfigure(1, weight=1) kegSent_page.grid_rowconfigure(2, weight=1) kegSent_page.grid_rowconfigure(3, weight=1) kegSent_page.grid_rowconfigure(4, weight=1) menuKegSent = Button(kegSent_page, text="Menu", command=goToMenuPage) kegSentMsg = Label(kegSent_page, text="Drink Name Sent:") kegSentDrink = Label(kegSent_page, textvariable=drinkName) menuKegSent.grid(row=4, column=1, sticky=N+S+E+W) kegSentMsg.grid(row=1, column=1, sticky=N+S+E+W) kegSentDrink.grid(row=2, column=1, sticky=N+S+E+W) menu_page.tkraise() bkui.mainloop() <file_sep>/src/pump.cpp /****************************************************************************** * Author: <NAME> * Date : 4/27/2017 *****************************************************************************/ #include "task.hpp" #include "pump.hpp" #include <wiringPi.h> #include <iostream> Pump::Pump(int ms) : Task(ms) { pinMode(3, OUTPUT); digitalWrite(3, LOW); state = INIT; } int Pump::tick_function() { /* State transitions */ switch(state) { case INIT: state = ON; break; case ON: state = OFF; break; case OFF: state = ON; break; default: state = INIT; break; } /* State actions */ switch(state) { case INIT: digitalWrite(3, LOW); break; case ON: digitalWrite(3, HIGH); break; case OFF: digitalWrite(3, LOW); break; default: break; } return 0; } <file_sep>/README.md # BoilKettlePi Automated boil kettle controller on the RaspberryPi ## WiringPi CMake issues Add the following file, named `FindWiringPi.cmake` to the directory `/usr/share/cmake-x.x/Modules`: ``` find_library(WIRINGPI_LIBRARIES NAMES wiringPi) find_path(WIRINGPI_INCLUDE_DIRS NAMES wiringPi.h) include(FindPackageHandleStandardArgs) find_package_handle_standard_args(wiringPi DEFAULT_MSG WIRINGPI_LIBRARIES WIRINGPI_INCLUDE_DIR) ``` <file_sep>/src/heater.cpp /****************************************************************************** * Author: <NAME> * Date : 4/27/2017 * Modified on 5/8 by <NAME> *****************************************************************************/ #include "task.hpp" #include "heater.hpp" #include <wiringPi.h> #include <iostream> #include <fstream> #include <stdio.h> #include <stdlib.h> Heater::Heater(int ms, Temperature* t, Timer* time, Sonar* s, int minutes) : Task(ms) { pinMode(6, OUTPUT); digitalWrite(6, LOW); state = INIT; this->t = t; this->time = time; this->dist = s; temp = t->get_temperature(); heatflag = -1; fullflag = -1; boilTimeHrs = 0; boilTimeMins = 0; boilTimeSeconds = 60*minutes; timerSeconds = 0; timeLeft = -1; } int Heater::get_timeLeft_seconds() { return timeLeft; } int Heater::calc_timeLeft() { timeLeft = boilTimeSeconds - timerSeconds; return timeLeft; } int Heater::get_boilTime() { return boilTimeSeconds; } int Heater::get_timerSeconds() { return timerSeconds; } int Heater::get_fullStatus() { return fullflag; } void Heater::init_boilTime(int hrs, int min, int sec) { boilTimeSeconds = sec + 60*min + 3600*hrs; return; } void Heater::create_boilText() { ofstream outfile("boil.txt"); if (outfile.is_open()) { outfile << "1"; } //std::cout << "boil.txt created" << std::endl; return; } int Heater::tick_function() { int temptime = 0; /* State transitions */ switch(state) { case INIT: state = OFF; break; case OFF: //state waits for boil kettle to fill before heating if (heatflag != -1) { if (dist->get_distance() > BK_MAX_HEIGHT_CM/2) { fullflag = 1; state = HEAT; //std::cout << "state = HEAT" << std::endl; } else { fullflag = -1; state = OFF; //std::cout << "state = OFF" << std::endl; } } break; case HEAT: if (temp >= 200.0) { time->start_timer(); create_boilText(); state = BOIL; //std::cout << "state = BOIL" << std::endl; } else { state = HEAT; } break; case BOIL: if (calc_timeLeft() <= 0) { time->stop_timer(); timeLeft = -10; //std::cout << "state = MAINTAIN" << std::endl; state = MAINTAIN; } else { state = BOIL; } break; case MAINTAIN: break; default: state = INIT; break; } /* State actions */ switch(state) { case INIT: break; case OFF: //init_boilTime(1, 0, 10); digitalWrite(6, LOW); heatflag = 1; break; case HEAT: digitalWrite(6, HIGH); temp = t->get_temperature(); break; case BOIL: timerSeconds = time->get_seconds(); temptime = calc_timeLeft(); /* std::cout << "Boil time: " << boilTimeSeconds << std::endl; std::cout << "Timer: " << timerSeconds << std::endl; std::cout << "Time Left: " << calc_timeLeft() << std::endl << std::endl; */ break; case MAINTAIN: /* if (temp <= 75.0) { //std::cout << "Heater: ON" << std::endl; digitalWrite(6, HIGH); temp = t->get_temperature(); } else { //std::cout << "Heater: OFF" << std::endl; digitalWrite(6, LOW); temp = t->get_temperature(); } */ digitalWrite(6, LOW); break; default: break; } return 0; } <file_sep>/src/calcgrav.cpp /****************************************************************************** * Author: <NAME> * Date : 5/2/2017 * Calcgrav is a state machine that obtains pressure and depth readings from * the pressure and depth state machines, then uses those values to calculate * the specific gravity of the fluid inside the boil kettle *****************************************************************************/ #include "task.hpp" #include "calcgrav.hpp" #include "sonar.hpp" #include <iostream> //TODO: modify constructor to include depth(sonar) SM // change h assignmend in calc_specific_gravity to call // get_depth function from depth SM // proper transitions between WAIT and GRAV_BEGIN/END // ^do this after implementing timing Calcgrav::Calcgrav(int ms, Pressure* pres, Sonar* s) : Task(ms) { this->pres = pres; this->s = s; specGravBegin = 0; specGravEnd = 0; } double Calcgrav::get_specGravBegin() { return specGravBegin; } double Calcgrav::get_specGravEnd() { return specGravEnd; } double Calcgrav::calc_specific_gravity() { double g = 9.81; // m per s^2 double p = pres->get_pressure(); //pressure in pascals double h = s->get_distance(); //height in cm //h = h*0.01; //convert height to meters if (h == 0) { return -1; } else { double d = p/(g*h); return p/(g*h); } } int Calcgrav::tick_function() { /* State transitions */ switch(state) { case INIT: state = WAIT; break; case WAIT: /*transition to GRAV_BEGIN vs GRAV_END depends on time * GRAV_BEGIN occurs before boiling, and saves result to specGravBegin * GRAV_END occurs after boiling, and saves result to specGravEnd * TODO: properly implement this (done when timer is set) */ state = GRAV_BEGIN; break; case GRAV_BEGIN: state = WAIT; break; case GRAV_END: break; default: break; } /* State actions */ switch(state) { case INIT: break; case WAIT: break; case GRAV_BEGIN: specGravBegin = calc_specific_gravity(); // std::cout << "Density of fluid = " << specGravBegin << " g/cm^3" << std::endl << std::endl; break; case GRAV_END: specGravEnd = calc_specific_gravity(); break; default: break; } return 0; } <file_sep>/src/timer.cpp #include "task.hpp" #include "timer.hpp" #include <iostream> Timer::Timer(int ms) : Task(1000) { state = INIT; hours = 0; minutes = 0; seconds = -1; } void Timer::start_timer() { hours = 0; minutes = 0; seconds = 0; } void Timer::stop_timer() { seconds = -1; } int Timer::get_hours() { return hours; } int Timer::get_minutes() { return minutes; } int Timer::get_seconds() { return seconds; } int Timer::tick_function() { /* State transitions */ switch(state) { case INIT: state = OFF; break; case OFF: if (seconds == -1) { state = OFF; } else { state = ON; } break; case ON: if (seconds != -1) { state = ON; } else { state = OFF; } break; default: state = INIT; break; }; /* State actions */ switch(state) { case INIT: break; case OFF: break; case ON: //std::cout << seconds++ << std::endl; seconds++; if ((seconds % 60) == 0) { minutes++; } if ((minutes % 60) == 0) { hours++; } break; default: break; }; return 0; } <file_sep>/inc/pump.hpp /****************************************************************************** * Author: <NAME> * Date : 4/27/2017 *****************************************************************************/ #ifndef PUMP_HPP #define PUMP_HPP #include "task.hpp" #include <wiringPi.h> class Pump : public Task { public: Pump(int ms); private: enum States { INIT, ON, OFF } state; virtual int tick_function(); }; #endif <file_sep>/src/sonar.cpp /****************************************************************************** * Author: <NAME> * Date : 5/6/2017 * * State machine for HC-SR04 sonar sensor *****************************************************************************/ #include "task.hpp" #include "sonar.hpp" #include <iostream> #include <wiringPi.h> //trig = GPIO 18 (1) //echo = GPIO 17 (0) Sonar::Sonar(int ms) : Task(ms) { state = INIT; distCM = 0; trigger = 1; echo = 0; pinMode(trigger, OUTPUT); pinMode(echo, INPUT); digitalWrite(trigger, LOW); delay(500); } double Sonar::get_distance() { return distCM; } double Sonar::calc_distance(volatile long travelTimeUsec) { double distInCM = 100*((travelTimeUsec/1000000.0) * 340.29)/2; //height of pot is 11 inches - 27.94 cm distInCM = BK_MAX_HEIGHT_CM - distInCM; if (distInCM < 0) { return 0; } else { return distInCM; } } double Sonar::poll_distance() { delay(10); digitalWrite(trigger, HIGH); delayMicroseconds(10); digitalWrite(trigger, LOW); now = micros(); while(digitalRead(echo) == LOW && micros()-now < 30000); // 30000 ms timeout startTimeUsec = micros(); while(digitalRead(echo) == HIGH); endTimeUsec = micros(); travelTimeUsec = endTimeUsec - startTimeUsec; double distInCM = calc_distance(travelTimeUsec); return distInCM; } int Sonar::tick_function() { /* State transitions */ switch(state) { case INIT: state = WAIT; break; case WAIT: state = PING; break; case PING: state = WAIT; break; default: state = INIT; break; } /* State actions */ switch(state) { case INIT: distCM = 0; trigger = 1; echo = 0; pinMode(trigger, OUTPUT); pinMode(echo, INPUT); digitalWrite(trigger, LOW); delay(500); break; case WAIT: break; case PING: distCM = poll_distance(); // std::cout << "Distance: " << distCM << " cm" << endl; break; default: break; } return 0; } <file_sep>/inc/sonar.hpp /****************************************************************************** * Author: <NAME> * Date : 5/6/2017 *****************************************************************************/ #ifndef SONAR_HPP #define SONAR_HPP #include "task.hpp" #include <wiringPi.h> #define BK_MAX_HEIGHT_CM 27.94 class Sonar : public Task { public: Sonar(int ms); double get_distance(); private: enum States { INIT, WAIT, PING } state; //variables double distCM; volatile long startTimeUsec; volatile long endTimeUsec; int trigger; int echo; long travelTimeUsec; long now; //functions double poll_distance(); double calc_distance(volatile long travelTimeUsec); virtual int tick_function(); }; #endif <file_sep>/inc/output.hpp /****************************************************************************** * Author: <NAME> * Date : 5/21/2017 * * Output is a state machine that polls all other state machines for data and * outputs them accordingly. *****************************************************************************/ #ifndef OUTPUT_HPP #define OUTPUT_HPP #include "temperature.hpp" #include "pressure.hpp" #include "sonar.hpp" #include "calcgrav.hpp" #include "heater.hpp" #include "task.hpp" class Output : public Task { public: Output(int ms, Temperature* t, Pressure* p, Sonar* s, Calcgrav* cg, Heater* h); private: Temperature* t; Pressure* p; Sonar* s; Calcgrav* cg; Heater* h; enum States { INIT, POLL, OUT } state; double temperature; //from temperature SM - get_Temp() double pressure; //from pressure SM - get_Pressure() double dist; //from sonar SM - get_Distance() double specGravBegin; //from calcgrav SM - get_specGravBegin() int timeLeft; //from Heater SM - get_timeLeft_seconds() int outputTimeHours; int outputTimeMinutes; int outputTimeSeconds; int pollCount; //used to suppress output to once per second int pollCountMax; //or as close as once per second as possible. void poll_Data(); void calc_outputTimes(); void output_Data(); void output_to_file(); virtual int tick_function(); }; #endif
bc3e0dcc414ad136bc57d0350ce46b1510b51082
[ "Markdown", "Python", "C++" ]
19
C++
alvtdev/BoilKettlePi
1f44df6822918e19da2110b492bb9fbd9c3af967
c88b58a1937daded948c670e603477e2db6c7a18
refs/heads/master
<file_sep>'use strict'; const config = require('config'); const stripePackage = require('stripe'); const stripe = stripePackage(config.stripe.apiKey); exports.createUser = (user) => { return new Promise((resolve, reject) => { stripe.customers .create({ email: user.account.email, }) .then((customer) => { user.account.paymentId = customer.id; user.save((saveErr) => { if (saveErr) { return reject(saveErr); } resolve(customer); }); }) .catch(err => reject(err)); }); }; exports.getUser = (user) => { return new Promise((resolve, reject) => { stripe.customers .retrieve(user.account.paymentId) .then(customer => resolve(customer)) .catch(err => reject(err)); }); }; exports.addCard = (idUser, body) => { return new Promise((resolve, reject) => { stripe.customers .createSource(idUser, { source: { object: 'card', exp_month: body.expirationMonth, exp_year: body.expirationYear, number: body.number, cvc: body.cvc, }, }) .then(card => resolve(card)) .catch(err => reject(err)); }); }; exports.deleteCard = (idUser, idCard) => { return new Promise((resolve, reject) => { stripe.customers .deleteCard( idUser, idCard ) .then(card => resolve(card)) .catch(err => reject(err)); }); }; exports.createPayment = (idUser, body) => { return new Promise((resolve, reject) => { stripe.charges .create({ amount: body.amount * 100, currency: body.currency, customer: idUser, source: body.idCard, description: body.description, metadata: body.meta, }) .then(payment => resolve(payment)) .catch(error => reject(error)); }); }; exports.getAllPayments = (idUser) => { return new Promise((resolve, reject) => { if (idUser === null) { return resolve({ data: [] }); } stripe.charges .list({ customer: idUser, limit: 100, }) .then(payments => resolve(payments)) .catch(err => reject(err)); }); }; exports.getPayment = (idPayment) => { return new Promise((resolve, reject) => { if (idPayment === null) { return resolve({ data: [] }); } stripe.charges .retrieve(idPayment) .then(payment => resolve(payment)) .catch(err => reject(err)); }); }; exports.createRefound = (idUser, body, amount) => { console.log(body); return new Promise((resolve, reject) => { stripe.payouts.create({ amount: amount * 100, currency: "eur", }) .then(payment => resolve(payment)) .catch(err => reject(err)); }); }; <file_sep>'use strict'; const commentManager = require('../managers/comment'); const advertManager = require('../managers/advert'); const notifManager = require('../managers/notification'); class CommentAdvert { static create(userId, idAdvert, reqBody) { return commentManager .create(userId, idAdvert, reqBody) .then(() => advertManager.find(idAdvert)) .then((result) => { if (String(result.advert.owner._id) !== userId) { notifManager.create(result.advert.owner._id, { title: 'You got a comment !', body: ` left a comment on your advert '${result.advert.title}'`, }, userId); } }) .then(() => CommentAdvert.findByCommentsAdvert(idAdvert)); } static findByCommentsAdvert(idAdvert) { return commentManager.findByCommentsAdvert(idAdvert); } static toggleLike(idUser, idAdvert, idComment) { return commentManager .toggleLike(idUser, idAdvert, idComment) .then(() => CommentAdvert.findByCommentsAdvert(idAdvert)); } static remove(userId, advertId, commentId) { return new Promise((resolve, reject) => { commentManager .findByCommentsAdvert(advertId) .then((res) => { const comment = res.comments.find(nextComment => String(nextComment._id) === commentId && String(nextComment.owner._id) === userId); if (comment) { const index = res.comments.indexOf(comment); res.comments.splice(index, 1); commentManager .findByIdAndUpdate(advertId, { comments: res.comments }) .then(() => resolve(res.comments)) .catch(err => reject(err)); } else { return reject({ code: 2, message: 'No such comment' }); } }) .catch(error => reject(error)); }); } } exports.CommentAdvert = CommentAdvert; <file_sep>const express = require('express'); const accountHandler = require('../../handlers/account').Account; const router = express.Router(); /** * @api {get} /public/accounts/ Find All * @apiName findAll * @apiGroup Account * @apiVersion 0.3.2 * * @apiSuccess {String[]} ids ObjectIds of the Accounts (in the same order as <code>accounts</code>). * @apiSuccess {Object[]} accounts Information of the Accounts. * * @apiSuccessExample Success-Response: * HTTP/1.1 200 OK * { * "ids": ["59c3df242c257a8b65540282"], * "accounts": [{ email: "<EMAIL>" }] * } * * @apiUse DatabaseError */ router.get('/', (req, res) => { accountHandler.findAll() .then(result => res.status(200).send(result)) .catch(error => res.status(400).send(error)); }); router.get('/:id/isConfirmed', (req, res) => { accountHandler.isConfirmed(req.params.id) .then(result => res.status(200).send(result)) .catch(error => res.status(400).send(error)); }); router.get('/:ids/areConfirmed', (req, res) => { const accountIds = req.params.ids.split(','); accountHandler.areConfirmed(accountIds) .then(result => res.status(200).send(result)) .catch(error => res.status(400).send(error)); }); module.exports = router; <file_sep>'use strict'; const fs = require('fs'); const db = require('./database'); const mime = require('mime-types'); const path = require('path'); const Grid = require('gridfs-stream'); const MAX_FILE_SIZE = 5242880; const MAX_FILE_SIZE_STR = '5mb'; Grid.mongo = db.mongo; exports.maxFileSize = () => { return { size: MAX_FILE_SIZE, label: MAX_FILE_SIZE_STR }; }; exports.uploadImage = (pathFile, fileName, mimetype, willUnlink = true) => { return new Promise((resolve, reject) => { const gfs = Grid(db.conn.db); const writestream = gfs.createWriteStream({ filename: fileName, content_type: mimetype, }); fs.createReadStream(pathFile).pipe(writestream); writestream.on('close', (file) => { if (willUnlink) { fs.unlink(pathFile, ((err) => { if (err) return reject({ code: 1, message: err }); resolve(file._id); })); } else { resolve(file._id); } }); }); }; exports.downloadImage = (idImage) => { return new Promise((resolve, reject) => { const gfs = Grid(db.conn.db); gfs.files.find({ _id: db.ObjectId(idImage) }).toArray((err, files) => { if (files.length === 0 || err) { return reject({ code: 1, message: err }); } const name = `${idImage}_${Date.now()}.${mime.extension(files[0].contentType)}`; const fsWriteStream = fs.createWriteStream(path.join(path.join(__dirname, '/../assets/'), name)); const readstream = gfs.createReadStream({ _id: idImage, }); readstream.pipe(fsWriteStream); fsWriteStream.on('close', () => { resolve(path.resolve(path.join(path.join(__dirname, '/../assets/'), name))); }); }); }); }; exports.deleteImage = (idImage) => { return new Promise((resolve, reject) => { const gfs = Grid(db.conn.db); gfs.remove({ _id: idImage, }, (err) => { if (err) return reject({ code: 1, message: err }); resolve(); }); }); }; <file_sep>const mongoose = require('mongoose'); const Schema = mongoose.Schema; const paymentSchema = new Schema({ payerId: { type: Schema.Types.ObjectId, ref: 'Users', required: true }, beneficiaryId: { type: Schema.Types.ObjectId, ref: 'Users', required: true }, amountPayer: { type: Number, required: true }, payed: { type: Boolean, required: false, default: false }, amountBeneficiary: { type: Number, required: true }, refounded: { type: Boolean, required: false, default: false }, date: { type: Date, default: Date.now }, description: { type: String, default: '' }, idPayment: { type: String, default: null }, idRefound: { type: String, default: null }, idVisit: { type: String, required: true }, }).index({ payerId: 1, beneficiaryId: 1, date: 1 }, { unique: true }); exports.Payments = mongoose.model('Payments', paymentSchema); <file_sep>'use strict'; const nodemailer = require('nodemailer'); const mg = require('nodemailer-mailgun-transport'); const config = require('config'); const auth = { auth: { api_key: config.mailgun.apiKey, domain: 'mg.pickaguide.fr', }, }; const nodemailerMailgun = nodemailer.createTransport(mg(auth)); const send = nodemailerMailgun.templateSender({ subject: '{{subject}}', html: 'Bonjour {{firstname}} {{lastname}}<br><br>' + '<a href="{{url}}">{{urlName}}</a>', }, { from: '<EMAIL>', }); const sendEmail = (user, subject, url, urlName) => { return new Promise((resolve, reject) => { send({ to: user.account.email, }, { subject, firstname: user.profile.firstName, lastname: user.profile.lastName, url, urlName, }, (err, info) => (err ? reject(err.message) : resolve(info))); }); }; exports.sendEmailConfirmation = (user) => { const subject = 'Confirmation email Pickaguide'; const url = config.host + '/public/verify/' + user._id; const urlName = 'Cliquez pour confirmer votre adresse email'; return new Promise((resolve, reject) => { sendEmail(user, subject, url, urlName) .then(result => resolve({ code: 0, message: result })) .catch(err => reject({ code: 1, message: err })); }); }; exports.sendEmailPasswordReset = (user) => { const subject = 'Reset password Pickaguide'; const url = config.host + '/public/reset/' + user.account.resetPasswordToken; const urlName = 'Cliquez pour changer votre mot de passe'; return new Promise((resolve, reject) => { sendEmail(user, subject, url, urlName) .then(result => resolve({ code: 0, message: result })) .catch(err => reject({ code: 1, message: err })); }); }; const sendContactUsEmail = nodemailerMailgun.templateSender({ subject: 'Message from {{name}}', html: 'Email : {{email}}<br><br>' + 'Phone : {{phone}}<br><br>' + '{{message}}', }, { from: '<EMAIL>', }); exports.contactUs = (mail) => { return new Promise((resolve, reject) => { if (!mail.phone) { mail.phone = 'None'; } sendContactUsEmail({ to: '<EMAIL>', }, { name: mail.name, email: mail.email, message: mail.message, phone: mail.phone, }, (err, info) => (err ? reject(err) : resolve(info))); }); }; <file_sep>const db = require('../database'); const _ = require('lodash'); const displayName = require('./profile').displayName; const update = (userId, visitId, files) => { return new Promise((resolve, reject) => { db.Visits .findOne({ _id: visitId, by: userId }) .exec((err, visit) => { if (err) { return reject({ code: 1, message: err.message }); } if (visit === null) { return reject({ code: 2, message: 'Cannot find visit' }); } const updatedFiles = (files.length > 0 ? files : visit._fsIds); visit._fsIds = updatedFiles; visit.save((saveErr, updatedVisit) => { if (saveErr) { return reject({ code: 3, message: saveErr.message }); } if (updatedVisit === null) { return reject({ code: 4, message: 'Failed to update advert' }); } resolve({ visit: updatedVisit }); }); }); }); }; const getUpcomingVisits = (advertId) => { const now = Date.now(); return new Promise((resolve, reject) => { db.Visits .find({ about: String(advertId), hasEnded: false, when: { $gt: now, }, }, 'when status numberVisitors') .sort('when') .lean() .exec((err, visits) => { if (err) { return reject({ code: 1, message: err.message }); } const concernedVisits = visits .filter(visit => visit.status.slice(-1).pop().label === 'accepted') .map(visit => ({ when: visit.when, numberVisitors: visit.numberVisitors })); resolve(concernedVisits); }); }); }; const isForGuide = (visitId, userId) => { return new Promise((resolve, reject) => { db.Visits .findOne({ _id: visitId }, 'about') .populate('about', 'owner') .lean() .exec((err, visit) => { if (err) { return reject({ code: 1, message: err.message }); } if (visit === null) { return reject({ code: 2, message: 'No such visit found' }); } resolve(visit.about ? String(visit.about.owner) === userId : false); }); }); }; const isFromVisitor = (visitId, userId) => { return new Promise((resolve, reject) => { db.Visits .findOne({ _id: visitId, by: userId }, '_id') .lean() .exec((err, visit) => { if (err) { return reject({ code: 1, message: err.message }); } resolve(visit !== null); }); }); }; const updateStatus = (visitId, label, message) => { const endStates = ['finished', 'denied', 'cancelled']; return new Promise((resolve, reject) => { db.Visits .findByIdAndUpdate( visitId, { $push: { status: { label, message } }, $set: { hasEnded: endStates.indexOf(label) !== -1 } }, { new: true }, (saveErr, updatedVisit) => { if (saveErr) { return reject({ code: 1, saveErr }); } if (updatedVisit === null) { return reject({ code: 2, message: 'Failed to update visit' }); } resolve({ visit: updatedVisit }); }); }); }; const getCreator = (visitId) => { return new Promise((resolve, reject) => { db.Visits .findById(String(visitId), 'by') .lean() .exec((err, visit) => { if (err) { return reject({ code: 1, message: err.message }); } if (visit == null) { return reject({ code: 2, message: 'Visit not found' }); } resolve(visit.by); }); }); }; const getGuide = (visitId) => { return new Promise((resolve, reject) => { db.Visits .findById(String(visitId), 'about') .populate({ path: 'about', select: 'owner' }) .lean() .exec((err, visit) => { if (err) { return reject({ code: 1, message: err.message }); } if (visit == null) { return reject({ code: 2, message: 'Visit not found' }); } resolve(visit.about.owner); }); }); }; const isStatus = (visitId, status) => { return new Promise((resolve, reject) => { if (status.constructor !== Array) { status = [status]; } db.Visits .findById(visitId, 'status') .lean() .exec((err, visit) => { if (err) { return reject({ code: 1, message: err.message }); } if (visit === null) { return reject({ code: 2, message: 'No such visit found' }); } const visitStatus = _.map(visit.status, 'label'); resolve(status.indexOf(visitStatus[visit.status.length - 1]) !== -1); }); }); }; const countAmountForAdvert = (idAdvert) => { return new Promise((resolve, reject) => { db.Visits .count({ about: String(idAdvert), hasEnded: true, 'status.label': 'finished', }) .exec((err, counts) => { if (err) { return reject({ code: 1, message: err.message }); } resolve(counts); }); }); }; const changeStatus = (input, allowedStatus, nextStatus) => { return new Promise((resolve, reject) => { Promise .all([ new Promise((resolveAssertUser, rejectAssertUser) => { input.assertUserType(input.visitId, input.userId) .then((itIs) => { if (itIs === false) { return rejectAssertUser({ code: 1, message: 'You cannot change a visit that is not yours' }); } if (input.reqBody.reason === undefined || typeof input.reqBody.reason !== 'string') { input.reqBody.reason = input.defaultReason; } resolveAssertUser(); }) .catch(err => rejectAssertUser(err)); }), new Promise((resolveStatus, rejectStatus) => { isStatus(input.visitId, allowedStatus) .then((itIs) => { if (itIs === false) { return rejectStatus({ code: 1, message: 'You cannot change the visit in this current state' }); } resolveStatus(); }) .catch(err => rejectStatus(err)); }), ]) .then(() => { updateStatus(input.visitId, nextStatus, input.reqBody.reason) .then(result => resolve(result)) .catch(err => reject(err)); }) .catch(err => reject(err)); }); }; const create = (by, about, reqBody) => { return new Promise((resolve, reject) => { const newVisit = new db.Visits({ by, about, when: reqBody.when, numberVisitors: reqBody.numberVisitors, status: [{ }], special: reqBody.special, }); newVisit.save((err) => { if (err) { let message; if (err.code === 11000) { message = 'This visit already exists'; } else { message = 'Invalid data'; } return reject({ code: 1, message }); } resolve({ code: 0, message: 'Visit requested' }); }); }); }; const find = (visitId) => { return new Promise((resolve, reject) => { db.Visits .findById(String(visitId)) .populate({ path: 'by', select: 'profile.firstName profile.lastName' }) .populate({ path: 'about', select: 'title photoUrl' }) .lean() .exec((err, visit) => { if (err) { return reject({ code: 1, message: err.message }); } if (visit == null) { return reject({ code: 2, message: 'Visit not found' }); } visit.with = (visit.by ? displayName(visit.by.profile) : 'Deleted user'); delete visit.by; resolve({ visit }); }); }); }; const findAllFrom = (userId) => { return new Promise((resolve, reject) => { db.Visits .find({ by: String(userId) }) .populate({ path: 'about', select: 'title photoUrl owner' }) .lean() .sort('-when') .exec((err, visits) => { if (err) { return reject({ code: 1, message: err.message }); } visits.forEach((visit) => { visit.finalStatus = visit.status[visit.status.length - 1]; }); resolve(visits); }); }); }; const findAllFor = (userId) => { return new Promise((resolve, reject) => { db.Visits .find({}) .populate({ path: 'about', match: { owner: String(userId) }, select: 'title photoUrl owner' }) .lean() .sort('-when') .exec((err, visits) => { if (err) { return reject({ code: 1, message: err.message }); } visits = visits.filter(visit => visit.about !== null); visits.forEach((visit) => { visit.finalStatus = visit.status[visit.status.length - 1]; }); resolve(visits); }); }); }; const findAsGuide = (visitId, userId) => { return new Promise((resolve, reject) => { isForGuide(visitId, userId) .then((itIs) => { if (itIs === false) { return reject({ code: 1, message: 'You are not the guide of this visit' }); } db.Visits .findById(String(visitId)) .populate({ path: 'by', select: 'profile.firstName profile.lastName profile.phone account.email' }) .populate({ path: 'about', select: 'title photoUrl' }) .lean() .exec((err, visit) => { if (err) { return reject({ code: 1, message: err.message }); } if (visit == null) { return reject({ code: 2, message: 'Visit not found' }); } visit.with = (visit.by ? displayName(visit.by.profile) : 'Deleted user'); if (visit.status[visit.status.length - 1].label === 'accepted') { visit.contact = { phone: visit.by.profile.phone, email: visit.by.account.email }; } delete visit.by; resolve({ visit }); }); }) .catch(err => reject(err)); }); }; const findAsVisitor = (visitId, userId) => { return new Promise((resolve, reject) => { isFromVisitor(visitId, userId) .then((itIs) => { if (itIs === false) { return reject({ code: 1, message: 'This is not your visit' }); } db.Visits .findById(String(visitId)) .populate({ path: 'about', select: 'title owner photoUrl' }) .lean() .exec((err, visit) => { if (err) { return reject({ code: 1, message: err.message }); } if (visit == null) { return reject({ code: 2, message: 'Visit not found' }); } resolve(visit); }); }) .catch(err => reject(err)); }); }; const findToReview = (userId, as) => { return new Promise((resolve, reject) => { const findMethod = (as === 'visitor' ? findAllFrom : findAllFor); findMethod(userId) .then((visits) => { const visitsEnded = visits.filter(visit => visit.hasEnded && visit[as === 'visitor' ? 'visitorRate' : 'guideRate'] === null); const visitsFinished = visitsEnded.filter(visit => visit.status[visit.status.length - 1].label === 'finished'); resolve(visitsFinished); }) .catch(err => reject(err)); }); }; const cancel = (userId, visitId, reqBody) => { return changeStatus({ userId, visitId, reqBody, assertUserType: isFromVisitor, defaultReason: 'No reason', }, ['waiting', 'accepted'], 'cancelled'); }; const cancelAll = (userId) => { return findAllFrom(userId) .then(visits => Promise.all( visits .filter(visit => visit.hasEnded === false) .map(visit => new Promise((resolveCancel, rejectCancel) => { cancel(userId, visit._id, { reason: 'User deleted' }) .then(() => resolveCancel()) .catch((err) => { if (err.code === 1 && err.message === 'You cannot change the visit in this current state') { return resolveCancel(); } return rejectCancel(err); }); }) ) ) ); }; const deny = (userId, visitId, reqBody) => { return changeStatus({ userId, visitId, reqBody, assertUserType: isForGuide, defaultReason: 'No reason', }, ['waiting', 'accepted'], 'denied'); }; const denyAll = (userId) => { return findAllFor(userId) .then(visits => Promise.all( visits .filter(visit => visit.hasEnded === false) .map(visit => new Promise((resolveDeny, rejectDeny) => { deny(userId, visit._id, { reason: 'Guide retired' }) .then(() => resolveDeny()) .catch((err) => { if (err.code === 1 && err.message === 'You cannot change the visit in this current state') { return resolveDeny(); } return rejectDeny(err); }); }) ) ) ); }; const finish = (userId, visitId, reqBody) => { return changeStatus({ userId, visitId, reqBody, assertUserType: isForGuide, defaultReason: 'No comment', }, 'accepted', 'finished'); }; const accept = (userId, visitId, reqBody) => { return changeStatus({ userId, visitId, reqBody, assertUserType: isForGuide, defaultReason: 'No comment', }, 'waiting', 'accepted'); }; const review = (userId, visitId, reqBody, systemRate) => { return new Promise((resolve, reject) => { if (userId === reqBody.for) { return reject({ code: 3, message: 'Cannot rate yourself' }); } db.Visits .findById(visitId, 'about by') .populate({ path: 'about', select: 'owner' }) .exec((err, visit) => { if (String(visit.by) === reqBody.for) { visit.guideRate = parseInt(reqBody.rate, 10); } else if (visit.about === null || String(visit.about.owner) === reqBody.for) { visit.visitorRate = parseInt(reqBody.rate, 10); visit.systemRate = systemRate; } visit.save((saveErr, updatedVisit) => { if (saveErr) { return reject({ code: 1, saveErr }); } if (updatedVisit === null) { return reject({ code: 2, message: 'Failed to update visit' }); } resolve({ visit: updatedVisit }); }); }); }); }; const findAllOf = (advertId) => { return new Promise((resolve, reject) => { db.Visits .find({ about: String(advertId) }, '_id by') .lean() .exec((err, visits) => { if (err) { return reject({ code: 1, message: err.message }); } resolve(visits); }); }); }; module.exports = { findAllOf, getUpcomingVisits, update, create, getCreator, getGuide, countAmountForAdvert, find, findAllFrom, findToReview, findAllFor, findAsGuide, findAsVisitor, cancel, cancelAll, deny, denyAll, finish, accept, review }; <file_sep>const mongoose = require('mongoose'); const config = require('config'); mongoose.Promise = global.Promise; const connectionUrl = (['staging', 'production'].indexOf(process.env.NODE_ENV) !== -1 ? `mongodb://${config.mongo.user}:${config.mongo.password}@${config.mongo.url}` : `${config.mongo.url}`); const init = () => mongoose.connect(connectionUrl, { keepAlive: true, reconnectTries: Number.MAX_VALUE, useMongoClient: true, }); exports.ObjectId = mongoose.Types.ObjectId; String.prototype.capitalize = function capitalize() { return this.charAt(0).toUpperCase() + this.slice(1); }; exports.Users = require('./models/user').Users; exports.Adverts = require('./models/advert').Adverts; exports.Visits = require('./models/visit').Visits; exports.Comments = require('./models/advert').Comments; exports.Blacklists = require('./models/blacklist').Blacklists; exports.Notifications = require('./models/notification').Notifications; exports.Payments = require('./models/payments').Payments; exports.conn = mongoose.connection; exports.mongo = mongoose.mongo; exports.init = init; <file_sep>const db = require('../database'); const jwt = require('jsonwebtoken'); const config = require('config'); const _ = require('lodash'); const assertInput = require('../handlers/_handler').assertInput; const capitalize = (user) => { const fieldsToCapitalize = ['city', 'country', 'firstName', 'lastName']; fieldsToCapitalize.forEach((fieldName) => { const fieldValue = user.profile[fieldName]; if (fieldValue && fieldValue.constructor === String) { user.profile[fieldName] = user.profile[fieldName].capitalize(); } }); }; const add = (fields) => { return new Promise((resolve, reject) => { const newUser = new db.Users(fields); newUser.hash(fields.account.password, (hashed) => { newUser.account.token = jwt.sign({ userId: newUser._id }, config.jwtSecret); newUser.account.password = <PASSWORD>; capitalize(newUser); newUser.save((err) => { if (err) { let message; if (err.code === 11000) { message = 'This account already exists'; } else { message = 'Invalid data'; } return reject({ code: 1, message }); } resolve(newUser); }); }); }); }; const find = (userId, selectFields = '', updatable = false) => { return new Promise((resolve, reject) => { let query = db.Users.findById(userId, selectFields); if (updatable === false) { query = query.lean(); } query.exec((err, user) => { if (err) { return reject({ code: 1, message: err.message }); } if (user === null) { return reject({ code: 2, message: 'No user with this id' }); } resolve(user); }); }); }; const findInIds = (userIds, selectFields = '', updatable = false) => { return new Promise((resolve, reject) => { let query = db.Users.find() .where('_id') .in(userIds) .select(selectFields); if (updatable === false) { query = query.lean(); } query.exec((err, users) => { if (err) { return reject({ code: 1, message: err.message }); } resolve(users); }); }); }; const findNear = (center, maxDistance) => { return new Promise((resolve, reject) => { db.Users .find({ isGuide: true }, { 'profile.firstName': 1, 'profile.description': 1, 'profile.rate': 1, location: 1, }) .near('location', { center, maxDistance: Number(maxDistance), spherical: true }) .lean() .exec((err, users) => { if (err) { return reject({ code: 4, message: err.message }); } resolve(users); }); }); }; const findAll = (selectFields = '') => { return new Promise((resolve, reject) => { db.Users .find({}, selectFields) .lean() .exec((err, users) => { if (err) { return reject({ code: 1, message: err.message }); } resolve(users); }); }); }; const findByEmail = (email) => { return new Promise((resolve, reject) => { if (email === undefined) { return reject({ code: 2, message: 'No account with this email' }); } db.Users .findOne({ 'account.email': email }) .exec((err, user) => { if (err) { return reject({ code: 1, message: err.message }); } if (user == null) { return reject({ code: 2, message: 'No account with this email' }); } resolve(user); }); }); }; const findByTerms = (terms) => { const fields = { account: 0, 'profile.gender': 0, 'profile.phone': 0, }; if (!terms || terms.length === 0) { return findAll(fields); } return new Promise((resolve, reject) => { const regexes = terms.trim().split(' ').filter(term => term.length > 2).map(term => new RegExp(term, 'i')); const regexSearch = []; ['firstName', 'lastName', 'description', 'interests'].forEach((field) => { const searchElement = {}; searchElement[`profile.${field}`] = { $in: regexes }; regexSearch.push(searchElement); }); db.Users .find({ $or: regexSearch, 'account.emailConfirmation': true }, fields) .lean() .exec((err, users) => { if (err) { return reject({ code: 1, message: err.message }); } resolve(users); }); }); }; const findByIdAndUpdate = (userId, fields) => { return new Promise((resolve, reject) => db.Users .findByIdAndUpdate(userId, fields, { new: true }, (err, user) => { if (err) { return reject({ code: 1, message: err.message }); } if (user === null) { return reject({ code: 2, message: 'Cannot find user' }); } resolve(user); }) ); }; const remove = (userId, reqBody) => { return new Promise((resolve, reject) => { const failed = assertInput(['email', 'password'], reqBody); if (failed) { return reject({ code: 1, error: `We need your ${failed}` }); } findByEmail(reqBody.email) .then((user) => { user.comparePassword(reqBody.password, (err, isMatch) => { if (err) { return reject({ code: 3, message: err.message }); } if (!isMatch) { return reject({ code: 4, message: 'Invalid password' }); } if (userId !== String(user._id)) { return reject({ code: 2, message: 'No account with this email' }); } resolve(user); }); }) .catch(err => reject(err)); }); }; const setBlocking = (userId, isBlocking) => { return new Promise((resolve, reject) => { db.Users .findByIdAndUpdate(userId, { isBlocking }, { new: true }, (err, user) => { if (err) { return reject({ code: 1, message: err.message }); } if (user === null) { return reject({ code: 2, message: 'Cannot find user' }); } resolve({ id: userId, isBlocking: user.isBlocking }); }); }); }; const update = (userId, reqBody) => { return new Promise((resolve, reject) => { db.Users .findById(userId) .exec((err, user) => { if (err) { return reject({ code: 1, message: err.message }); } if (user === null) { return reject({ code: 2, message: 'Cannot find user' }); } const mergedUser = _.merge(user, reqBody); capitalize(mergedUser); if (reqBody.profile && reqBody.profile.interests !== undefined) { mergedUser.profile.interests = reqBody.profile.interests; mergedUser.markModified('profile.interests'); } mergedUser.save((saveErr, updatedUser) => { if (saveErr) { let message; if (saveErr.code === 11000) { message = 'This account already exists'; } else { message = 'Invalid update'; } return reject({ code: 3, message }); } if (updatedUser === null) { return reject({ code: 4, message: 'Failed to update user' }); } resolve(updatedUser); }); }); }); }; const updateRate = (userId) => { return new Promise((resolve, reject) => { db.Adverts .find({ owner: String(userId) }, '_id') .lean() .exec((err, adverts) => { if (err) { return reject({ code: 1, message: err.message }); } resolve(adverts); }); }) .then((adverts) => { return new Promise((resolve, reject) => { db.Visits .find({ $or: [{ about: { $in: adverts, }, visitorRate: { $ne: null, }, }, { by: String(userId), guideRate: { $ne: null, }, }], }, 'by visitorRate guideRate systemRate') .lean() .exec((err, visits) => { if (err) { return reject({ code: 2, message: err.message }); } let notIndicated = 0; let averageRate = visits.reduce((sum, visit) => { let toAdd = (String(visit.by) === userId ? visit.guideRate : visit.visitorRate); if (String(visit.by) === userId && visit.systemRate !== null) { toAdd += visit.systemRate; notIndicated -= 1; } if (toAdd === null) { notIndicated += 1; } return sum + (toAdd || 0); }, 0) / (visits.length - notIndicated); if (isNaN(averageRate)) { averageRate = null; } resolve(averageRate); }); }); }) .then((rate) => { return new Promise((resolve, reject) => { db.Users.findByIdAndUpdate(userId, { 'profile.rate': rate }) .exec((err) => { if (err) { return reject({ code: 3, message: err.message }); } resolve(); }); }); }); }; const isGuide = (userId) => { return new Promise((resolve, reject) => { db.Users .findById(userId, { isGuide: 1 }) .lean() .exec((err, user) => { if (err) { return reject({ code: 1, message: err.message }); } if (user === null) { return reject({ code: 2, message: 'Cannot find user' }); } resolve({ id: userId, isGuide: user.isGuide }); }); }); }; const isBlocking = (userId) => { return new Promise((resolve, reject) => { db.Users .findById(userId, { isBlocking: 1 }) .lean() .exec((err, user) => { if (err) { return reject({ code: 1, message: err.message }); } if (user === null) { return reject({ code: 2, message: 'Cannot find user' }); } resolve({ id: userId, isBlocking: user.isBlocking }); }); }); }; const becomeGuide = (userId) => { return new Promise((resolve, reject) => { db.Users .findById(userId) .exec((err, user) => { if (err) { return reject({ code: 1, message: err.message }); } if (user === null) { return reject({ code: 2, message: 'Cannot find user' }); } if (user.account.emailConfirmation === false) { return reject({ code: 3, message: 'You need to confirm your email address' }); } const fieldsToValidate = ['phone', 'city', 'country', 'description', 'interests']; if (fieldsToValidate.every(field => ([undefined, null].indexOf(user.profile[field]) === -1)) === false) { return reject({ code: 4, message: 'You need to fill in all fields' }); } user.isGuide = true; user.save((saveErr, updatedUser) => { if (saveErr) { return reject({ code: 3, message: saveErr.message }); } if (updatedUser === null) { return reject({ code: 4, message: 'Failed to update user' }); } resolve({ id: userId, isGuide: updatedUser.isGuide }); }); }); }); }; module.exports = { add, remove, update, becomeGuide, updateRate, isBlocking, isGuide, setBlocking, find, findByIdAndUpdate, findInIds, findAll, findNear, findByEmail, findByTerms }; <file_sep>const natural = require('natural'); const TfIdf = natural.TfIdf; const matchAdverts = (interests, adverts) => { const tf = new TfIdf(); adverts.forEach((advert) => { tf.addDocument(advert.description); }); const measures = []; tf.tfidfs(interests, (i, measure) => { measures.push({ index: i, measure }); }); measures.sort((a, b) => { return a.measure - b.measure; }); const sortedAdverts = []; measures.forEach((el) => { sortedAdverts.push(adverts[el.index]); }); return sortedAdverts; }; const matchUsers = (interests, users) => { const tf = new TfIdf(); users.forEach((user) => { tf.addDocument(user.profile.description); }); const measures = []; tf.tfidfs(interests, (i, measure) => { measures.push({ index: i, measure }); }); measures.sort((a, b) => { return b.measure - a.measure; }); const sortedUsers = []; measures.forEach((el) => { sortedUsers.push(users[el.index]); }); console.log(sortedUsers); return sortedUsers; }; module.exports = { matchAdverts, matchUsers }; <file_sep>'use strict'; const Promise = require('bluebird'); const paymentService = require('../payment-service'); const paymentManager = require('../managers/payment'); const userManager = require('../managers/user'); const visitManager = require('../managers/visit'); class Payment { static createUser(user) { return new Promise((resolve, reject) => { paymentService.createUser(user) .then(result => resolve(result)) .catch(error => reject(error)); }); } static getUser(user) { return new Promise((resolve, reject) => { paymentService.getUser(user) .then(result => resolve(result)) .catch(error => reject(error)); }); } static addCard(paymentId, reqBody) { return new Promise((resolve, reject) => { paymentService.addCard(paymentId, reqBody) .then(result => resolve(result)) .catch(error => reject(error)); }); } static createPayment(user, reqBody) { return new Promise((resolve, reject) => { visitManager.getGuide(reqBody.idVisit) .then(guide => userManager.find(guide)) .then((userDestination) => { return paymentManager .create(user, userDestination, reqBody.amount, reqBody.amount, reqBody.idVisit) .catch(error => reject(error)); }) .catch(error => reject(error)) .then((paymentDb) => { paymentService.createPayment(user.account.paymentId, reqBody) .then((result) => { return paymentManager .paymentPayed(paymentDb, result.id) .then(() => resolve(result)) .catch(error => reject(error)); }); }) .catch(error => reject(error)); }); } static getAllPayments(user) { return new Promise((resolve, reject) => { paymentManager.getPayments(user) .then((result) => { const payments = result.Payments; return Promise.mapSeries(payments, payment => visitManager.find(payment.idVisit)) .then((visits) => { payments.forEach((payment, index) => { const visit = visits[index].visit; payment.description = visit.about ? visit.about.title : 'Advert deleted'; }); resolve({ Payments: payments }); }); }) .catch(error => reject(error)); }); } static getPayment(paymentId) { return new Promise((resolve, reject) => { paymentService.getPayment(paymentId) .then(result => resolve(result)) .catch(error => reject(error)); }); } static getRefounds(user, refounded) { return new Promise((resolve, reject) => { paymentManager.getRefounds(user, refounded) .then(result => resolve(result)) .catch(error => reject(error)); }); } static postRefounds(user, refounded) { return new Promise((resolve, reject) => { paymentManager.getRefounds(user, false) .then((payments) => { const totalAmount = payments.Payments.reduce((sum, x) => { return sum + x.amountBeneficiary; }, 0); if (totalAmount <= 0) reject('no payment to refound'); paymentService.createRefound(user, body, totalAmount) .then((result) => { Promise.all(payments.Payments.map((x) => { return paymentManager .paymentRefounded(x, result.id) })) .then(() => resolve(result)) .catch(error => reject(error)) }) .catch(error => reject(error)) }) .catch(error => reject(error)); }); } static deleteCard(user, idCard) { return new Promise((resolve, reject) => { paymentService.deleteCard(user, idCard) .then(result => resolve(result)) .catch(error => reject(error)); }); } } exports.Payment = Payment; <file_sep>const express = require('express'); const notificationHandler = require('../handlers/notification').Notification; const router = express.Router(); router.get('/', (req, res) => { notificationHandler.findAllFrom(req.user.userId) .then(result => res.status(200).send(result)) .catch(error => res.status(400).send(error)); }); router.get('/hasUnread', (req, res) => { notificationHandler.hasUnread(req.user.userId) .then(result => res.status(200).send(result)) .catch(error => res.status(400).send(error)); }); router.get('/unread', (req, res) => { notificationHandler.getUnread(req.user.userId) .then(result => res.status(200).send(result)) .catch(error => res.status(400).send(error)); }); router.put('/read', (req, res) => { notificationHandler.readAll(req.user.userId) .then(result => res.status(200).send(result)) .catch(error => res.status(400).send(error)); }); router.put('/:id/read', (req, res) => { notificationHandler.read(req.params.id, req.user.userId) .then(result => res.status(200).send(result)) .catch(error => res.status(500).send(error)); }); module.exports = router; <file_sep>'use strict'; const request = require('supertest'); const expect = require('chai').expect; const server = require('../index'); const helpers = require('./helpers'); const db = require('../api/database'); describe('Private Profile Routes', () => { let app, user; before((done) => { server.start((err, _app) => { if (err) return done(err); app = _app; helpers.createUser(_user => { user = _user; done(); }); }); }); after((done) => { helpers.deleteUser(user._id, () => { server.stop(done); }); }); describe('POST /profiles/avatars', () => { it('should return 400 if avatar body param does not exist', (done) => { request(app) .post('/profiles/avatar') .set('Content-Type', 'application/json') .set('Authorization', 'Bearer ' + user.account.token) .expect(404, done); }); it('should return 400 if file upload is not an image', (done) => { request(app) .post('/profiles/avatar') .set('Content-Type', 'application/json') .set('Authorization', 'Bearer ' + user.account.token) .attach('avatar', __dirname + '/helpers.js') .expect(400, { code: 1, message: 'The mimetype is not valid must be jpeg|jpg|png|gif' }, done); }); it('should return 200 if the image is uploaded', (done) => { request(app) .post('/profiles/avatar') .set('Content-Type', 'application/json') .set('Authorization', 'Bearer ' + user.account.token) .attach('avatar', __dirname + '/test.png') .expect(200, (err) => { if (err) done(err); db.Users.findById(user._id, (err, user) => { if (err) done(err); expect(user.profile._fsId).to.be.not.null; done(); }); }); }); }); describe('GET /public/profiles/:id/avatar', () => { it('should return 404 if id not found', (done) => { request(app) .get('/public/profiles/123412341234/avatar') .set('Content-Type', 'application/json') .set('Authorization', 'Bearer ' + user.account.token) .expect(404, done); }); it('should return 200 if user can get avatar', (done) => { request(app) .get('/public/profiles/' + user._id + '/avatar') .set('Content-Type', 'application/json') .set('Authorization', 'Bearer ' + user.account.token) .expect(200, done); }); }); describe('DELETE /profiles/avatars', () => { it('should return 200 if avatar deleted', (done) => { request(app) .delete('/profiles/avatar') .set('Authorization', 'Bearer ' + user.account.token) .expect(200, done); }); }); }); <file_sep>'use strict'; const jwt = require('jsonwebtoken'); const config = require('config'); const db = require('../api/database'); const account = { password: '<PASSWORD>', email: '<EMAIL>' }; const profile = { firstName: 'userValid', lastName: 'test' }; const userValid = new db.Users({account, profile}); exports.createUser = (next) => { userValid.hash(userValid.account.password, (hashed) => { userValid.account.token = jwt.sign({ userId: userValid._id }, config.jwtSecret); userValid.account.password = <PASSWORD>; userValid.save((err, user) => { return next(user); }); }); }; exports.deleteUser = (idUser, next) => { db.Users.findByIdAndRemove(idUser, () => { return next(); }); }; <file_sep>'use strict'; const request = require('supertest'); const expect = require('chai').expect; const server = require('../../index'); const helpers = require('../helpers'); const nock = require('nock'); const db = require('../../api/database'); describe('Public Account Routes', () => { let app, user; before((done) => { server.start((err, _app) => { if (err) return done(err); app = _app; helpers.createUser(_user => { user = _user; done(); }); }); }); after((done) => { helpers.deleteUser(user._id, () => { server.stop(done); }); }); describe('GET /public/accounts/', () => { it('should return accounts', (done) => { request(app) .get('/public/accounts/') .expect(200, done); }); }); });<file_sep>'use strict'; const http = require('http'); const https = require('https'); const fs = require('fs'); const express = require('express'); const bodyParser = require('body-parser'); const expressJwt = require('express-jwt'); const config = require('config'); const morgan = require('morgan'); const cors = require('cors'); const db = require('./api/database'); const app = express(); let server = null; let httpsServer = null; const run = function run(next) { db.init() .then(function then() { app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(morgan('dev')); app.use(cors()); app.use('/public', require('./api/routes/public/public')); app.use('/public/accounts', require('./api/routes/public/account')); app.use('/public/profiles', require('./api/routes/public/profile')); app.use('/public/users', require('./api/routes/public/user')); app.use('/public/proposals', require('./api/routes/public/advert')); app.use('/public/visits', require('./api/routes/public/visit')); app.use('/public/search', require('./api/routes/public/search')); app.use('/public/contact-us', require('./api/routes/public/contact')); app.use('/', expressJwt({ secret: config.jwtSecret }).unless({ path: /\/public(\/.*)?/ })); app.use('/', require('./api/middleware-service').errorsTokenMissing); app.use('/', require('./api/handlers/account').Account.isAuthorised); app.use('/', require('./api/middleware-service').checkContentTypeHeader); app.use('/', require('./api/middleware-service').checkUserIsBlocked); app.use('/', require('./api/middleware-service').trimForm); app.use('/profiles', require('./api/routes/profile')); app.use('/accounts', require('./api/routes/account')); app.use('/users', require('./api/routes/user')); app.use('/proposals', require('./api/routes/advert')); app.use('/visits', require('./api/routes/visit')); app.use('/payment', require('./api/routes/payment')) app.use('/notifications', require('./api/routes/notification')) app.use('/travelbook', require('./api/routes/travelbook')) app.set('port', config.port); server = http.createServer(app).listen(app.get('port'), function handler() { console.log('Express server listening on %d, in %s mode', app.get('port'), app.get('env')); if (next) next(null, app); }); if (process.env.ENVIRONMENT === 'production') { const sslOptions = { key: fs.readFileSync('/home/sslCertificates/privkey.pem'), cert: fs.readFileSync('/home/sslCertificates/cert.pem'), ca: fs.readFileSync('/home/sslCertificates/chain.pem') }; httpsServer = https.createServer(sslOptions, app).listen(443); } }) .catch(function error(err) { console.error('Could not init the database:', err); }); }; if (require.main === module) { run(); } const stop = function stop(next) { if (httpsServer) { httpsServer.close() } if (server) { server.close(next); } }; module.exports.start = run; module.exports.stop = stop; <file_sep>const express = require('express'); const userHandler = require('../handlers/user').User; const profileHandler = require('../handlers/profile').Profile; const router = express.Router(); router.post('/becomeGuide', (req, res) => { profileHandler.update(req.user.userId, { profile: req.body }) .then((updatedUser) => { userHandler.becomeGuide(req.user.userId) .then((result) => { updatedUser.isGuide = result.isGuide; res.status(200).send(updatedUser); }) .catch(error => res.status(500).send(error)); }) .catch(error => res.status(400).send(error)); }); router.get('/isBlocking', (req, res) => { userHandler.isBlocking(req.user.userId) .then(result => res.status(200).send(result)) .catch(error => res.status(400).send(error)); }); router.post('/retire', (req, res) => { userHandler.retire(req.user.userId) .then(result => res.status(200).send(result)) .catch(error => res.status(500).send(error)); }); module.exports = router; <file_sep>const NodeGeocoder = require('node-geocoder'); const db = require('../database'); const _ = require('lodash'); const displayName = require('./profile').displayName; const userManager = require('./user'); const matchingService = require('../matching-service'); const options = { provider: 'google', apiKey: '<KEY>', }; const geocoder = NodeGeocoder(options); const capitalize = (advert) => { const fieldsToCapitalize = ['title', 'city', 'country']; fieldsToCapitalize.forEach((fieldName) => { const fieldValue = advert[fieldName]; if (fieldValue && fieldValue.constructor === String) { advert[fieldName] = advert[fieldName].capitalize(); } }); }; const transformAdressToCoordinates = (fields) => { return new Promise((resolve, reject) => { let address = `${fields.city}, ${fields.country}`; if (fields.location) { address = `${fields.location}, ${fields.city}, ${fields.country}`; } geocoder.geocode(address) .then((res) => { if (res.length === 0) { resolve('address not found'); } resolve([res[0].longitude, res[0].latitude]); }) .catch(err => reject(err)); }); }; const add = (creator, fields, files) => { return new Promise((resolve, reject) => { fields.owner = creator; return transformAdressToCoordinates(fields) .then((coordinatesTransformed) => { if (coordinatesTransformed === 'address not found') { coordinatesTransformed = [0, 0]; } const cover = files.splice(fields.coverIndex, 1); files.splice(0, 0, cover[0]); fields._fsIds = files; delete fields.coverIndex; if (fields.photoUrl === undefined) { fields.photoUrl = ''; } fields.location = { coordinates: coordinatesTransformed }; const newAd = new db.Adverts(fields); capitalize(newAd); newAd.save((err) => { if (err) { let message; if (err.code === 11000) { message = 'This advert already exists'; } else { message = 'Invalid data'; } return reject({ code: 1, message }); } resolve({ code: 0, message: 'Advert created' }); }); }); }); }; const remove = (userId, advertId) => { return new Promise((resolve, reject) => { db.Adverts .findOne({ _id: advertId, owner: userId }, 'owner active') .exec((err, advert) => { if (err) { return reject({ code: 1, message: err.message }); } if (advert === null) { return reject({ code: 2, message: 'No such advert' }); } advert.remove((removeErr) => { if (removeErr) { return reject({ code: 3, message: removeErr.message }); } resolve(); }); }); }); }; const removeAll = (userId) => { return new Promise((resolve, reject) => { db.Adverts .find({ owner: userId }) .exec((err, adverts) => { if (err) { return reject({ code: 1, message: err.message }); } Promise .all(adverts.map(advert => new Promise((resolveRemove, rejectRemove) => { advert.remove((removeErr) => { if (removeErr) { return rejectRemove({ code: 2, message: removeErr.message }); } resolveRemove(); }); }) )) .then(() => resolve()) .catch(removeAllErr => reject(removeAllErr)); }); }); }; const find = (advertId) => { return new Promise((resolve, reject) => { db.Adverts .findById(String(advertId), '-comments') .populate({ path: 'owner', select: 'profile.firstName profile.lastName' }) .lean() .exec((err, advert) => { if (err) { return reject({ code: 1, message: err.message }); } if (advert == null) { return reject({ code: 2, message: 'Advert not found' }); } const formatAndResolve = () => { if (advert.owner) { const ownerId = advert.owner._id; advert.owner = advert.owner.profile; advert.owner._id = ownerId; advert.owner.displayName = displayName(advert.owner); delete advert.owner.firstName; delete advert.owner.lastName; } else { advert.owner = { displayName: 'Deleted user' }; } resolve({ advert }); }; geocoder.reverse({ lat: advert.location.coordinates[1], lon: advert.location.coordinates[0] }) .then((res) => { advert.location = `${res[0].streetNumber || ''} ${res[0].streetName || ''}`.trim(); formatAndResolve(); }) .catch(formatAndResolve); }); }); }; const findAll = (userId) => { return new Promise((resolve, reject) => { db.Adverts .find({ active: true }) .populate({ path: 'owner', select: 'profile.firstName profile.lastName' }) .lean() .exec((err, adverts) => { if (err) { return reject({ code: 1, message: err.message }); } if (userId) { userManager.find(userId, 'profile.interests') .then(user => matchingService.matchAdverts(user.profile.interests, adverts)) .then((sorted) => { sorted.forEach((advert) => { if (advert.owner) { advert.ownerId = advert.owner._id; advert.owner = displayName(advert.owner.profile); } }); resolve(sorted); }); } else { adverts.forEach((advert) => { if (advert.owner) { advert.ownerId = advert.owner._id; advert.owner = displayName(advert.owner.profile); } }); resolve(adverts); } }); }); }; const findMain = (userId) => { return new Promise((resolve, reject) => { db.Adverts .find({ active: true }) .populate({ path: 'owner', select: 'profile.firstName profile.lastName' }) .lean() .limit(10) .exec((err, adverts) => { if (err) { return reject({ code: 1, message: err.message }); } if (userId) { userManager.find(userId, 'profile.interests') .then(user => matchingService.matchAdverts(user.profile.interests, adverts)) .then((sorted) => { sorted.forEach((advert) => { if (advert.owner) { advert.ownerId = advert.owner._id; advert.owner = displayName(advert.owner.profile); } }); resolve(sorted); }); } else { adverts.forEach((advert) => { if (advert.owner) { advert.ownerId = advert.owner._id; advert.owner = displayName(advert.owner.profile); } }); resolve(adverts); } }); }); }; const findAllFrom = (userId) => { return new Promise((resolve, reject) => { db.Adverts .find({ owner: String(userId) }, 'title description photoUrl active city country rate') .lean() .exec((err, adverts) => { if (err) { return reject({ code: 1, message: err.message }); } resolve(adverts); }); }); }; const findAllFromHim = (userId) => { return new Promise((resolve, reject) => { db.Adverts .find({ owner: String(userId), active: true }, 'title description photoUrl city country rate') .lean() .exec((err, adverts) => { if (err) { return reject({ code: 1, message: err.message }); } resolve(adverts); }); }); }; const findNear = (center, maxDistance) => { return new Promise((resolve, reject) => { db.Adverts .find({ active: true }) .near('location', { center, maxDistance: Number(maxDistance), spherical: true }) .lean() .exec((err, adverts) => { if (err) { return reject({ code: 4, message: err.message }); } resolve(adverts); }); }); }; const search = (regexSearch) => { return new Promise((resolve, reject) => { db.Adverts .find({ $or: regexSearch, active: true }) .populate({ path: 'owner', select: 'profile.firstName profile.lastName' }) .lean() .exec((err, adverts) => { if (err) { return reject({ code: 1, message: err.message }); } adverts.forEach((advert) => { if (advert.owner) { advert.ownerId = advert.owner._id; advert.owner = displayName(advert.owner.profile); } }); resolve(adverts); }); }); }; const findOwner = (advertId) => { return new Promise((resolve, reject) => { db.Adverts .findById(String(advertId)) .lean() .exec((err, advert) => { if (err) { return reject({ code: 1, message: err.message }); } if (advert == null) { return reject({ code: 2, message: 'Advert not found' }); } resolve(advert.owner); }); }); }; const update = (userId, advertId, advertBody, files) => { return new Promise((resolve, reject) => { db.Adverts .findOne({ _id: advertId, owner: userId }) .populate({ path: 'owner', select: 'profile.firstName profile.lastName' }) .exec((err, advert) => { if (err) { return reject({ code: 1, message: err.message }); } if (advert === null) { return reject({ code: 2, message: 'Cannot find advert' }); } return transformAdressToCoordinates(advertBody) .then((coordinatesTransformed) => { if (coordinatesTransformed === 'address not found') { coordinatesTransformed = [0, 0]; } const updatedFiles = (files.length > 0 ? files : advert._fsIds); const cover = updatedFiles.splice(advertBody.coverIndex, 1); updatedFiles.splice(0, 0, cover[0]); delete advertBody.coverIndex; delete advertBody.location; const mergedAdvert = _.merge(advert, advertBody); mergedAdvert._fsIds = updatedFiles; mergedAdvert.location.coordinates = coordinatesTransformed; capitalize(mergedAdvert); mergedAdvert.save((saveErr, updatedAdvert) => { if (saveErr) { let message; if (saveErr.code === 11000) { message = 'This advert already exists'; } else { message = 'Invalid update'; } return reject({ code: 3, message }); } if (updatedAdvert === null) { return reject({ code: 4, message: 'Failed to update advert' }); } const jsonAdvert = JSON.parse(JSON.stringify(updatedAdvert)); if (jsonAdvert.owner) { jsonAdvert.owner.displayName = displayName(jsonAdvert.owner.profile); delete jsonAdvert.owner.profile; } else { jsonAdvert.owner = { displayName: 'Deleted user' }; } resolve({ advert: jsonAdvert }); }); }); }); }); }; const updateRate = (visitId) => { return new Promise((resolve, reject) => { db.Visits .findById(visitId, 'about') .lean() .exec((err, visit) => { if (err) { return reject({ code: 1, message: err.message }); } resolve(visit.about); }); }) .then((advertId) => { return new Promise((resolve, reject) => { db.Visits .find({ about: String(advertId), visitorRate: { $ne: null, }, }, 'visitorRate') .lean() .exec((err, visits) => { if (err) { return reject({ code: 2, message: err.message }); } let averageRate = null; if (visits.length !== 0) { averageRate = visits.reduce((sum, visit) => sum + visit.visitorRate, 0) / visits.length; } resolve(averageRate); }); }) .then((rate) => { return new Promise((resolve, reject) => { db.Adverts.findByIdAndUpdate(advertId, { rate }) .exec((err) => { if (err) { return reject({ code: 3, message: err.message }); } resolve(); }); }); }); }); }; // const addOccupied = (userId, advertId, reqBody) => { // return new Promise((resolve, reject) => { // const occupied = reqBody.occupied; // // if (occupied === undefined) { return reject({ code: 1, message: 'Need occupied' }); } // if (occupied.from === undefined || occupied.to === undefined) { // return reject({ code: 2, message: 'Occupied has to be well formatted' }); // } // if (occupied.from.constructor !== Date || occupied.to.constructor !== Date) { // return reject({ code: 3, message: 'Occupied has to be expressed in Date' }); // } // // db.Adverts // .findOne({ // owner: userId, // _id: advertId, // }, 'occupied') // .exec((err, advert) => { // if (err) { return reject({ code: 1, message: err.message }); } // if (advert === null) { return reject({ code: 2, message: 'Cannot find advert' }); } // // advert.occupied.sort((a, b) => a.from - b.from); // const isNotPossible = advert.occupied.some((block) => { // if (block.from <= occupied.from && block.to > occupied.from) { // return true; // } // // if (occupied.from <= block.from && occupied.to > block.from) { // return true; // } // // return false; // }); // // if (isNotPossible) { return reject({ code: 3, message: 'Cannot fit this occupied in' }); } // // advert.occupied.push(occupied); // advert.occupied.sort((a, b) => a.from - b.from); // advert.save((saveErr, updatedAdvert) => { // if (saveErr) { return reject({ code: 4, messages: saveErr.message }); } // if (updatedAdvert === null) { return reject({ code: 5, message: 'Failed to update advert' }); } // // const jsonAdvert = JSON.parse(JSON.stringify(updatedAdvert)); // // if (jsonAdvert.owner) { // jsonAdvert.owner.displayName = displayName(jsonAdvert.owner.profile); // delete jsonAdvert.owner.profile; // } else { // jsonAdvert.owner = { displayName: 'Deleted user' }; // } // // resolve({ advert: jsonAdvert }); // }); // }); // }); // }; // const removeOccupied = (userId, advertId, reqBody) => { // return new Promise((resolve, reject) => { // const occupied = reqBody.occupied; // // if (occupied === undefined) { return reject({ code: 1, message: 'Need occupied' }); } // if (occupied.from === undefined || occupied.to === undefined) { // return reject({ code: 2, message: 'Occupied has to be well formatted' }); // } // if (occupied.from.constructor !== Date || occupied.to.constructor !== Date) { // return reject({ code: 3, message: 'Occupied has to be expressed in Date' }); // } // // db.Adverts // .findOne({ // owner: userId, // _id: advertId, // }, 'occupied') // .exec((err, advert) => { // if (err) { return reject({ code: 1, message: err.message }); } // if (advert === null) { return reject({ code: 2, message: 'Cannot find advert' }); } // // const index = advert.occupied.findIndex(occupy => occupy.from === occupied.from && occupy.to === occupy.to); // if (index !== -1) { // advert.occupied.remove(index); // advert.save((saveErr, updatedAdvert) => { // if (saveErr) { return reject({ code: 4, messages: saveErr.message }); } // if (updatedAdvert === null) { return reject({ code: 5, message: 'Failed to update advert' }); } // // const jsonAdvert = JSON.parse(JSON.stringify(updatedAdvert)); // // if (jsonAdvert.owner) { // jsonAdvert.owner.displayName = displayName(jsonAdvert.owner.profile); // delete jsonAdvert.owner.profile; // } else { // jsonAdvert.owner = { displayName: 'Deleted user' }; // } // // resolve({ advert: jsonAdvert }); // }); // } // // resolve({ advert }); // }); // }); // }; // const getOccupied = (userId, advertId) => { // return new Promise((resolve, reject) => { // db.Adverts // .findOne({ // owner: userId, // _id: advertId, // }, 'occupied') // .exec((err, advert) => { // if (err) { return reject({ code: 1, message: err.message }); } // if (advert === null) { return reject({ code: 2, message: 'Cannot find advert' }); } // // resolve(advert.occupied); // }); // }); // }; const toggle = (userId, advertId) => { return new Promise((resolve, reject) => { db.Adverts .findOne({ _id: advertId, owner: userId }, 'owner active') .exec((err, advert) => { if (err) { return reject({ code: 1, message: err.message }); } if (advert === null) { return reject({ code: 2, message: 'No such advert' }); } advert.active = !advert.active; advert.save((saveErr) => { if (saveErr) { return reject({ code: 3, message: saveErr.message }); } resolve(); }); }); }); }; const toggleOff = (userId, advertId) => { return new Promise((resolve, reject) => { db.Adverts .findOneAndUpdate({ _id: advertId, owner: userId }, { active: false }, (err, advert) => { if (err) { return reject({ code: 1, message: err.message }); } if (advert === null) { return reject({ code: 2, message: 'No such advert' }); } resolve(); }); }); }; const toggleAllOff = (userId) => { return findAllFromHim(userId) .then(adverts => Promise.all( adverts.map(advert => toggleOff(userId, advert._id)) ) ); }; module.exports = { add, remove, removeAll, findOwner, find, findAll, findMain, findAllFrom, findAllFromHim, findNear, search, toggle, toggleOff, toggleAllOff, update, updateRate }; <file_sep>'use strict'; const assertInput = (requirements, input) => { return requirements.find(requirement => Object.keys(input).indexOf(requirement) === -1 || input[requirement] === null); }; module.exports = { assertInput }; <file_sep>const db = require('../database'); const displayName = require('./profile').displayName; const create = (userId, idAdvert, reqBody) => { return new Promise((resolve, reject) => { db.Adverts.findById(idAdvert).exec((err, advert) => { if (err) { return reject({ code: 1, message: err.message }); } if (advert === null) { return reject({ code: 2, message: 'No such advert' }); } reqBody.owner = userId; const newComment = new db.Comments(reqBody); advert.comments.push(newComment); advert.save((saveErr) => { if (saveErr) return reject({ code: 3, message: saveErr }); resolve(); }); }); }); }; const findByCommentsAdvert = (idAdvert) => { return new Promise((resolve, reject) => { db.Adverts .findById(idAdvert, 'comments') .populate({ path: 'comments.owner', select: 'profile.firstName profile.lastName' }) .lean() .exec((err, commentsForAd) => { if (err) return reject({ code: 1, message: err.message }); if (commentsForAd === null) { return reject({ code: 2, message: 'No such advert' }); } commentsForAd.comments.forEach((comment) => { if (comment.owner) { if (comment.owner.displayName === undefined) { comment.owner.displayName = displayName(comment.owner.profile); } delete comment.owner.profile; } else { comment.owner = { displayName: 'Deleted user' }; } }); commentsForAd.comments.reverse(); resolve(commentsForAd); }); }); }; const toggleLike = (idUser, idAdvert, idComment) => { return new Promise((resolve, reject) => { db.Adverts .findById(idAdvert) .exec((err, advert) => { if (err) { return reject({ code: 1, message: err.message }); } if (advert === null) { return reject({ code: 2, message: 'No such advert' }); } const comment = advert.comments.id(idComment); if (comment.likes.indexOf(idUser) !== -1) { comment.likes.remove(idUser); } else { comment.likes.push(idUser); } advert.save((saveErr) => { if (saveErr) return reject({ code: 3, message: saveErr }); resolve(); }); }); }); }; const findByIdAndUpdate = (advertId, fields) => { return new Promise((resolve, reject) => { db.Adverts .findByIdAndUpdate( advertId, fields, { new: true }, (err) => { if (err) { return reject({ code: 1, message: err.message }); } resolve(); } ); }); }; module.exports = { create, findByCommentsAdvert, toggleLike, findByIdAndUpdate }; <file_sep>const express = require('express'); const multer = require('multer'); const mime = require('mime-types'); const path = require('path'); const advertHandler = require('../handlers/advert').Advert; const visitHandler = require('../handlers/visit').Visit; const commentAdvert = require('../handlers/commentAdvert').CommentAdvert; const upload = multer({ fileFilter(req, file, cb) { if (!mime.extension(file.mimetype).match(/^(jpeg|jpg|png|gif)$/)) { return cb(new Error(`The mimetype is not valid : ${file.mimetype}`)); } cb(null, true); }, dest: path.join(__dirname, '/../../assets/'), }); const filesUpload = upload.any(); const router = express.Router(); /** * @api {post} /adverts/ Create Advert * @apiName create * @apiGroup Advert * @apiVersion 0.3.2 * * @apiHeader {String} Authorization The jsonwebtoken given on <code>/public/sign-in</code> preceded by <code>Bearer</code> * @apiParam {String} title The title of the advert * @apiParam {String} country The country where the advert places the visit * @apiParam {String} city The city for the visit * @apiParam {String} description The description of the advert * @apiParam {String} photoUrl The web url to the cover for the advert * * @apiSuccess {Number} code Code representing the status of the request. * @apiSuccess {String} message A message to indicate if the Advert has been created. * * @apiSuccessExample Success-Response: * HTTP/1.1 200 OK * { * "code": 0, * "message": "Advert created" * } * * @apiUse DatabaseError * @apiUse UserNotFound */ router.post('/', (req, res) => { filesUpload(req, res, (err) => { if (err) return res.status(400).send({ code: 1, message: 'The mimetype is not valid must be jpeg|jpg|png|gif' }); advertHandler.create(req.user.userId, JSON.parse(req.body.proposalForm), req.files) .then(result => res.status(200).send(result)) .catch(error => res.status(500).send(error)); }); }); router.get('/', (req, res) => { advertHandler.findAllFrom(req.user.userId) .then(result => res.status(200).send({ adverts: result })) .catch(error => res.status(500).send(error)); }); router.put('/:id/toggle', (req, res) => { advertHandler.toggle(req.user.userId, req.params.id) .then(result => res.status(200).send({ adverts: result })) .catch(error => res.status(500).send(error)); }); router.post('/:id/visit', (req, res) => { visitHandler.create(req.user.userId, req.params.id, req.body) .then(result => res.status(200).send(result)) .catch(error => res.status(500).send(error)); }); router.put('/:id', (req, res) => { filesUpload(req, res, (err) => { if (err) return res.status(400).send({ code: 1, message: 'The mimetype is not valid must be jpeg|jpg|png|gif' }); let form = req.body.proposalForm; if (typeof form === 'string') { form = JSON.parse(form); } advertHandler.update(req.user.userId, req.params.id, form, req.files) .then(result => res.status(200).send(result)) .catch(error => res.status(500).send(error)); }); }); router.delete('/:id', (req, res) => { advertHandler.remove(req.user.userId, req.params.id) .then(result => res.status(200).send({ adverts: result })) .catch(error => res.status(500).send(error)); }); router.get('/:id/comments', (req, res) => { commentAdvert.findByCommentsAdvert(req.params.id) .then(result => res.status(200).send(result)) .catch(error => res.status(500).send(error)); }); router.post('/:id/comments', (req, res) => { commentAdvert.create(req.user.userId, req.params.id, req.body) .then(result => res.status(200).send(result)) .catch(error => res.status(500).send(error)); }); router.get('/geo/:distance', (req, res) => { advertHandler.findNear(req.user.userId, req.params.distance) .then(result => res.status(200).send(result)) .catch(error => res.status(500).send(error)); }); // router.put('/:id/comments/:idcomment', (req, res) => { // commentAdvert.edit(req.user.userId, req.params.id, req.params.idcomment) // .then(result => res.status(200).send(result)) // .catch(error => res.status(500).send(error)); // }); router.delete('/:id/comments/:idcomment', (req, res) => { commentAdvert.remove(req.user.userId, req.params.id, req.params.idcomment) .then(result => res.status(200).send({ comments: result, _id: req.params.id })) .catch(error => res.status(500).send(error)); }); router.put('/:id/comments/:idcomment/likes', (req, res) => { commentAdvert.toggleLike(req.user.userId, req.params.id, req.params.idcomment) .then(result => res.status(200).send(result)) .catch(error => res.status(500).send(error)); }); // router.put('/:id/occupied', (req, res) => { // advertHandler.addOccupied(req.user.userId, req.params.id, req.body) // .then(result => res.status(200).send(result)) // .catch(error => res.status(500).send(error)); // }); // // router.delete('/:id/occupied', (req, res) => { // advertHandler.removeOccupied(req.user.userId, req.params.id, req.body) // .then(result => res.status(200).send(result)) // .catch(error => res.status(500).send(error)); // }); // // router.get('/:id/occupied', (req, res) => { // advertHandler.getOccupied(req.user.userId, req.params.id) // .then(result => res.status(200).send(result)) // .catch(error => res.status(500).send(error)); // }); module.exports = router; <file_sep>const express = require('express'); const paymentHandler = require('../handlers/payment').Payment; const userManager = require('../managers/user'); const router = express.Router(); /** * @apiDefine UserNotConnected * @apiError (400) UserNotConnected The user is not logged in. */ /** * @apiDefine StripeError * @apiError (400) StripeError Encountered an error with Stripe, probably a bad request. */ router.use((req, res, next) => { // middleware to get the account for every request if (req.user) { userManager.find(req.user.userId, 'account', true) .then((user) => { req.loadedUser = user; next(); }) .catch(error => res.status(500).send(error)); } else { res.status(400).send({ code: 1, message: 'You need to be logged in' }); } }); /** * @api {get} /payment/ Find Stripe User * @apiName getUser * @apiGroup Payment * @apiVersion 0.3.2 * * @apiHeader {String} Authorization The jsonwebtoken given on <code>/public/sign-in</code> preceded by <code>Bearer</code> * * @apiSuccess {Object} customer A Stripe Customer object <a>https://stripe.com/docs/api/node#customer_object</a>. * @apiUse DatabaseError * @apiUse UserNotConnected * @apiUse StripeError */ router.get('/', (req, res) => { const user = req.loadedUser; if (user.account.paymentId == null) { paymentHandler.createUser(user) .then(result => res.status(200).send(result)) .catch(err => res.status(400).send(err)); } else { paymentHandler.getUser(user) .then(result => res.status(200).send(result)) .catch(err => res.status(400).send(err)); } }); /** * @api {post} /payment/card Add Card * @apiName addCard * @apiGroup Payment * @apiVersion 0.3.2 * * @apiHeader {String} Authorization The jsonwebtoken given on <code>/public/sign-in</code> preceded by <code>Bearer</code> * @apiParam {Number} expirationMonth The expiration month of the card * @apiParam {Number} expirationYear The expiration year of the card * @apiParam {String} number The card number * @apiParam {String} cvc The security code of the card (3 numbers behind the card) * * @apiSuccess {Object} source The newly created Bank Account object <a>https://stripe.com/docs/api/node#customer_create_bank_account</a>. * @apiUse DatabaseError * @apiUse UserNotConnected * @apiUse StripeError */ router.post('/card', (req, res) => { const user = req.loadedUser; paymentHandler.addCard(user.account.paymentId, req.body) .then(result => res.status(200).send(result)) .catch(err => res.status(400).send(err)); }); /** * @api {post} /payment/pay Create Payment * @apiName createPayment * @apiGroup Payment * @apiVersion 0.3.2 * * @apiHeader {String} Authorization The jsonwebtoken given on <code>/public/sign-in</code> preceded by <code>Bearer</code> * @apiParam {Number} amount Amount in currency units (for instance <code>23</code> as in <code>$23</code>) * @apiParam {String} idCard The id of the card used for this payment * @apiParam {String} description A description to explain the reason of this payment * * @apiSuccess {Object} charge The newly created Charge object for the selected Card Source <a>https://stripe.com/docs/api/node#create_charge</a>. * @apiUse DatabaseError * @apiUse UserNotConnected * @apiUse StripeError */ router.post('/pay', (req, res) => { const user = req.loadedUser; req.body.currency = 'eur'; paymentHandler.createPayment(user, req.body) .then(payment => res.status(200).send(payment)) .catch(err => res.status(400).send(err)); }); /** * @api {get} /payment/pay Get Payments * @apiName getAllPayments * @apiGroup Payment * @apiVersion 0.3.2 * * @apiHeader {String} Authorization The jsonwebtoken given on <code>/public/sign-in</code> preceded by <code>Bearer</code> * * @apiSuccess {Object[]} payments All Payments made by this User <a>https://stripe.com/docs/api/node#list_charges</a>. * @apiUse DatabaseError * @apiUse UserNotConnected * @apiUse StripeError */ router.get('/pay', (req, res) => { const user = req.loadedUser; paymentHandler.getAllPayments(user._id) .then(payments => res.status(200).send(payments)) .catch(err => res.status(400).send(err)); }); /** * @api {get} /payment/refounds Get Refound for guide * @apiName getAllPayments * @apiGroup Payment * @apiVersion 0.3.2 * * @apiHeader {String} Authorization The jsonwebtoken given on <code>/public/sign-in</code> preceded by <code>Bearer</code> * * @apiSuccess {Object[]} payments All refound for this User <a>https://stripe.com/docs/api/node#list_charges</a>. * @apiUse DatabaseError * @apiUse UserNotConnected * @apiUse StripeError */ router.get('/refounds', (req, res) => { const user = req.loadedUser; paymentHandler.getRefounds(user, false) .then(payments => res.status(200).send(payments)) .catch(err => res.status(400).send(err)); }); /** * @api {post} /payment/refounds Guive Refound to guide * @apiName getAllPayments * @apiGroup Payment * @apiVersion 0.3.2 * * @apiHeader {String} Authorization The jsonwebtoken given on <code>/public/sign-in</code> preceded by <code>Bearer</code> * * @apiSuccess {Object[]} payments All refound for this User <a>https://stripe.com/docs/api/node#list_charges</a>. * @apiUse DatabaseError * @apiUse UserNotConnected * @apiUse StripeError */ router.post('/refounds', (req, res) => { const user = req.loadedUser; paymentHandler.postRefounds(user, req.body) .then(payments => res.status(200).send(payments)) .catch(err => res.status(400).send(err)); }); /** * @api {get} /payment/refounded Get Refounded payement for guide * @apiName getAllPayments * @apiGroup Payment * @apiVersion 0.3.2 * * @apiHeader {String} Authorization The jsonwebtoken given on <code>/public/sign-in</code> preceded by <code>Bearer</code> * * @apiSuccess {Object[]} payments All refounded for this User <a>https://stripe.com/docs/api/node#list_charges</a>. * @apiUse DatabaseError * @apiUse UserNotConnected * @apiUse StripeError */ router.get('/refounded', (req, res) => { const user = req.loadedUser; paymentHandler.getRefounds(user, true) .then(payments => res.status(200).send(payments)) .catch(err => res.status(400).send(err)); }); /** * @api {get} /payment/pay/:id Get infos for one payment * @apiName getAllPayments * @apiGroup Payment * @apiVersion 0.3.2 * * @apiHeader {String} Authorization The jsonwebtoken given on <code>/public/sign-in</code> preceded by <code>Bearer</code> * * @apiSuccess {Object[]} return info of one payment <a>https://stripe.com/docs/api/node#list_charges</a>. * @apiUse DatabaseError * @apiUse UserNotConnected * @apiUse StripeError */ router.get('/pay/:id', (req, res) => { paymentHandler.getPayment(req.params.id) .then(payments => res.status(200).send(payments)) .catch(err => res.status(400).send(err)); }); /** * @api {post} /payment/pay Create Payment * @apiName createPayment * @apiGroup Payment * @apiVersion 0.3.2 * * @apiHeader {String} Authorization The jsonwebtoken given on <code>/public/sign-in</code> preceded by <code>Bearer</code> * @apiParam {Number} amount Amount in currency units (for instance <code>23</code> as in <code>$23</code>) * @apiParam {String} idCard The id of the card used for this payment * @apiParam {String} description A description to explain the reason of this payment * * @apiSuccess {Object} charge The newly created Charge object for the selected Card Source <a>https://stripe.com/docs/api/node#create_charge</a>. * @apiUse DatabaseError * @apiUse UserNotConnected * @apiUse StripeError */ router.delete('/card/:id', (req, res) => { const user = req.loadedUser; paymentHandler.deleteCard(user.account.paymentId, req.params.id) .then(payment => res.status(200).send(payment)) .catch(err => res.status(400).send(err)); }); module.exports = router; <file_sep>'use strict'; const request = require('supertest'); const expect = require('chai').expect; const server = require('../index'); const helpers = require('./helpers'); const nock = require('nock'); const db = require('../api/database'); describe('Private Account Routes', () => { let app, user; before((done) => { server.start((err, _app) => { if (err) return done(err); app = _app; helpers.createUser(_user => { user = _user; done(); }); }); }); after((done) => { helpers.deleteUser(user._id, () => { server.stop(done); }); }); describe('GET /accounts/:id', () => { it('should return 401 if token is not valid', (done) => { request(app) .get('/accounts/123412341234') .set('Content-Type', 'application/json') .expect(401, { code: 1, message: 'No authorization token was found' }, done); }); it('should return 401 if token not found', (done) => { request(app) .get('/accounts/123412341234') .set('Content-Type', 'application/json') .set('Authorization', 'Bearer <KEY>') .expect(401, { code: 1, message: 'Bad token authentication' }, done); }); it('should return 404 if id is not found', (done) => { request(app) .get('/accounts/123412341234') .set('Content-Type', 'application/json') .set('Authorization', 'Bearer ' + user.account.token) .expect(404, done); }); it('should return 200 and an account', (done) => { request(app) .get('/accounts/' + user._id) .set('Content-Type', 'application/json') .set('Authorization', 'Bearer ' + user.account.token) .expect(200, (err, res) => { if (err) done(err); expect(res.body.email).to.equal('<EMAIL>'); done(); }); }); }); describe('PUT /accounts/mail', () => { // Todo fix why middleware does not work as expected it.skip('should return 415 if header content-type not provided', (done) => { request(app) .put('/accounts/mail') .set('Authorization', 'Bearer ' + user.account.token) .expect(400, { code: 1, message: 'Missing "Content-Type" header set to "application/json"' }, done); }); it('should return 400 if email not provided', (done) => { request(app) .put('/accounts/mail') .set('Content-Type', 'application/json') .set('Authorization', 'Bearer ' + user.account.token) .expect(400, done); }); // todo the update does not work on the circle. it.skip('should return 200 and the new email', (done) => { request(app) .put('/accounts/mail') .set('Content-Type', 'application/json') .set('Authorization', 'Bearer ' + user.account.token) .send({email: '<EMAIL>'}) .expect(200, (err, res) => { if (err) done(err); console.log(user); expect(res.body.email).to.be.equal('<EMAIL>'); db.Users.findById(user._id, (err, user) => { if (err) done(err); expect(user.account.email).to.be.equal('<EMAIL>'); done(); }); }); }); }); describe('PUT /accounts/password', () => { it('should return 400 if password not provided', (done) => { request(app) .put('/accounts/password') .set('Content-Type', 'application/json') .set('Authorization', 'Bearer ' + user.account.token) .send({currentPassword: '<PASSWORD>'}) .expect(400, { code: 1, message: 'We need your password' }, done); }); it('should return 400 if currentPassword not provided', (done) => { request(app) .put('/accounts/password') .set('Content-Type', 'application/json') .set('Authorization', 'Bearer ' + user.account.token) .send({password: '<PASSWORD>'}) .expect(400, { code: 1, message: 'We need your currentPassword' }, done); }); it('should return 400 if password shorter', (done) => { request(app) .put('/accounts/password') .set('Content-Type', 'application/json') .set('Authorization', 'Bearer ' + user.account.token) .send({password: 'new', currentPassword: '<PASSWORD>'}) .expect(400, { code: 3, message: 'Invalid new password' }, done); }); it('should return 400 if wrong currentPassword', (done) => { request(app) .put('/accounts/password') .set('Content-Type', 'application/json') .set('Authorization', 'Bearer ' + user.account.token) .send({password: 'new', currentPassword: '<PASSWORD>'}) .expect(400, { code: 3, message: 'Invalid password' }, done); }); it('should return 200 and update the user password', (done) => { request(app) .put('/accounts/password') .set('Content-Type', 'application/json') .set('Authorization', 'Bearer ' + user.account.token) .send({password: '<PASSWORD>', currentPassword: '<PASSWORD>'}) .expect(200, done); }); }); describe('GET /accounts/:id/resend-email', () => { it('should return 200 if an email is sent', (done) => { let body; let emailSent = nock('https://api.mailgun.net/v3/mg.pickaguide.fr') .post(/messages/, function (b) { body = b; return true; }) .reply(200, {status: 'sent'}); request(app) .get('/accounts/' + user._id + '/resend-email') .set('Content-Type', 'application/json') .set('Authorization', 'Bearer ' + user.account.token) .expect(200, (err, res) => { if (err) done(err); expect(body.from).to.be.eql('<EMAIL>'); expect(body.to).to.be.eql('<EMAIL>'); expect(res.body.code).to.be.equal(0); expect(res.body.message).to.be.eql('Confirmation email has been resent'); expect(emailSent.isDone()).to.be.true; done(); }); }); }); describe('PUT /accounts/logout', () => { it('should logout a user deleting his token', (done) => { request(app) .put('/accounts/logout') .set('Content-Type', 'application/json') .set('Authorization', 'Bearer ' + user.account.token) .expect(200, (err, res) => { if (err) done(err); expect(res.body.code).to.be.equal(0); expect(res.body.message).to.be.eql('User logout'); db.Users.findById(user._id, (err, user) => { if (err) return done(err); expect(user.account.token).to.be.null; done(); }); }); }); }); }); <file_sep>const express = require('express'); const profileHandler = require('../../handlers/profile').Profile; const accountHandler = require('../../handlers/account').Account; const advertHandler = require('../../handlers/advert').Advert; const router = express.Router(); router.get('/filter/:userId/:search', (req, res) => { Promise.all([ profileHandler.search(req.params.search, req.params.userId), advertHandler.search(req.params.search, req.params.userId), ]) .then(results => accountHandler.areConfirmed(results[0].ids) .then((areConfirmedRes) => { areConfirmedRes.ids = areConfirmedRes.ids.map(String); const orderedAreConfirmed = results[0].ids.map(String).map(id => areConfirmedRes.areConfirmed[areConfirmedRes.ids.indexOf(id)] ); res.status(200).send({ profiles: results[0].profiles, ids: results[0].ids, adverts: results[1], areConfirmed: orderedAreConfirmed, }); }) ) .catch(error => res.status(400).send(error)); }); router.get('/filter/:search', (req, res) => { Promise.all([ profileHandler.search(req.params.search), advertHandler.search(req.params.search), ]) .then(results => accountHandler.areConfirmed(results[0].ids) .then((areConfirmedRes) => { areConfirmedRes.ids = areConfirmedRes.ids.map(String); const orderedAreConfirmed = results[0].ids.map(String).map(id => areConfirmedRes.areConfirmed[areConfirmedRes.ids.indexOf(id)] ); res.status(200).send({ profiles: results[0].profiles, ids: results[0].ids, adverts: results[1], areConfirmed: orderedAreConfirmed, }); }) ) .catch(error => res.status(400).send(error)); }); module.exports = router; <file_sep>#!/bin/bash FILES=$(find test -type f -name '*.test.js') CMD="echo \"Running backend tests\""; for f in $FILES do CMD="$CMD && PORT=3030 ./node_modules/.bin/mocha --compilers js:babel-core/register $f --timeout 10000" done eval $CMD <file_sep>const db = require('../database'); const _ = require('lodash'); const displayName = require('./profile').displayName; const create = (payerIdx, beneficiaryIdx, amountPayerx, amountBeneficiaryx, idVisitx) => { return new Promise((resolve, reject) => { const newPayment = new db.Payments({ payerId: payerIdx, beneficiaryId: beneficiaryIdx, amountPayer: amountPayerx, amountBeneficiary: amountBeneficiaryx, idVisit: idVisitx, }); newPayment.save((err, payment) => { if (err) { let message; if (err.code === 11000) { message = 'This payment already exists'; } else { message = 'Invalid data'; } return reject({ code: 1, message }); } resolve(payment); // resolve({ code: 0, message: 'Payment requested' }); }); }); }; const getRefounds = (user, refoundedx = false) => { return new Promise((resolve, reject) => { db.Payments .find({ beneficiaryId: user, refounded: refoundedx, payed: true}) .exec((err, Payments) => { if (err) { return reject({ code: 1, message: err.message }); } if (Payments == null) { return reject({ code: 2, message: 'You don\'t have any refound' }); } resolve({ Payments }); }); }); }; const getAveragePrice = (visitIds) => { return new Promise((resolve, reject) => { db.Payments .find({ idVisit: { $in: visitIds.map(String), }, }, 'amountPayer') .lean() .exec((err, payments) => { if (err) { return reject({ code: 1, message: err.message }); } let averagePrice; if (payments.length > 0) { averagePrice = payments.reduce((sum, payment) => { return sum + payment.amountPayer; }, 0) / payments.length; } return resolve(averagePrice); }); }); }; const getPayments = (user) => { return new Promise((resolve, reject) => { db.Payments .find({ $or: [{ payerId: user }, { beneficiaryId: user }] }) .lean() .sort('-date') .exec((err, Payments) => { if (err) { return reject({ code: 1, message: err.message }); } if (Payments == null) { return reject({ code: 2, message: 'You don\'t have any payment' }); } resolve({ Payments }); }); }); }; const getAmounts = (visitIds) => { return new Promise((resolve, reject) => { db.Payments .find({ idVisit: { $in: visitIds.map(String), }, }, 'amountPayer') .lean() .exec((err, payments) => { if (err) { return reject({ code: 1, message: err.message }); } return resolve(payments.map(payment => payment.amountPayer)); }); }); }; const getMyAmount = (visitId) => { return new Promise((resolve, reject) => { db.Payments .find({ idVisit: String(visitId), }, 'amountPayer') .lean() .exec((err, payments) => { if (err) { return reject({ code: 1, message: err.message }); } const amounts = payments.map(payment => payment.amountPayer); const amount = amounts.reduce((sum, price) => sum + price, 0); return resolve(amount); }); }); }; const paymentPayed = (payment, paymentId) => { return new Promise ((resolve, reject) => { payment.payed = true; payment.idPayment = paymentId payment.save((saveErr, updatedPayment) => { if (saveErr) { return reject({ code: 1, saveErr }); } if (updatedPayment === null) { return reject({ code: 2, message: 'Failed to update payment' }); } resolve({ visit: updatedPayment }); }); }) }; const paymentRefounded = (payment, paymentId) => { return new Promise ((resolve, reject) => { payment.refounded = true; payment.idRefound = paymentId payment.save((saveErr, updatedPayment) => { if (saveErr) { return reject({ code: 1, saveErr }); } if (updatedPayment === null) { return reject({ code: 2, message: 'Failed to update payment' }); } resolve({ visit: updatedPayment }); }); }) }; module.exports = { getAmounts, getMyAmount, getAveragePrice, create, getRefounds, getPayments, paymentPayed, paymentRefounded }; <file_sep>'use strict'; const request = require('supertest'); const expect = require('chai').expect; const server = require('../../index'); const nock = require('nock'); const db = require('../../api/database'); describe('Public Routes', () => { let app, userId, userTokenResetPassword; const userWithoutEmail = { firstName: 'userWithoutEmail', lastName: 'test', password: '<PASSWORD>' }; const userPasswordTooShort = { firstName: 'userPasswordTooShort', lastName: 'test', password: 'te', email: '<EMAIL>' }; const userEmailInvalid = { firstName: 'userPasswordTooShort', lastName: 'test', password: '<PASSWORD>', email: 'test@<PASSWORD>' }; const userValid = { firstName: 'userValid', lastName: 'test', password: '<PASSWORD>', email: '<EMAIL>' }; before((done) => { server.start((err, _app) => { if (err) return done(err); app = _app; done(); }); }); after((done) => { db.Users.findOne({'account.email': userValid.email}).remove().exec(() => { server.stop(done); }); }); describe('POST /public/sign-up', () => { it('should return error if param is missing', (done) => { request(app) .post('/public/sign-up') .send(userWithoutEmail) .expect(400, { code: 1, message: 'We need your email' }, done); }); it('should return error if email is invalid', (done) => { request(app) .post('/public/sign-up') .send(userEmailInvalid) .expect(400, { code: 2, message: 'Invalid email' }, done); }); it('should return error if password too short', (done) => { request(app) .post('/public/sign-up') .send(userPasswordTooShort) .expect(400, { code: 3, message: 'Invalid Password' }, done); }); it('should return 201 and create an user', (done) => { let body; let emailSent = nock('https://api.mailgun.net/v3/mg.pickaguide.fr') .post(/messages/, (result) => { body = result; return true; }) .reply(200, { status: 'sent' }); request(app) .post('/public/sign-up') .send(userValid) .expect(201, (err, res) => { if (err) done(err); expect(body.from).to.be.eql('<EMAIL>'); expect(body.to).to.be.eql(userValid.email); expect(res.body.code).to.equal(0); expect(res.body.message).to.eql('Account created'); expect(emailSent.isDone()).to.be.true; done(); }); }); it('should return error if user already exist', (done) => { request(app) .post('/public/sign-up') .send(userValid) .expect(400, { code: 1, message: 'This account already exists' }, done) }); }); describe('POST /public/sign-in', () => { it('should return error if email is wrong', (done) => { request(app) .post('/public/sign-in') .send(userPasswordTooShort) .expect(400, { code: 2, message: 'No account with this email' }, done) }); it('should return error if password is wrong', (done) => { const singinWrongPassword = { email: userValid.email, password: '<PASSWORD>' }; request(app) .post('/public/sign-in') .send(singinWrongPassword) .expect(400, { code: 2, message: 'Invalid password' }, done); }); it('should return a token and an id', (done) => { const singinuserValid = { email: userValid.email, password: <PASSWORD> }; request(app) .post('/public/sign-in') .send(singinuserValid) .expect(200, (err, res) => { if (err) done(err); expect(res.body).to.have.property('token'); expect(res.body).to.have.property('id'); userId = res.body.id; done(); }); }); it('should return a token created after a login', (done) => { const singinuserValid = { email: userValid.email, password: <PASSWORD> }; db.Users.findByIdAndUpdate(userId, { 'account.token': null }, { new: true }, (err, user) => { if (err) return done(err); expect(user.account.token).to.be.null; request(app) .post('/public/sign-in') .send(singinuserValid) .expect(200, (err, res) => { if (err) done(err); expect(res.body).to.have.property('token'); expect(res.body).to.have.property('id'); db.Users.findById(userId, (err, user) => { if (err) return done(err); expect(user.account.token).to.exist; done(); }); }); }); }); }); describe('GET /public/verify/:id', () => { it('should return err if id invalid', (done) => { request(app) .get('/public/verify/1234') .expect(404, done) }); it('should confirm the email address', (done) => { request(app) .get('/public/verify/' + userId) .expect(200, (err, res) => { expect(res.body.code).to.equal(0); expect(res.body.message).to.eql('Email verified'); db.Users.findById(userId, (err, user) => { if (err) return done(err); expect(user.account.emailConfirmation).to.be.true; done(); }); }); }); }); describe('POST /public/forgot', () => { it('should return error if email does not exist', (done) => { request(app) .post('/public/forgot/') .send({ 'email': userEmailInvalid.email }) .expect(404, { code: 2, message: 'No account with this email' }, done) }); it('should send an email and create resetPasswordToken', (done) => { let body; let emailSent = nock('https://api.mailgun.net/v3/mg.pickaguide.fr') .post(/messages/, function (b) { body = b; return true; }) .reply(200, {status: 'sent'}); request(app) .post('/public/forgot/') .send({'email': userValid.email}) .expect(200, (err, res) => { expect(res.body.code).to.equal(0); expect(res.body.message).to.eql('Reset password email has been sent'); expect(emailSent.isDone()).to.be.true; db.Users.findOne({'account.email': userValid.email}, (err, user) => { if (err) return done(err); expect(user.account.resetPasswordToken).to.exist; userTokenResetPassword = user.account.resetPasswordToken; done() }); }); }); }); describe('GET /public/reset/:token', () => { it('should return error if wrong token', (done) => { request(app) .get('/public/reset/12345') .expect(404, { code: 1, message: 'Password reset token is invalid' }, done) }); it('should return status 200 and validate the token reset password', (done) => { request(app) .get('/public/reset/' + userTokenResetPassword) .expect(200, { code: 0, message: 'Password reset token is valid' }, done); }); }); describe('POST /public/reset/:token', () => { it('should return error if wrong token', (done) => { request(app) .post('/public/reset/12345') .send({'password': '<PASSWORD>'}) .expect(404, { code: 1, message: 'Password reset token is invalid' }, done); }); it('should return error if password shorter', (done) => { request(app) .post('/public/reset/' + userTokenResetPassword) .send({'password': 'new'}) .expect(404, { code: 3, message: 'Invalid new Password' }, done); }); it('should update password of the user', (done) => { request(app) .post('/public/reset/' + userTokenResetPassword) .send({'password': '<PASSWORD>'}) .expect(200, (err, res) => { expect(res.body.code).to.equal(0); expect(res.body.message).to.eql('Password reset token is valid'); db.Users.findOne({'account.email': userValid.email}, (err, user) => { if(err) return done(err); user.comparePassword('<PASSWORD>', (err, isMatch) => { expect(isMatch).to.be.true; expect(user.account.resetPasswordToken).to.be.null; done(); }); }); }); }); }); }); <file_sep>'use strict'; const Promise = require('bluebird'); const visitManager = require('../managers/visit'); const advertManager = require('../managers/advert'); const paymentManager = require('../managers/payment'); const userManager = require('../managers/user'); const notifManager = require('../managers/notification'); const displayName = require('../managers/profile').displayName; const uploadService = require('../upload-service'); const rateService = require('../rate-service'); const _ = require('lodash'); class Visit { static update(userId, visitId, reqFiles = []) { return new Promise((resolve, reject) => { if (reqFiles.some(file => file.size > uploadService.maxFileSize().size)) { return reject({ code: 1, message: `File size exceeds ${uploadService.maxFileSize().label}` }); } Promise.mapSeries(reqFiles, file => uploadService.uploadImage(file.path, file.originalname, file.mimetype)) .then(values => visitManager.update(userId, visitId, values)) .then(advert => resolve(advert)) .catch(err => reject(err)); }); } static create(by, about, reqBody) { return new Promise((resolve, reject) => { advertManager .find(about) .then((result) => { if (result.advert.owner._id === undefined) { return reject({ code: 1, message: 'The user has been deleted' }); } if (String(result.advert.owner._id) === by) { return reject({ code: 2, message: 'You cannot ask yourself for a visit' }); } visitManager.create(by, about, reqBody) .then(visit => resolve(visit)) .catch(createErr => reject(createErr)) .then(() => notifManager.create(result.advert.owner._id, { title: 'You got a visitor !', body: `is asking to visit '${result.advert.title}' with you`, }, by)); }) .catch(err => reject(err)); }); } static downloadImageByHook(visitId, hook) { return uploadService.downloadImage(hook); } static getImageHooks(visitId) { return new Promise((resolve, reject) => { visitManager.find(visitId) .then(result => resolve(result.visit._fsIds)) .catch(error => reject(error)); }); } static find(visitId) { return visitManager.find(visitId); } static findAsGuide(visitId, userId) { return visitManager.findAsGuide(visitId, userId); } static findAsVisitor(visitId, userId) { return new Promise((resolve, reject) => visitManager .findAsVisitor(visitId, userId) .then((visit) => { if (visit.about && visit.about.owner) { userManager .findInIds([visit.about.owner], 'profile.firstName profile.lastName profile.phone account.email') .then((users) => { visit.with = displayName(users[0].profile); if (visit.status[visit.status.length - 1].label === 'accepted') { visit.contact = { phone: users[0].profile.phone, email: users[0].account.email }; } delete visit.about.owner; resolve({ visit }); }) .catch(findGuideErr => reject(findGuideErr)); } else { delete visit.about; visit.with = 'Unknown'; resolve({ visit }); } }) .catch(err => reject(err)) ); } static findAllFrom(userId) { return new Promise((resolve, reject) => visitManager .findAllFrom(userId) .then((visits) => { const ids = _.map(visits, 'about.owner'); userManager .findInIds(ids, 'profile.firstName profile.lastName') .then((users) => { const userHash = _.map(users, '_id').map(String); visits.forEach((visit) => { if (visit.about) { const index = userHash.indexOf(String(visit.about.owner)); visit.about.ownerName = displayName(users[index].profile); } }); resolve(visits); }) .catch(findGuideErr => reject(findGuideErr)); }) .catch(err => reject(err)) ); } static findAllFor(userId) { return new Promise((resolve, reject) => visitManager .findAllFor(userId) .then((visits) => { const ids = _.map(visits, 'by'); userManager .findInIds(ids, 'profile.firstName profile.lastName') .then((users) => { const userHash = _.map(users, '_id').map(String); visits.forEach((visit) => { if (visit.by) { const index = userHash.indexOf(String(visit.by)); visit.byName = displayName(users[index].profile); } else { visit.byName = 'Deleted user'; } }); resolve(visits); }) .catch(findVisitorErr => reject(findVisitorErr)); }) .catch(err => reject(err)) ); } static findToReview(userId) { return new Promise((resolve, reject) => { const results = {}; visitManager .findToReview(userId, 'visitor') .then((visits) => { const ids = _.map(visits, 'about.owner'); return userManager .findInIds(ids, 'profile.firstName profile.lastName') .then((users) => { const userHash = _.map(users, '_id').map(String); return Promise.mapSeries(visits, (visit) => { return new Promise((resolveVisit, rejectVisit) => { if (visit.about) { const index = userHash.indexOf(String(visit.about.owner)); visit.about.ownerName = (index !== -1 ? displayName(users[index].profile) : 'User deleted'); visitManager.findAllOf(visit.about._id) .then(otherVisits => paymentManager.getAveragePrice(otherVisits.map(otherVisit => otherVisit._id))) .then((price) => { visit.averagePrice = price; resolveVisit(visit); }) .catch(rejectVisit); } else { resolveVisit(visit); } }); }) .then((treatedVisits) => { results.myVisits = treatedVisits; return visitManager.findToReview(userId, 'guide'); }); }); }) .then((visits) => { const ids = _.map(visits, 'by'); userManager .findInIds(ids, 'profile.firstName profile.lastName') .then((users) => { const userHash = _.map(users, '_id').map(String); visits.forEach((visit) => { const index = userHash.indexOf(String(visit.by)); visit.byName = (index !== -1 ? displayName(users[index].profile) : 'User deleted'); }); results.theirVisits = visits; resolve(results); }) .catch(findErr => reject(findErr)); }) .catch(err => reject(err)); }); } static cancel(userId, visitId, reqBody) { return new Promise((resolve, reject) => { visitManager.cancel(userId, visitId, reqBody) .then(result => resolve(result)) .catch(error => reject(error)) .then(() => visitManager.getGuide(visitId)) .then(guide => notifManager.create(guide, { title: 'Your visit was cancelled', body: 'cancelled one of your visits', }, userId)); }); } static deny(userId, visitId, reqBody) { return new Promise((resolve, reject) => { visitManager.deny(userId, visitId, reqBody) .then(result => resolve(result)) .catch(error => reject(error)) .then(() => visitManager.getCreator(visitId)) .then(creator => notifManager.create(creator, { title: 'Your visit was denied', body: 'denied guiding you in one of your visits', }, userId)); }); } static accept(userId, visitId, reqBody) { return new Promise((resolve, reject) => { visitManager.accept(userId, visitId, reqBody) .then((result) => { return userManager.find(result.visit.by, 'profile.phone account.email', false) .then((creator) => { result.contact = { phone: creator.profile.phone, email: creator.account.email }; resolve(result); }) .then(() => notifManager.create(result.visit.by, { title: 'Your visit was accepted !', body: 'accepted to be guide in one of your visits, you will be exploring the city soon !', }, userId)); }) .catch(error => reject(error)); }); } static finish(userId, visitId, reqBody) { return new Promise((resolve, reject) => visitManager .finish(userId, visitId, reqBody) .then((result) => { visitManager.getCreator(visitId) .then(creator => userManager.setBlocking(creator, true) .then(() => notifManager.create(creator, { title: 'Your visit finished', body: 'marked one of your visits as completed', }, userId)) ) .then(() => userManager.setBlocking(userId, true)) .then(() => resolve(result)) .catch(blockErr => reject(blockErr)); }) .catch(err => reject(err)) ); } static review(userId, visitId, reqBody) { return new Promise((resolve, reject) => { let systemRate; visitManager .find(visitId) .then(result => visitManager.findAllOf(result.visit.about ? result.visit.about._id : '')) .then((visits) => { return userManager.find(userId, 'profile.rate') .then((user) => { return paymentManager.getAmounts(visits.map(el => el._id)) .then((prices) => { return paymentManager.getMyAmount(visitId) .then((price) => { systemRate = rateService.getSystemRating(prices, user.profile.rate || 3, price); }); }); }); }) .then(() => visitManager.review(userId, visitId, reqBody, systemRate)) .then(() => userManager.updateRate(userId)) .then(() => advertManager.updateRate(visitId)) .then(() => Visit.findToReview(userId)) .then((results) => { if (results.theirVisits.length === 0 && results.myVisits.length === 0) { userManager .setBlocking(userId, false) .then(() => resolve(results)) .catch(err => reject(err)); } else { resolve(results); } }) .catch(err => reject(err)); }); } } exports.Visit = Visit; <file_sep>'use strict'; const User = require('./user').User; const assertInput = require('./_handler').assertInput; const accountManager = require('../managers/account'); const blacklistManager = require('../managers/blacklist'); const validator = require('validator'); const emailService = require('../email-service'); const jwt = require('jsonwebtoken'); const config = require('config'); class Account extends User { static find(userId, updatable = false) { return new Promise((resolve, reject) => { super.find(userId, 'account.email', updatable) .then(user => resolve(updatable ? user : user.account)) .catch(err => reject(err)); }); } static findAll() { return new Promise((resolve, reject) => { super.findAll('account.email') .then(users => resolve({ accounts: users.map(user => user.account), ids: users.map(user => user._id), })) .catch(err => reject(err)); }); } static updatePassword(userId, reqBody) { return new Promise((resolve, reject) => { const failed = assertInput(['password', 'currentPassword'], reqBody); if (failed) { return reject({ code: 1, message: `We need your ${failed}` }); } super.find(userId, 'account.password', true) .then((user) => { user.comparePassword(reqBody.currentPassword, (err, isMatch) => { if (err) { return reject({ code: 2, message: err.message }); } if (!isMatch) { return reject({ code: 3, message: 'Invalid password' }); } if (!validator.isLength(reqBody.password, { min: 4, max: undefined })) { return reject({ code: 3, message: 'Invalid new password' }); } user.hash(reqBody.password, (hashed) => { user.account.password = <PASSWORD>; user.save((saveErr) => { if (saveErr) { return reject({ code: 4, message: saveErr.message }); } resolve({ code: 0, message: 'Password updated' }); }); }); }); }) .catch(err => reject(err)); }); } static updateMail(userId, reqBody) { return new Promise((resolve, reject) => { const failed = assertInput(['email'], reqBody); if (failed) { return reject({ code: 1, message: `We need your ${failed}` }); } if (!validator.isEmail(reqBody.email)) { return reject({ code: 2, message: 'Invalid email' }); } super.update(userId, { account: { email: reqBody.email, emailConfirmation: false } }) .then((user) => { this.resendEmail(userId) .then(() => resolve({ account: { email: user.account.email } })) .catch((mailErr) => { if (mailErr.code === 1) { resolve({ account: { email: user.account.email } }); } else { reject(mailErr); } }); }) .catch(err => reject(err)); }); } static signup(reqBody) { return new Promise((resolve, reject) => { const failed = assertInput(['firstName', 'lastName', 'password', 'email'], reqBody); if (failed) { return reject({ code: 1, message: `We need your ${failed}` }); } const account = { password: <PASSWORD>, email: reqBody.email }; const profile = { firstName: reqBody.firstName, lastName: reqBody.lastName }; if (!validator.isEmail(account.email)) { return reject({ code: 2, message: 'Invalid email' }); } if (!validator.isLength(account.password, { min: 4, max: undefined })) { return reject({ code: 3, message: 'Invalid Password' }); } if (!validator.isLength(profile.firstName, { min: 2, max: 50 })) { return reject({ code: 4, message: 'Invalid firstName' }); } if (!validator.isLength(profile.lastName, { min: 2, max: 50 })) { return reject({ code: 5, message: 'Invalid lastName' }); } blacklistManager .findByEmail(account.email) .then((blacklist) => { if (blacklist) { reject({ code: 6, message: 'You previously made an account with this email' }); } else { super.add({ account, profile }) .then(res => resolve(res)) .catch(err => reject(err)); } }) .catch(err => reject(err)); }); } static authenticate(email, password) { return new Promise((resolve, reject) => { super.findByEmail(email) .then((user) => { user.comparePassword(password, (err, isMatch) => { if (err) { return reject({ code: 1, message: err.message }); } if (!isMatch) { return reject({ code: 2, message: 'Invalid password' }); } if (!user.account.token) { user.account.token = jwt.sign({ userId: user._id }, config.jwtSecret); user.save((saveErr) => { if (saveErr) { reject({ code: 3, message: saveErr.message }); } }); } resolve({ token: user.account.token, id: user._id }); }); }) .catch(err => reject(err)); }); } static isAuthorised(req, res, next) { if (!req.user.userId) return res.status(401).send(); super.find(req.user.userId, 'account.token') .then((user) => { if (`Bearer ${user.account.token}` !== req.headers.authorization) { return res.status(401).send({ code: 1, message: 'Bad token authentication' }); } next(); }) .catch((findErr) => { if (findErr.code === 1) return res.status(500).send(); return res.status(401).send({ code: 1, message: 'Bad token authentication' }); }); } static isConfirmed(userId) { return new Promise((resolve, reject) => { super.find(userId, 'account.emailConfirmation') .then(user => resolve({ id: userId, isConfirmed: user.account.emailConfirmation })) .catch(err => reject(err)); }); } static areConfirmed(userIds) { return new Promise((resolve, reject) => { super.findInIds(userIds, 'account.emailConfirmation') .then(users => resolve({ areConfirmed: users.map(user => user.account.emailConfirmation), ids: users.map(user => user._id), })) .catch(err => reject(err)); }); } static verifyEmailAccount(userId) { return new Promise((resolve, reject) => { super.update(userId, { account: { emailConfirmation: true } }) .then(() => resolve({ code: 0, message: 'Email verified' })) .catch(err => reject(err)); }); } static resendEmail(userId) { return new Promise((resolve, reject) => { super.find(userId) .then((user) => { emailService.sendEmailConfirmation(user) .then(() => resolve({ code: 0, message: 'Confirmation email has been resent' })) .catch(err => reject(err)); }) .catch(err => reject(err)); }); } static sendResetPassword(email) { return new Promise((resolve, reject) => { super.findByEmail(email) .then((user) => { user.account.resetPasswordToken = jwt.sign({ issuer: 'www.pickaguide.com' }, config.jwtSecret); user.save((err) => { if (err) { reject({ code: 1, message: err.message }); } else { emailService.sendEmailPasswordReset(user) .then(() => resolve({ code: 0, message: 'Reset password email has been sent' })) .catch(emailErr => reject(emailErr)); } }); }) .catch(err => reject(err)); }); } static validateToken(token) { return accountManager.validateToken(token); } static resetPassword(token, password) { return accountManager.resetPassword(token, password); } static logout(userId) { return new Promise((resolve, reject) => { super.update(userId, { account: { token: null } }) .then(() => resolve({ code: 0, message: 'User logout' })) .catch(err => reject(err)); }); } } exports.Account = Account; <file_sep># pickaguide-api ## Documentation ### Generate npm run docs:generate Cette commande va générer la documentation de l'api ### View npm run docs:View Ceci va ouvrir la documentation actuelle dans un nouvel onglet du navigateur ## Launch in dev mode make dev Il faut aussi cloner le repository `pickaguide-ops` et aller dans `dev`, ensuite: make mongo Ceci lancera en local l'image docker de la base de données vide ## Launch tests make test-api ## Staging Après que votre branche soit mergée avec `dev` et que vous avez reçu dans slack dans le channel `#build` la notification d'une build réussie alors l'api sera actif sur (http://172.16.58.3:3030/) ou (http://pickaguide.fr:3030/) ## Production Après que `dev` soit mergée avec `master` et que vous avez reçu dans slack dans le channel `#build` la notification d'une build réussie alors l'api sera actif sur (https://172.16.58.3:3000/) ou (https://pickaguide.fr:3000/) <file_sep>const express = require('express'); const userHandler = require('../../handlers/user').User; const advertHandler = require('../../handlers/advert').Advert; const router = express.Router(); router.get('/:id/isGuide', (req, res) => { userHandler.isGuide(req.params.id) .then(result => res.status(200).send(result)) .catch(error => res.status(400).send(error)); }); router.get('/:id/proposals', (req, res) => { advertHandler.findAllFromHim(req.params.id) .then(result => res.status(200).send({ adverts: result })) .catch(error => res.status(500).send(error)); }); module.exports = router; <file_sep>'use strict'; const notificationManager = require('../managers/notification'); class Notification { static findAllFrom(idUser) { return notificationManager.findAllFrom(idUser); } static hasUnread(idUser) { return notificationManager.hasUnread(idUser); } static getUnread(idUser) { return notificationManager.getUnread(idUser); } static read(idNotif, idUser) { return new Promise((resolve, reject) => { notificationManager.read(idNotif, idUser) .then(() => notificationManager.findAllFrom(idUser)) .then(notifications => resolve({ notifications })) .catch(err => reject(err)); }); } static readAll(idUser) { return new Promise((resolve, reject) => { notificationManager.readAll(idUser) .then(() => notificationManager.findAllFrom(idUser)) .then(notifications => resolve({ notifications })) .catch(err => reject(err)); }); } } exports.Notification = Notification; <file_sep>'use strict'; const userManager = require('../managers/user'); const visitManager = require('../managers/visit'); const advertManager = require('../managers/advert'); const blacklistManager = require('../managers/blacklist'); const emailService = require('../email-service'); class User { static add(fields) { return new Promise((resolve, reject) => userManager .add(fields) .then(newUser => emailService.sendEmailConfirmation(newUser) .then(() => resolve({ code: 0, message: 'Account created' })) .catch((mailErr) => { if (mailErr.code === 1) { resolve({ code: 0, message: 'Account created' }); } else { reject(mailErr); } }) ) .catch(addErr => reject(addErr)) ); } static find(userId, selectFields = '', updatable = false) { return userManager.find(userId, selectFields, updatable); } static findInIds(userIds, selectFields = '', updatable = false) { return userManager.findInIds(userIds, selectFields, updatable); } static findAll(selectFields = '') { return userManager.findAll(selectFields); } static findByEmail(email) { return userManager.findByEmail(email); } static findByTerms(terms) { return userManager.findByTerms(terms); } static update(userId, reqBody) { return userManager.update(userId, reqBody); } static remove(userId, reqBody) { return new Promise((resolve, reject) => { userManager .remove(userId, reqBody) .then((user) => { visitManager.cancelAll(userId) .then(() => new Promise((resolveRetire, rejectRetire) => { userManager .isGuide(userId) .then((res) => { if (res.isGuide) { User .retire(userId) .then(() => advertManager.removeAll(userId)) .then(() => resolveRetire()) .catch(err => rejectRetire(err)); } else { resolveRetire(); } }) .catch(err => rejectRetire(err)); }) ) .then(() => blacklistManager.add({ email: user.account.email })) .then(() => { user.remove((removalErr) => { if (removalErr) { return reject({ code: 1, message: removalErr.message }); } resolve({ code: 0, message: 'Account deleted' }); }); }) .catch(err => reject(err)); }) .catch(err => reject(err)); }); } static isGuide(userId) { return userManager.isGuide(userId); } static isBlocking(userId) { return userManager.isBlocking(userId); } static becomeGuide(userId) { return userManager.becomeGuide(userId); } static retire(userId) { return new Promise((resolve, reject) => visitManager.denyAll(userId) .then(() => advertManager.toggleAllOff(userId)) .then(() => userManager .findByIdAndUpdate(userId, { isGuide: false }) .then(user => resolve({ id: userId, isGuide: user.isGuide })) .catch(updateErr => reject(updateErr)) ) .catch(err => reject(err)) ); } static findNear(geo, distance) { return userManager.findNear(geo, distance); } } exports.User = User; <file_sep>const db = require('../database'); const add = (fields) => { return new Promise((resolve, reject) => { const newBlacklist = new db.Blacklists(fields); newBlacklist.save((err) => { if (err) { let message; if (err.code === 11000) { message = 'This blacklist already exists'; } else { message = 'Invalid data'; } return reject({ code: 1, message }); } resolve(newBlacklist); }); }); }; const findByEmail = (email) => { return new Promise((resolve, reject) => { db.Blacklists .findOne({ email }) .lean() .exec((err, blacklist) => { if (err) { return reject({ code: 1, message: err.message }); } resolve(blacklist); }); }); }; module.exports = { add, findByEmail }; <file_sep>'use strict'; const userManager = require('./managers/user'); exports.errorsTokenMissing = function errorsTokenMissing(err, req, res, next) { // eslint-disable-line no-unused-vars if (err.name === 'UnauthorizedError') { return res.status(401).send({ code: 1, message: err.message, }); } return res.status(500).send({ code: 1, message: err, }); }; exports.checkContentTypeHeader = (err, req, res, next) => { if (['PUT', 'POST'].indexOf(req.method) !== -1 && req.url.indexOf('avatar') === -1) { if (req.headers['content-type'] !== 'application/json') { return res.status(415).send({ code: 1, message: 'Missing "Content-Type" header set to "application/json"', }); } } next(); }; exports.trimForm = function trimForm(req, res, next) { if (req.body) { const keys = Object.keys(req.body); keys.forEach((key) => { const value = req.body[key]; if (typeof value === 'string') { req.body[key] = value.trim(); } }); } next(); }; exports.checkUserIsBlocked = function checkUserIsBlocked(req, res, next) { if (req.user === undefined) { return next(); // the user is not logged in } const whitelisted = [ new RegExp(/^\/users\/isBlocking$/), new RegExp(/^\/accounts\/logout$/), new RegExp(`^/accounts/${req.user.userId}`), new RegExp(`^/profiles/${req.user.userId}`), new RegExp(/^\/notifications\/hasUnread/), new RegExp(/^\/notifications\/unread/), new RegExp(/^\/notifications/), new RegExp(/^\/proposals\/[a-z0-9]{24}\/comments/), new RegExp(/^\/payment\//), new RegExp(/^\/visits\/review$/), new RegExp(/^\/visits\/[a-z0-9]{24}\/review$/), ]; if (whitelisted.reduce((a, b) => a || RegExp(b).test(req.url), false) === false) { userManager.isBlocking(req.user.userId) .then((user) => { if (user.isBlocking) { return res.status(403).send({ code: 1, message: 'Your account is blocked, please review all visits first', }); } next(); }) .catch(err => res.status(500).send(err)); } else { next(); } };
e6fd1708b8f58b171d72b31a24e275b5ce808b51
[ "JavaScript", "Markdown", "Shell" ]
35
JavaScript
Bozotek/pickaguide-api
51f0969716bbcb428464acde82c1a4bfd2092abc
4913c9c1e1316d5381d7aa7806381ff17d9838ae
refs/heads/master
<file_sep>class AddComicIdToPanels < ActiveRecord::Migration def change add_column :panels, :comic_id, :integer add_index :panels, :comic_id end end <file_sep>class Admin::Comics::PanelsController < ApplicationController def index @comic = Comic.find params[:comic_id] @panels = @comic.panels.all end def show @comic = Comic.find params[:comic_id] @panel = @comic.panels.find params[:id] end def new @comic = Comic.find params[:comic_id] @panel = @comic.panels.build end def edit @comic = Comic.find params[:comic_id] @panel = @comic.panels.find params[:id] end def create @comic = Comic.find params[:comic_id] @panel = @comic.panels.new params[:panel] if @panel.save flash[:notice] = 'Panel was successfully created.' redirect_to admin_comic_path( @comic ) else render 'new' end end def update @comic = Comic.find params[:comic_id] @panel = @comic.panels.find params[:id] if @panel.update_attributes params[:panel] flash[:notice] = 'Panel was successfully updated.' redirect_to admin_comic_path( @comic ) else flash[:error] = @panel.errors.full_messages.to_sentence render 'edit' end end def destroy @comic = Comic.find params[:comic_id] @panel = @comic.panels.find params[:id] @panel.destroy flash[:notice] = 'Panel was successfully deleted.' redirect_to admin_comic_path( @comic ) end end <file_sep>class Comic < ActiveRecord::Base attr_accessible :order_id, :title validates_presence_of :order_id validates_uniqueness_of :order_id has_many :panels, :order => 'order_id asc' end <file_sep>class Panel < ActiveRecord::Base attr_accessible :order_id, :image validates_presence_of :order_id validates_uniqueness_of :order_id has_attached_file :image, :styles => { :medium => "230x230>", :thumb => "100x100>" } belongs_to :comic end <file_sep>class StaticPagesController < ApplicationController def home end def archive @comics = Comic.all( :order => 'order_id desc' ) end def about end def contact end end <file_sep>class Admin::ComicsController < AdminController def index @comics = Comic.all( :order => 'order_id' ) end def show @comic = Comic.find params[:id] @panels = @comic.panels end def new @comic = Comic.new end def edit @comic = Comic.find params[:id] end def create @comic = Comic.new params[:comic] if @comic.save flash[:notice] = 'Comic was successfully created.' redirect_to [:admin, @comic] else render 'new' end end def update @comic = Comic.find params[:id] if @comic.update_attributes(params[:comic]) flash[:notice] = 'Comic was successfully updated.' redirect_to [:admin, @comic] else flash[:notice] = @comic.errors.full_messages.to_sentence render 'edit' end end def destroy @comic = Comic.find(params[:id]) @comic.destroy flash[:notice] = 'Comic was successfully deleted.' redirect_to admin_comics_path end end
c9c8ce61e45424c6a41e5ac3bb3b3a679940af43
[ "Ruby" ]
6
Ruby
bohuie/doggie_commic
f1e675ca5503340e2fa63042b011b3766bc5a03e
929a48221d8618616e56e632efd389456d433ae7
refs/heads/master
<file_sep>// // Created by 松本拓真 on 2019/11/06. // #include "gtest/gtest.h" #include "bo/popcnt.hpp" namespace { constexpr int N = 1<<16; uint64_t rand64() { return uint64_t(random()) | (uint64_t(random()) << 32); } } TEST(Popcnt, 64) { for (int i = 0; i < N; i++) { uint64_t x = rand64(); int cnt = 0; for (int j = 0; j < 64; j++) { if (x & (1ull<<j)) cnt++; } EXPECT_EQ(bo::popcnt_u64(x), cnt); } } TEST(Popcnt, 32) { for (int i = 0; i < N; i++) { uint32_t x = random(); int cnt = 0; for (int j = 0; j < 32; j++) { if (x & (1u<<j)) cnt++; } EXPECT_EQ(bo::popcnt_u32(x), cnt); } } TEST(Popcnt, 16) { for (int i = 0; i < N; i++) { uint16_t x = random() % (1u<<16); int cnt = 0; for (int j = 0; j < 16; j++) { if (x & (1u<<j)) cnt++; } EXPECT_EQ(bo::popcnt_u16(x), cnt); } } TEST(Popcnt, 8) { for (int i = 0; i < N; i++) { uint8_t x = random() % (1u<<8); int cnt = 0; for (int j = 0; j < 8; j++) { if (x & (1u<<j)) cnt++; } EXPECT_EQ(bo::popcnt_u8(x), cnt); } } <file_sep>#ifndef PLAIN_DA_TRIES__BIT_VECTOR_HPP_ #define PLAIN_DA_TRIES__BIT_VECTOR_HPP_ #include <cstdint> #include <vector> namespace plain_da { class BitVector : private std::vector<uint64_t> { using _base = std::vector<uint64_t>; private: size_t size_; public: BitVector() : size_(0) {} explicit BitVector(size_t size) : _base(size > 0 ? (size-1)/64+1 : 0), size_(size) {} size_t size() const { return size_; } void resize(size_t new_size) { _base::resize(new_size > 0 ? (new_size-1)/64+1 : 0); size_ = new_size; } const uint64_t* data() const { return _base::data(); } uint64_t* data() { return _base::data(); } uint64_t word(size_t wi) const { return wi < _base::size() ? _base::operator[](wi) : 0ull; } uint64_t bits64(size_t offset) const { auto inset = offset % 64; auto block = offset / 64; if (inset == 0) { return word(block); } else { return (word(block) >> inset) | (word(block + 1) << (64 - inset)); } } class reference { public: using pointer = uint64_t*; private: pointer ptr_; uint64_t mask_; friend class BitVector; reference(pointer ptr, uint64_t mask) : ptr_(ptr), mask_(mask) {} public: operator bool() const { return (*ptr_ & mask_) != 0; } reference operator=(bool bit) { if (bit) { *ptr_ |= mask_; } else { *ptr_ &= ~mask_; } return *this; } }; class const_reference { public: using pointer = const uint64_t*; private: pointer ptr_; uint64_t mask_; friend class BitVector; const_reference(pointer ptr, uint64_t mask) : ptr_(ptr), mask_(mask) {} public: operator bool() const { return (*ptr_ & mask_) != 0; } }; reference operator[](size_t pos) { return reference(_base::data() + pos/64, 1ull<<(pos%64)); } const_reference operator[](size_t pos) const { return const_reference(_base::data() + pos/64, 1ull<<(pos%64)); } private: template<bool IsConst> class _iterator { public: using reference = std::conditional_t<!IsConst, BitVector::reference, BitVector::const_reference>; using pointer = std::conditional_t<!IsConst, uint64_t*, const uint64_t*>; using value_type = reference; using difference_type = long long; using iterator_category = std::random_access_iterator_tag; private: pointer ptr_; uint8_t ctz_; friend class BitVector; _iterator(pointer ptr, unsigned ctz) : ptr_(ptr), ctz_(ctz) {} public: reference operator*() const { return reference(ptr_, 1ull << ctz_); } _iterator& operator++() { if (ctz_ < 63) ++ctz_; else { ++ptr_; ctz_ = 0; } return *this; } _iterator operator++(int) { _iterator ret = *this; ++*this; return ret; } _iterator& operator--() { if (ctz_ > 0) --ctz_; else { --ptr_; ctz_ = 63; } } _iterator operator--(int) { _iterator ret = *this; --*this; return ret; } _iterator operator+(long long shifts) const { long long i = ctz_ + shifts; if (i >= 0) { return _iterator(ptr_ + i / 64, i % 64); } else { return _iterator(ptr_ - (-i-1) / 64 + 1, (i % 64 + 64) % 64); } } friend _iterator operator+(difference_type shifts, _iterator it) { return it + shifts; } _iterator& operator+=(difference_type shifts) { return *this = *this + shifts; } _iterator operator-(difference_type shifts) const { return operator+(-shifts); } _iterator& operator-=(difference_type shifts) { return *this = *this - shifts; } difference_type operator-(_iterator rhs) const { return difference_type(ptr_ - rhs.ptr_) * 64 + ((difference_type) ctz_ - rhs.ctz_); } reference operator[](size_t i) const { return *(*this + i); } bool operator<(_iterator rhs) const { return ptr_ != rhs.ptr_ ? ptr_ < rhs.ptr_ : ctz_ < rhs.ctz_; } bool operator>(_iterator rhs) const { return rhs < *this; } bool operator==(_iterator rhs) const { return ptr_ == rhs.ptr_ and ctz_ == rhs.ctz_; } bool operator<=(_iterator rhs) const { return ptr_ != rhs.ptr_ ? ptr_ < rhs.ptr_ : ctz_ <= rhs.ctz_; } bool operator>=(_iterator rhs) const { return rhs <= *this; } }; public: using iterator = _iterator<false>; using const_iterator = _iterator<true>; iterator begin() { return iterator(_base::data(), 0); } const_iterator cbegin() const { return const_iterator(_base::data(), 0); } const_iterator begin() const { return cbegin(); } iterator end() { return iterator(_base::data() + (size()-1) / 64, (size() - 1) % 64); } const_iterator cend() const { return const_iterator(_base::data() + (size()-1) / 64, (size() - 1) % 64); } const_iterator end() const { return cend(); } }; } #endif //PLAIN_DA_TRIES__BIT_VECTOR_HPP_ <file_sep>// // Created by 松本拓真 on 2019/11/06. // #include "gtest/gtest.h" #include "bo/clz.hpp" namespace { constexpr int N = 1<<16; uint64_t rand64() { return uint64_t(random()) | (uint64_t(random()) << 32); } } TEST(Clz, 64) { for (int i = 0; i < N; i++) { auto val = rand64(); int clz = 64; for (int j = 63; j >= 0; j--) { if (val & (1ull << j)) { clz = 63 - j; break; } } EXPECT_EQ(bo::clz_u64(val), clz); } } <file_sep>cmake_minimum_required(VERSION 3.10) project(plain-da-tries CXX) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_FLAGS "-Wall -Wno-sign-compare -march=native -O3") if(NOT CMAKE_BUILD_TYPE) set(CMAKE_BUILD_TYPE Release) endif() add_subdirectory(libbo EXCLUDE_FROM_ALL) add_executable(bench benchmark.cpp) target_link_libraries(bench libbo) enable_testing() file(GLOB TEST_SOURCES *_test.cpp) foreach(TEST_SOURCE ${TEST_SOURCES}) get_filename_component(TEST_SOURCE_NAME ${TEST_SOURCE} NAME_WE) add_executable(${TEST_SOURCE_NAME} ${TEST_SOURCE}) target_link_libraries(${TEST_SOURCE_NAME} libbo) add_test(NAME ${TEST_SOURCE_NAME} COMMAND ${TEST_SOURCE_NAME}) endforeach() <file_sep>#include "convolution.hpp" #include <iostream> using namespace plain_da::convolution; constexpr int _f[4] = {1,5,3,4}; constexpr int _g[4] = {5,2,1,3}; constexpr int expected[4] = {30,40,39,34}; int main() { std::cout << "Test index_xor_convolution..." << std::endl; int f[4], g[4]; for (int i = 0; i < 4; i++) { f[i] = _f[i]; g[i] = _g[i]; } fwt(g, 4); index_xor_convolution_for_xcheck(f, g, 4); for (int i = 0; i < 4; i++) { if (f[i] != expected[i]) { std::cout << "Test failed" << std::endl; std::cout << "f: \t\t"; for (int i = 0; i < 4; i++) std::cout << _f[i] << ' '; std::cout << std::endl; std::cout << "g: \t\t"; for (int i = 0; i < 4; i++) std::cout << _g[i] << ' '; std::cout << std::endl; std::cout << "expected: \t"; for (int i = 0; i < 4; i++) std::cout << expected[i] << ' '; std::cout << std::endl; std::cout << "result: \t"; for (int i = 0; i < 4; i++) std::cout << f[i] << ' '; std::cout << std::endl; return 1; } } std::cout << "OK" << std::endl; return 0; } <file_sep>#ifndef PLAIN_DA_TRIES__DEFINITION_HPP_ #define PLAIN_DA_TRIES__DEFINITION_HPP_ namespace plain_da { constexpr uint8_t kLeafChar = '\0'; constexpr size_t kAlphabetSize = 1u << 8; } #endif //PLAIN_DA_TRIES__DEFINITION_HPP_ <file_sep>#ifndef PLAIN_DA_TRIES__TAIL_HPP_ #define PLAIN_DA_TRIES__TAIL_HPP_ #include <vector> #include <string> #include <string_view> #include <queue> #include <cassert> namespace plain_da { class TailConstructor { public: std::vector<std::pair<std::string, size_t>> key_vec_; std::vector<size_t> index_; std::vector<char> arr_; friend class Tail; public: size_t push(const std::string& key) { auto id = key_vec_.size() + 1; key_vec_.emplace_back(key, id); return id; } void Construct() { if (key_vec_.empty()) return; arr_.resize(1, kLeafChar); size_t n = key_vec_.size(); std::sort(key_vec_.begin(), key_vec_.end(), [](auto& l, auto& r) { auto& lkey = l.first; auto& rkey = r.first; return std::lexicographical_compare(lkey.rbegin(), lkey.rend(), rkey.rbegin(), rkey.rend()); }); index_.resize(n+1, -1); auto it = key_vec_.begin(); std::queue<std::pair<size_t, size_t>> idqueue; idqueue.emplace(it->second, it->first.length()); std::string* prev = &it->first; ++it; auto construct = [&]() { for (uint8_t c : *prev) arr_.push_back(c); arr_.push_back(kLeafChar); while (!idqueue.empty()) { auto [id, len] = idqueue.front(); idqueue.pop(); assert(id > 0); assert(len <= prev->length()); index_[id] = arr_.size() - 1 - len; assert(index_[id] > 0); if (index_[id] >= 1 << 31) { throw "Too large tail length for embedded 31bit pointer."; } } }; for (; it != key_vec_.end(); ++it) { auto& [key, id] = *it; bool mergeable = prev->length() <= key.length(); if (mergeable) { auto rit = prev->rbegin(); auto kit = key.rbegin(); for (; mergeable and rit != prev->rend(); ++rit, ++kit) { mergeable &= *rit == *kit; } } if (!mergeable) { construct(); } prev = &it->first; idqueue.emplace(id, key.length()); } construct(); arr_.shrink_to_fit(); } size_t map_to(size_t id) const { return index_[id]; } }; class Tail { private: std::vector<char> arr_; public: Tail() = default; explicit Tail(TailConstructor&& constructor) : arr_(std::move(constructor.arr_)) {} size_t size() const { return arr_.size(); } char operator[](size_t i) const { return arr_[i]; } std::string_view label(size_t i) const { return std::string_view(arr_.data() + i); } }; } #endif //PLAIN_DA_TRIES__TAIL_HPP_ <file_sep>/* This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. For more information, please refer to <https://unlicense.org> */ #ifndef BO_SUMMARY_HPP_ #define BO_SUMMARY_HPP_ #ifdef _MSC_VER #include <intrin.h> #else #include <x86intrin.h> #endif namespace bo { // summarize x_{0-7} by follows: // { 0: x = 0 // 1: 1 <= x < 256 inline uint8_t summary_u64_each8(uint64_t x) { #ifdef __MMX__ auto c = uint64_t(_mm_cmpeq_pi8(__m64(x), __m64(0ull))); c = ~c & 0x8080808080808080ull; #else constexpr uint64_t hmask = 0x8080808080808080ull; constexpr uint64_t lmask = 0x7F7F7F7F7F7F7F7Full; uint64_t a = x & hmask; uint64_t b = x & lmask; b = hmask - b; b = ~b; auto c = (a | b) & hmask; #endif c *= 0x0002040810204081ull; return c >> 56; } } // namespace bo #endif //BO_SUMMARY_HPP_ <file_sep>#include "convolution.hpp" #include <iostream> using namespace plain_da::convolution; using mint = ModuloNTT; constexpr mint _f[8] = {1,5,3,4,0,0,0,0}; constexpr mint _g[8] = {5,2,1,3,0,0,0,0}; constexpr mint expected[8] = {5,27,26,34,26,13,12,0}; int main() { std::cout << "Test index_sum_convolution..." << std::endl; mint f[8], g[8]; for (int i = 0; i < 8; i++) { f[i] = _f[i]; g[i] = _g[i]; } ntt(g, 8); index_sum_convolution_for_xcheck(f, g, 8); for (int i = 0; i < 8; i++) { if (f[i] != expected[i]) { std::cout << "Test failed" << std::endl; std::cout << "f: \t\t\t"; for (int i = 0; i < 8; i++) std::cout << _f[i].val() << ' '; std::cout << std::endl; std::cout << "g: \t\t\t"; for (int i = 0; i < 8; i++) std::cout << _g[i].val() << ' '; std::cout << std::endl; std::cout << "expected: \t"; for (int i = 0; i < 8; i++) std::cout << expected[i].val() << ' '; std::cout << std::endl; std::cout << "result: \t"; for (int i = 0; i < 8; i++) std::cout << f[i].val() << ' '; std::cout << std::endl; return 1; } } std::cout << "OK" << std::endl; return 0; } <file_sep>#ifndef PLAIN_DA_TRIES__KEYSET_HPP_ #define PLAIN_DA_TRIES__KEYSET_HPP_ #include <cstdint> #include <vector> #include <string_view> namespace plain_da { class KeysetHandler { public: using value_type = std::string_view; using iterator = std::vector<std::string_view>::iterator; using const_iterator = std::vector<std::string_view>::const_iterator; private: std::vector<uint8_t> storage_; std::vector<std::string_view> sv_list_; std::vector<std::pair<size_t, size_t>> pls_; public: KeysetHandler() = default; explicit KeysetHandler(std::istream& is) { for (std::string key; std::getline(is, key); ) insert(key); update_list(); } void insert(std::string_view key) { size_t front = storage_.size(); storage_.resize(storage_.size() + key.length()+1); for (int i = 0; i < key.length(); i++) storage_[front + i] = key[i]; storage_[front + key.length()] = '\0'; pls_.emplace_back(front, key.length()); } void update_list() { sv_list_.clear(); sv_list_.reserve(pls_.size()); for (auto [p, l] : pls_) sv_list_.emplace_back((const char*) storage_.data() + p, l); pls_ = {}; } size_t size() const { return sv_list_.size(); } std::string_view operator[](size_t i) const { return sv_list_[i]; } const_iterator begin() const { return sv_list_.begin(); } const_iterator cbegin() const { return sv_list_.cbegin(); } const_iterator end() const { return sv_list_.end(); } const_iterator cend() const { return sv_list_.cend(); } }; class RawTrie { public: static constexpr uint8_t kLeafChar = '\0'; struct Edge { uint8_t c = kLeafChar; int next = -1; }; using TableType = std::vector<std::vector<Edge>>; using const_iterator = TableType::const_iterator; private: TableType edge_table_; public: explicit RawTrie(const KeysetHandler& keyset) { using key_iterator = typename KeysetHandler::const_iterator; auto dfs = [&]( const auto dfs, const key_iterator begin, const key_iterator end, int depth ) -> size_t { size_t cur_node = edge_table_.size(); edge_table_.emplace_back(); assert(begin < end); auto keyit = begin; if (keyit->size() == depth) { edge_table_[cur_node].push_back({kLeafChar, -1}); ++keyit; } auto pit = keyit; uint8_t pibot_char = kLeafChar; while (keyit < end) { uint8_t c = (*keyit)[depth]; if (pibot_char < c) { if (pit < keyit) { assert(!edge_table_[cur_node].empty()); edge_table_[cur_node].back().next = dfs(dfs, pit, keyit, depth+1); } edge_table_[cur_node].push_back({c, -1}); pit = keyit; pibot_char = c; } ++keyit; } if (pit < keyit) { assert(!edge_table_[cur_node].empty()); edge_table_[cur_node].back().next = dfs(dfs, pit, keyit, depth+1); } return cur_node; }; dfs(dfs, keyset.begin(), keyset.end(), 0); } size_t size() const { return edge_table_.size(); } const std::vector<Edge>& operator[](size_t idx) const { return edge_table_[idx]; } const_iterator begin() const { return edge_table_.begin(); } const_iterator cbegin() const { return edge_table_.cbegin(); } const_iterator end() const { return edge_table_.end(); } const_iterator cend() const { return edge_table_.cend(); } }; } #endif //PLAIN_DA_TRIES__KEYSET_HPP_ <file_sep>// // Created by 松本拓真 on 2019/11/06. // #include "gtest/gtest.h" #include "bo/bextr.hpp" namespace { constexpr int N = 1<<16; uint64_t rand64() { return uint64_t(random()) | (uint64_t(random()) << 32); } } TEST(Bextr, 64) { for (int i = 0; i < N; i++) { auto val = rand64(); int s = random() % 64; int l = random() % (64 - s) + 1; uint64_t bar = (l < 64) ? (1ull<<l)-1 : -1; uint64_t mask = bar << s; EXPECT_EQ(bo::bextr_u64(val, s, l), (val & mask) >> s); } } <file_sep>#ifndef PLAIN_DA_TRIES__PLAIN_DA_HPP_ #define PLAIN_DA_TRIES__PLAIN_DA_HPP_ #include <cstdint> #include <string> #include <cstring> #include <vector> #include <deque> #include <unordered_map> #include <limits> #include <cassert> #include <iostream> #include <bitset> #include <chrono> #include <iterator> #include <numeric> #include <algorithm> #include <stdexcept> #include "double_array_base.hpp" #include "tail.hpp" #include "keyset.hpp" namespace plain_da { template <typename DaType, bool EdgeOrdering> class PlainDaTrie { public: using da_type = DaType; private: da_type bc_; public: PlainDaTrie() = default; explicit PlainDaTrie(const KeysetHandler& keyset) { Build(keyset); } void Build(const KeysetHandler& keyset); explicit PlainDaTrie(const RawTrie& trie) { Build(trie); } void Build(const RawTrie& trie); size_t size() const { return bc_.size(); } bool contains(const std::string& key) const { return _contains(key); } bool contains(std::string_view key) const { return _contains(key); } private: template <typename Key> bool _contains(Key key) const { index_type idx = 0; for (uint8_t c : key) { auto nxt = bc_.Operate(bc_[idx].base, c); if (nxt >= bc_.size() or bc_[nxt].check != idx) { return false; } idx = nxt; } auto nxt = bc_.Operate(bc_[idx].base, kLeafChar); return !(nxt >= bc_.size() or bc_[nxt].check != idx); } }; template <typename DaType, bool EdgeOrdering> void PlainDaTrie<DaType, EdgeOrdering>::Build(const KeysetHandler& keyset) { // A keys in keyset is required to be sorted and unique. using key_iterator = typename KeysetHandler::const_iterator; if constexpr (!EdgeOrdering) { size_t cnt_skip = 0; uint64_t time_fb = 0; auto dfs = [&]( const auto dfs, const key_iterator begin, const key_iterator end, int depth, index_type da_index ) -> void { std::deque<uint8_t> children; assert(begin < end); auto keyit = begin; if (keyit->size() == depth) { children.push_back(kLeafChar); ++keyit; } std::vector<key_iterator> its; uint8_t pibot_char = kLeafChar; while (keyit < end) { uint8_t c = (*keyit)[depth]; if (pibot_char < c) { children.push_back(c); its.push_back(keyit); pibot_char = c; } ++keyit; } its.push_back(end); assert(!children.empty()); auto start_t = std::chrono::high_resolution_clock::now(); auto base = bc_.FindBase(children, &cnt_skip); auto end_t = std::chrono::high_resolution_clock::now(); time_fb += std::chrono::duration_cast<std::chrono::microseconds>(end_t-start_t).count(); bc_[da_index].base = base; CheckExpand(Operate(base, children.back())); for (uint8_t c : children) { auto pos = Operate(base, c); assert(!bc_[pos].Enabled()); if (bc_[pos].Enabled()) { throw std::logic_error("FindBase is not implemented correctly!"); } SetEnabled(pos); bc_[pos].check = da_index; } if (children.front() == kLeafChar) children.pop_front(); for (int i = 0; i < children.size(); i++) { dfs(dfs, its[i], its[i+1], depth+1, Operate(bc_[da_index].base, children[i])); } }; const index_type root_index = 0; bc_.CheckExpand(root_index); bc_.SetEnabled(root_index); bc_[root_index].check = std::numeric_limits<index_type>::max(); dfs(dfs, keyset.cbegin(), keyset.cend(), 0, root_index); std::cout << "\tCount roops: " << cnt_skip << std::endl; std::cout << "\tFindBase time: " << std::fixed << (double)time_fb/1000000 << " ￿s" << std::endl; } else { Build(RawTrie(keyset)); } } template <typename DaType, bool EdgeOrdering> void PlainDaTrie<DaType, EdgeOrdering>::Build(const RawTrie& trie) { // A keys in keyset is required to be sorted and unique. size_t cnt_skip = 0; uint64_t time_fb = 0; auto da_save_edges = [&](std::vector<uint8_t>& children, index_type da_index) { assert(!children.empty()); auto start_t = std::chrono::high_resolution_clock::now(); auto base = bc_.FindBase(children, &cnt_skip); auto end_t = std::chrono::high_resolution_clock::now(); time_fb += std::chrono::duration_cast<std::chrono::microseconds>(end_t-start_t).count(); bc_[da_index].base = base; bc_.CheckExpand(bc_.Operate(base, children.back())); for (uint8_t c : children) { auto pos = bc_.Operate(base, c); assert(!bc_[pos].Enabled()); if (bc_[pos].Enabled()) { throw std::logic_error("FindBase is not implemented correctly!"); } bc_.SetEnabled(pos); bc_[pos].check = da_index; } }; if constexpr (!EdgeOrdering) { auto dfs = [&]( const auto dfs, size_t trie_node, size_t da_index ) -> void { auto& edges = trie[trie_node]; std::vector<uint8_t> children; children.reserve(edges.size()); for (auto e : edges) { children.push_back(e.c); } da_save_edges(children, da_index); for (auto e : edges) { if (e.next == -1) continue; dfs(dfs, e.next, bc_.Operate(bc_[da_index].base, e.c)); } }; const index_type root_index = 0; bc_.CheckExpand(root_index); bc_.SetEnabled(root_index); bc_[root_index].check = std::numeric_limits<index_type>::max(); dfs(dfs, 0, root_index); } else { std::vector<int> size(trie.size()); auto set_trie_size = [&](const auto dfs, int s) -> int { int sz = 1; for (auto [c, t] : trie[s]) { if (t == -1) sz++; else sz += dfs(dfs, t); } size[s] = sz; return sz; }; set_trie_size(set_trie_size, 0); auto dfs = [&]( const auto dfs, int trie_node, index_type da_index ) -> void { auto& edges = trie[trie_node]; std::vector<uint8_t> children; children.reserve(edges.size()); for (auto e : edges) children.push_back(e.c); da_save_edges(children, da_index); std::deque<int> order(edges.size()); std::iota(order.begin(), order.end(), 0); if (children[0] == kLeafChar) order.pop_front(); std::sort(order.begin(), order.end(), [&](int l, int r) { return size[edges[l].next] > size[edges[r].next]; }); for (auto i : order) { assert(edges[i].next != -1); dfs(dfs, trie[trie_node][i].next, bc_.Operate(bc_[da_index].base, children[i])); } }; const index_type root_index = 0; bc_.CheckExpand(root_index); bc_.SetEnabled(root_index); bc_[root_index].check = std::numeric_limits<index_type>::max(); dfs(dfs, 0, root_index); } std::cout << "\tCount roops: " << cnt_skip << std::endl; std::cout << "\tFindBase time: " << std::fixed << (double)time_fb/1000000 << " ￿s" << std::endl; } template <typename DaType, bool EdgeOrdering> class PlainDaMpTrie { public: using da_type = DaType; private: da_type bc_; Tail tail_; public: PlainDaMpTrie() = default; explicit PlainDaMpTrie(const KeysetHandler& keyset) { Build(keyset); } void Build(const KeysetHandler& keyset); explicit PlainDaMpTrie(const RawTrie& trie) { Build(trie); } void Build(const RawTrie& trie); size_t size() const { return bc_.size(); } bool contains(const std::string& key) const { return _contains(key); } bool contains(std::string_view key) const { return _contains(key); } private: template <typename Key> bool _contains(Key key) const { index_type idx = 0; auto it = key.begin(); for (; it != key.end(); ++it) { if (!bc_[idx].HasBase()) break; auto nxt = bc_.Operate(bc_[idx].base(), *it); if (nxt >= bc_.size() or bc_[nxt].check() != idx) { return false; } idx = nxt; } if (bc_[idx].HasBase()) { // Check leaf transition if (it != key.end()) return false; auto nxt = bc_.Operate(bc_[idx].base(), kLeafChar); return nxt < bc_.size() and bc_[nxt].check() == idx; } else { // Compare on a TAIL size_t tail_i = bc_[idx].tail_i(); for (; it != key.end(); ++it, ++tail_i) { if (tail_i < tail_.size() and *it != tail_[tail_i]) return false; } return tail_i < tail_.size() and tail_[tail_i] == (char) kLeafChar; } } }; template <typename DaType, bool EdgeOrdering> void PlainDaMpTrie<DaType, EdgeOrdering>::Build(const KeysetHandler& keyset) { // A keys in keyset is required to be sorted and distinct for each keys. using key_iterator = typename KeysetHandler::const_iterator; if constexpr (!EdgeOrdering) { TailConstructor tail_constr; size_t cnt_skip = 0; uint64_t time_fb = 0; auto dfs = [&]( const auto dfs, const key_iterator begin, const key_iterator end, int depth, index_type da_index ) -> void { assert(begin < end); if (std::next(begin) == end) { // Store on TAIL auto idx = tail_constr.push(std::string(begin->substr(depth))); bc_[da_index].set_tail_i(idx); return; } std::deque<uint8_t> children; auto keyit = begin; if (keyit->size() == depth) { children.push_back(kLeafChar); ++keyit; } std::vector<key_iterator> its; uint8_t pibot_char = kLeafChar; while (keyit < end) { uint8_t c = (*keyit)[depth]; if (pibot_char < c) { children.push_back(c); its.push_back(keyit); pibot_char = c; } ++keyit; } its.push_back(end); assert(!children.empty()); auto start_t = std::chrono::high_resolution_clock::now(); auto base = bc_.FindBase(children, &cnt_skip); auto end_t = std::chrono::high_resolution_clock::now(); time_fb += std::chrono::duration_cast<std::chrono::microseconds>(end_t-start_t).count(); bc_[da_index].base = base; CheckExpand(Operate(base, children.back())); for (uint8_t c : children) { auto pos = Operate(base, c); assert(!bc_[pos].Enabled()); if (bc_[pos].Enabled()) { throw std::logic_error("FindBase is not implemented correctly!"); } SetEnabled(pos); bc_[pos].check = da_index; } if (children.front() == kLeafChar) children.pop_front(); for (int i = 0; i < children.size(); i++) { dfs(dfs, its[i], its[i+1], depth+1, Operate(bc_[da_index].base, children[i])); } }; const index_type root_index = 0; bc_.CheckExpand(root_index); bc_.SetEnabled(root_index); bc_[root_index].check = std::numeric_limits<index_type>::max(); dfs(dfs, keyset.cbegin(), keyset.cend(), 0, root_index); tail_constr.Construct(); for (size_t i = 0; i < bc_.size(); i++) { if (!bc_[i].Enabled() or bc_[i].HasBase()) continue; bc_[i].set_tail_i(tail_constr.map_to(bc_[i].tail_i())); } tail_ = Tail(std::move(tail_constr)); std::cout << "\tCount roops: " << cnt_skip << std::endl; std::cout << "\tFindBase time: " << std::fixed << (double)time_fb/1000000 << " ￿s" << std::endl; } else { Build(RawTrie(keyset)); } } template <typename DaType, bool EdgeOrdering> void PlainDaMpTrie<DaType, EdgeOrdering>::Build(const RawTrie& trie) { // A keys in keyset is required to be sorted and unique. size_t cnt_skip = 0; uint64_t time_fb = 0; std::vector<bool> to_leaf(trie.size()); auto set_to_leaf = [&](auto f, size_t trie_node) { if (trie_node == -1) return; auto& edges = trie[trie_node]; for (auto &e : edges) { f(f, e.next); } if (edges.size() == 1) { if (edges[0].c == kLeafChar) { to_leaf[trie_node] = true; } else { to_leaf[trie_node] = to_leaf[edges[0].next]; } } }; set_to_leaf(set_to_leaf, 0); auto get_suffix_rev = [f = [&trie](auto f, int trie_node, std::string& suf) -> void { auto& edges = trie[trie_node]; assert(edges.size() == 1); if (edges[0].c != kLeafChar) { suf += edges[0].c; f(f, edges[0].next, suf); } }](int trie_node) { std::string suf = ""; f(f, trie_node, suf); return suf; }; TailConstructor tail_constr; auto da_save_edges = [&](const std::vector<uint8_t>& children, index_type da_index) { assert(!children.empty()); auto start_t = std::chrono::high_resolution_clock::now(); auto base = bc_.FindBase(children, &cnt_skip); auto end_t = std::chrono::high_resolution_clock::now(); time_fb += std::chrono::duration_cast<std::chrono::microseconds>(end_t-start_t).count(); bc_[da_index].set_base(base); bc_.CheckExpand(bc_.Operate(base, children.back())); for (uint8_t c : children) { auto pos = bc_.Operate(base, c); assert(!bc_[pos].Enabled()); if (bc_[pos].Enabled()) { throw std::logic_error("FindBase is not implemented correctly!"); } bc_.SetEnabled(pos); bc_[pos].set_check(da_index); } }; std::vector<int> subtree_size; if constexpr (EdgeOrdering) { subtree_size.resize(trie.size()); auto set_trie_size = [&](const auto dfs, int s) -> void { int& sz = subtree_size[s] = 1; for (auto [c, t] : trie[s]) { if (t == -1) sz++; else { dfs(dfs, t); sz += subtree_size[t]; } } }; set_trie_size(set_trie_size, 0); } auto dfs = [&]( const auto dfs, int trie_node, index_type da_index ) -> void { if (to_leaf[trie_node]) { // Store on the TAIL auto suffix = get_suffix_rev(trie_node); auto idx = tail_constr.push(suffix); bc_[da_index].set_tail_i(idx); return; } auto& edges = trie[trie_node]; std::vector<uint8_t> children; children.reserve(edges.size()); for (auto e : edges) children.push_back(e.c); da_save_edges(children, da_index); std::deque<int> order(edges.size()); std::iota(order.begin(), order.end(), 0); if (children[0] == kLeafChar) // (edges[0].next == -1) order.pop_front(); if constexpr (EdgeOrdering) { std::sort(order.begin(), order.end(), [&](int l, int r) { return subtree_size[edges[l].next] > subtree_size[edges[r].next]; }); } for (auto i : order) { assert(edges[i].next != -1); dfs(dfs, trie[trie_node][i].next, bc_.Operate(bc_[da_index].base(), children[i])); } }; const index_type root_index = 0; bc_.CheckExpand(root_index); bc_.SetEnabled(root_index); bc_[root_index].set_check(std::numeric_limits<index_type>::max()); dfs(dfs, 0, root_index); tail_constr.Construct(); for (size_t i = 0; i < bc_.size(); i++) { if (!bc_[i].Enabled() or bc_[i].HasBase()) continue; auto c = bc_.RestoreLabel(bc_[bc_[i].check()].base(), i); if (c == kLeafChar) continue; auto tail_i = tail_constr.map_to(bc_[i].tail_i()); assert(tail_i > 0); bc_[i].set_tail_i(tail_i); } tail_ = Tail(std::move(tail_constr)); std::cout << "\tCount roops: " << cnt_skip << std::endl; std::cout << "\tFindBase time: " << std::fixed << (double)time_fb/1000000 << " ￿s" << std::endl; } } #endif //PLAIN_DA_TRIES__PLAIN_DA_HPP_ <file_sep>#ifndef PLAIN_DA_TRIES__DOUBLE_ARRAY_BASE_HPP_ #define PLAIN_DA_TRIES__DOUBLE_ARRAY_BASE_HPP_ #include <cstdint> #include <vector> #include <array> #include <type_traits> #include <bo.hpp> #include "definition.hpp" #include "bit_vector.hpp" #include "convolution.hpp" namespace plain_da { using index_type = int32_t; constexpr index_type kInvalidIndex = -1; struct da_plus_operation_tag {}; struct da_xor_operation_tag {}; template<typename OperationTag> struct DaOperation {}; template<> struct DaOperation<da_plus_operation_tag> { index_type operator()(index_type base, uint8_t c) const { return base + c; } index_type inv(index_type index, uint8_t c) const { return index - c; } uint8_t label(index_type from, index_type to) const { return to - from; } }; template<> struct DaOperation<da_xor_operation_tag> { index_type operator()(index_type base, uint8_t c) const { return base ^ c; } index_type inv(index_type index, uint8_t c) const { return index ^ c; } uint8_t label(index_type from, index_type to) const { return to ^ from; } }; struct ELM_xcheck_tag {}; struct WW_xcheck_tag {}; struct WW_ELM_xcheck_tag : WW_xcheck_tag, ELM_xcheck_tag {}; struct CNV_xcheck_tag {}; struct CNV_ELM_xcheck_tag : CNV_xcheck_tag, ELM_xcheck_tag {}; template <typename OperationTag, typename ConstructionType> class DoubleArrayBase { public: using op_type = DaOperation<OperationTag>; static constexpr bool kEnableBitVector = std::is_base_of_v<WW_xcheck_tag, ConstructionType>; class DaUnit { private: index_type check_ = kInvalidIndex; index_type base_ = kInvalidIndex; public: index_type check() const { return check_; } void set_check(index_type nv) { check_ = nv; } index_type base() const { return base_ - kAlphabetSize; } void set_base(index_type nv) { base_ = nv + kAlphabetSize; } index_type succ() const { return -check_-1; } void set_succ(index_type nv) { check_ = -(nv+1); } index_type pred() const { return -base_-1; } void set_pred(index_type nv) { base_ = -(nv+1); } bool Enabled() const { return check_ >= 0; } bool HasBase() const { return base_ >= 0; } index_type tail_i() const { return -base_; } void set_tail_i(index_type idx) { base_ = -idx; } }; private: op_type operation_; std::vector<DaUnit> bc_; BitVector exists_bits_; index_type empty_head_ = kInvalidIndex; public: size_t size() const { return bc_.size(); } index_type Operate(index_type base, uint8_t c) const { return operation_(base, c); } uint8_t RestoreLabel(index_type from, index_type to) const { return operation_.label(from, to); } const DaUnit& operator[](size_t i) const { return bc_[i]; } DaUnit& operator[](size_t i) { return bc_[i]; } void SetDisabled(index_type pos); void SetEnabled(index_type pos); void CheckExpand(index_type pos); template <typename Container> index_type FindBase(const Container& children, size_t* counter) const; template <typename Container> index_type FindBaseELM(const Container& children, size_t* counter) const; template <typename Container> index_type FindBaseWW(const Container& children, size_t* counter) const; template <typename Container> index_type FindBaseCNV(const Container& children, size_t* counter) const; }; template <typename OperationTag, typename ConstructionType> void DoubleArrayBase<OperationTag, ConstructionType>::SetDisabled(index_type pos) { if (empty_head_ == kInvalidIndex) { empty_head_ = pos; bc_[pos].set_succ(pos); bc_[pos].set_pred(pos); } else { auto back_pos = bc_[empty_head_].pred(); bc_[back_pos].set_succ(pos); bc_[empty_head_].set_pred(pos); bc_[pos].set_succ(empty_head_); bc_[pos].set_pred(back_pos); } if constexpr (kEnableBitVector) { exists_bits_[pos] = false; } } template <typename OperationTag, typename ConstructionType> void DoubleArrayBase<OperationTag, ConstructionType>::SetEnabled(index_type pos) { assert(!bc_[pos].Enabled()); auto succ_pos = bc_[pos].succ(); if (pos == empty_head_) { empty_head_ = (succ_pos != pos) ? succ_pos : kInvalidIndex; } auto pred_pos = bc_[pos].pred(); bc_[pos].set_check(kInvalidIndex); bc_[pos].set_base(kInvalidIndex); bc_[pred_pos].set_succ(succ_pos); bc_[succ_pos].set_pred(pred_pos); if constexpr (kEnableBitVector) { exists_bits_[pos] = true; } } template <typename OperationTag, typename ConstructionType> void DoubleArrayBase<OperationTag, ConstructionType>::CheckExpand(index_type pos) { auto old_size = size(); auto new_size = ((pos/256)+1)*256; if (new_size <= old_size) return; bc_.resize(new_size); if constexpr (kEnableBitVector) { exists_bits_.resize(new_size); } for (auto i = old_size; i < new_size; i++) { SetDisabled(i); } } template <typename OperationTag, typename ConstructionType> template <typename Container> index_type DoubleArrayBase<OperationTag, ConstructionType>::FindBase(const Container& children, size_t* counter) const { assert(!children.empty()); if (empty_head_ == kInvalidIndex) return std::max(0, operation_.inv(size(), children[0])); if constexpr (std::is_same_v<ConstructionType, ELM_xcheck_tag>) { return FindBaseELM(children, counter); } else if constexpr (std::is_base_of_v<WW_xcheck_tag, ConstructionType>) { return FindBaseWW(children, counter); } else if constexpr (std::is_base_of_v<CNV_xcheck_tag, ConstructionType>) { return FindBaseCNV(children, counter); } throw std::bad_function_call(); } template <typename OperationTag, typename ConstructionType> template <typename Container> index_type DoubleArrayBase<OperationTag, ConstructionType>::FindBaseELM(const Container& children, size_t* counter) const { uint8_t fstc = children[0]; auto base_front = operation_.inv(empty_head_, fstc); auto base = base_front; while (operation_(base, fstc) < size()) { bool ok = base >= 0; assert(!bc_[operation_(base, fstc)].Enabled()); for (int i = 1; ok and i < children.size(); i++) { uint8_t c = children[i]; ok &= operation_(base, c) >= size() or !bc_[operation_(base, c)].Enabled(); } if (ok) { return base; } base = operation_.inv(bc_[operation_(base, fstc)].succ(), fstc); if (base == base_front) break; if (counter) (*counter)++; } return std::max(0, operation_.inv(size(), fstc)); } template <typename OperationTag, typename ConstructionType> template <typename Container> index_type DoubleArrayBase<OperationTag, ConstructionType>::FindBaseWW(const Container& children, size_t* counter) const { if constexpr (std::is_same_v<OperationTag, da_plus_operation_tag>) { uint8_t fstc = children[0]; index_type offset = empty_head_ - fstc; for (; offset+fstc < size(); ) { uint64_t bits = 0ull; for (uint8_t c : children) { bits |= exists_bits_.bits64(offset + c); if (~bits == 0ull) break; } bits = ~bits; if (bits != 0ull) { return offset + (index_type) bo::ctz_u64(bits); } if constexpr (std::is_same_v<ConstructionType, WW_xcheck_tag>) { offset += 64; } else if constexpr (std::is_same_v<ConstructionType, WW_ELM_xcheck_tag>) { auto window_front = offset + fstc; uint64_t word_with_fstc = ~exists_bits_.bits64(window_front); assert(word_with_fstc != 0ull); auto window_empty_tail = window_front + 63 - bo::clz_u64(word_with_fstc); if (window_empty_tail >= size()) break; assert(!bc_[window_empty_tail].Enabled()); auto next_empty_pos = bc_[window_empty_tail].succ(); if (next_empty_pos == empty_head_) break; assert(next_empty_pos - window_front >= 64); // This is advantage over WW_xcheck_tag offset = next_empty_pos - fstc; } if (counter) (*counter)++; } return std::max(0, (index_type) size() - fstc); } else if constexpr (std::is_same_v<OperationTag, da_xor_operation_tag>) { size_t b = empty_head_/256; size_t bend = size()/256; for (; b < bend; ++b) { std::array<uint64_t, 4> bits{}; for (uint8_t c : children) { static uint64_t exists_word[4]; std::memcpy(exists_word, exists_bits_.data()+(b*4), sizeof(uint64_t)*4); if (c & (1<<0)) for (int i = 0; i < 4; i++) exists_word[i] |= ((exists_word[i] >> 1) & 0x5555555555555555ull) | ((exists_word[i] & 0x5555555555555555ull) << 1); if (c & (1<<1)) for (int i = 0; i < 4; i++) exists_word[i] |= ((exists_word[i] >> 2) & 0x3333333333333333ull) | ((exists_word[i] & 0x3333333333333333ull) << 2); if (c & (1<<2)) for (int i = 0; i < 4; i++) exists_word[i] |= ((exists_word[i] >> 4) & 0x0F0F0F0F0F0F0F0Full) | ((exists_word[i] & 0x0F0F0F0F0F0F0F0Full) << 4); if (c & (1<<3)) for (int i = 0; i < 4; i++) exists_word[i] |= ((exists_word[i] >> 8) & 0x00FF00FF00FF00FFull) | ((exists_word[i] & 0x00FF00FF00FF00FFull) << 8); if (c & (1<<4)) for (int i = 0; i < 4; i++) exists_word[i] |= ((exists_word[i] >> 16) & 0x0000FFFF0000FFFFull) | ((exists_word[i] & 0x0000FFFF0000FFFFull) << 16); if (c & (1<<5)) for (int i = 0; i < 4; i++) exists_word[i] |= (exists_word[i] >> 32) | (exists_word[i] << 32); if (c & (1<<6)) { std::swap(exists_word[0], exists_word[1]); std::swap(exists_word[2], exists_word[3]); } if (c & (1<<7)) { std::swap(exists_word[0], exists_word[2]); std::swap(exists_word[1], exists_word[3]); } for (int i = 0; i < 4; i++) bits[i] |= exists_word[i]; } for (int i = 0; i < 4; i++) { if (~bits[i] != 0ull) { auto inset = bo::ctz_u64(~bits[i]); return b*256 + i*64 + inset; } } if (counter) (*counter)++; } return size(); } } template <typename OperationTag, typename ConstructionType> template <typename Container> index_type DoubleArrayBase<OperationTag, ConstructionType>::FindBaseCNV(const Container& children, size_t* counter) const { if (std::is_same_v<OperationTag, da_plus_operation_tag>) { static convolution::ModuloNTT fda[kAlphabetSize*2], fch[kAlphabetSize*2]; index_type fstc = children[0]; index_type endc = children.back(); const index_type m = endc - fstc + 1; const index_type b = 1<<(64-bo::clz_u64(m-1)); const index_type n = b<<1; { std::fill(fch, fch + n, 0); for (uint8_t c : children) fch[m-1-(c-fstc)] = 1; } convolution::ntt(fch, n); index_type endi = 0; for (index_type f = empty_head_; f < size(); ) { for (int i = 0; i < n; i++) { fda[i] = f + i < size() ? (int) operator[](f + i).Enabled() : 0; if constexpr (std::is_base_of_v<ELM_xcheck_tag, ConstructionType>) { if (i <= n-m and fda[i] == 0) { endi = f + i; } } } convolution::index_sum_convolution_for_xcheck(fda, fch, n); for (int i = m-1; i < n; i++) { if (fda[i].val() == 0) { return f - fstc + i - (m-1); } } if constexpr (!std::is_base_of_v<ELM_xcheck_tag, ConstructionType>) { f += n - m + 1; } else { if (endi >= size() or (f = operator[](endi).succ()) == empty_head_) { break; } } if (counter) counter++; } return size(); } else if (std::is_same_v<OperationTag, da_xor_operation_tag>) { static index_type hda[kAlphabetSize], hch[kAlphabetSize]; constexpr size_t n = kAlphabetSize; memset(hch, 0, sizeof(index_type) * n); for (uint8_t c : children) hch[c] = 1; convolution::fwt(hch, n); for (size_t f = empty_head_ / n * n; f < size(); f += n) { for (int i = 0; i < n; i++) { hda[i] = f + i < size() ? (int) operator[](f + i).Enabled() : 0; } convolution::index_xor_convolution_for_xcheck(hda, hch, n); for (int i = 0; i < n; i++) { if (hda[i] == 0) { return (index_type) f + i; } } if (counter) counter++; } return size(); } } } #endif //PLAIN_DA_TRIES__DOUBLE_ARRAY_BASE_HPP_ <file_sep>#ifndef PLAIN_DA_TRIES__CONVOLUTION_HPP_ #define PLAIN_DA_TRIES__CONVOLUTION_HPP_ #include <cstdint> #include <vector> #include <stdexcept> #include <bo.hpp> namespace plain_da::convolution { // Index SUM(+) convolution using uint = uint32_t; template<uint MOD> class Modulo { private: uint v_; public: constexpr Modulo() : v_(0) {} template<typename T> constexpr Modulo(T v) : v_(v >= 0 ? v % (T) MOD : v % (T) MOD + (T) MOD) {} constexpr uint val() const { return v_; } constexpr bool operator==(Modulo x) const { return v_ == x.v_; } constexpr bool operator!=(Modulo x) const { return v_ != x.v_; } Modulo operator+() const { return *this; } Modulo operator-() const { return {MOD - v_}; } constexpr Modulo operator+(Modulo x) const { return {v_ + x.v_}; } constexpr Modulo operator-(Modulo x) const { return *this + -x; } constexpr Modulo operator*(Modulo x) const { return {(unsigned long long) v_ * x.v_}; } friend constexpr Modulo pow(Modulo x, uint p) { Modulo t = 1; Modulo u = x; while (p > 0) { if (p & 1) { t *= u; } u *= u; p >>= 1; } return t; } constexpr Modulo inv() const { return pow(*this, MOD-2); } constexpr Modulo operator/(Modulo x) const { return *this * x.inv(); } constexpr Modulo& operator+=(Modulo x) { return *this = *this + x; } constexpr Modulo& operator-=(Modulo x) { return *this = *this - x; } constexpr Modulo& operator*=(Modulo x) { return *this = *this * x; } constexpr Modulo& operator/=(Modulo x) { return *this = *this / x; } }; template<typename T> void bit_reverse(T f[], size_t n) { for (size_t i = 0, j = 1; j < n-1; j++) { for (size_t k = n >> 1; k > (i ^= k); k >>= 1) {} if (i < j) std::swap(f[i], f[j]); } } constexpr uint kModNTT = 998244353; constexpr int kDivLim = 23; using ModuloNTT = Modulo<kModNTT>; constexpr ModuloNTT kPrimitiveRoot = 3; // Number Theoretic Transform template<bool INV> void _ntt(ModuloNTT f[], size_t n) { if (n == 1) return; if (n > 1<<23) { throw std::logic_error("Length of input array of NTT is too long."); } static bool initialized = false; static ModuloNTT es[kDivLim+1], ies[kDivLim+1]; if (!initialized) { initialized = true; es[kDivLim] = pow(kPrimitiveRoot, (kModNTT-1)>>kDivLim); for (int i = kDivLim-1; i >= 0; i--) { es[i] = es[i+1] * es[i+1]; } ies[kDivLim] = es[kDivLim].inv(); for (int i = kDivLim-1; i >= 0; i--) { ies[i] = ies[i+1] * ies[i+1]; } } bit_reverse(f, n); for (int s = 1; 1 << s <= n; s++) { const size_t m = 1 << s; const auto wm = !INV ? es[s] : ies[s]; for (size_t k = 0; k < n; k += m) { ModuloNTT w = 1; for (size_t j = 0; j < m/2; j++) { auto a = f[k + j]; auto b = f[k + j + m/2] * w; f[k + j] = a + b; f[k + j + m/2] = a - b; w *= wm; } } } if constexpr (INV) { auto invn = ModuloNTT(n).inv(); for (size_t i = 0; i < n; i++) f[i] *= invn; } } void ntt(ModuloNTT f[], size_t n) { _ntt<0>(f, n); } void intt(ModuloNTT f[], size_t n) { _ntt<1>(f, n); } void index_sum_convolution_for_xcheck(ModuloNTT f[], ModuloNTT Tg[], size_t n) { assert(bo::popcnt_u64(n) == 1); ntt(f, n); for (size_t i = 0; i < n; i++) { f[i] *= Tg[i]; } intt(f, n); } // Index XOR(^) convolution // Fast Walsh-Hadamard Transform for XOR-Convolution template<typename T> void fwt(T f[], size_t n) { assert(bo::popcnt_u64(n) == 1); for (int i = 1; i < n; i <<= 1) { for (int j = 0; j < n; j++) { if ((i & j) != 0) continue; auto x = f[j], y = f[j | i]; f[j] = x + y; f[j | i] = x - y; } } } template<typename T> void ifwt(T f[], size_t n) { assert(bo::popcnt_u64(n) == 1); for (int i = 1; i < n; i <<= 1) { for (int j = 0; j < n; j++) { if ((i & j) != 0) continue; auto x = f[j], y = f[j | i]; f[j] = (x + y) / 2; f[j | i] = (x - y) / 2; } } } template<typename T> void index_xor_convolution_for_xcheck(T f[], T Tg[], size_t n) { fwt(f, n); for (int i = 0; i < n; i++) { f[i] *= Tg[i]; } ifwt(f, n); } } #endif //PLAIN_DA_TRIES__CONVOLUTION_HPP_ <file_sep>#include "plain_da.hpp" #include <iostream> #include <fstream> #include <chrono> #include "keyset.hpp" #include "double_array_base.hpp" namespace { template <class Fn> double ProcessTime(Fn fn) { auto start = std::chrono::high_resolution_clock::now(); fn(); auto now = std::chrono::high_resolution_clock::now(); return std::chrono::duration<double, std::micro>(now-start).count(); } constexpr int BenchKeyCounts = 1000000; constexpr int LoopTimes = 10; template <class Da> void Benchmark(const plain_da::KeysetHandler& keyset, const plain_da::RawTrie& trie, const plain_da::KeysetHandler& bench_keyset) { Da plain_da; auto construction_time = ProcessTime([&] { plain_da.Build(trie); }); std::cout << "construction_time: \t" << construction_time/1000000 << " s" << std::endl; { // Check is construction perfect. std::cout << "Test..." << std::endl; for (auto &key : keyset) { bool ok = plain_da.contains(key); if (!ok) { std::cout << "NG" << std::endl; std::cout << "ERROR! " << key << "\t is not contained!" << std::endl; return; } } std::cout << "OK" << std::endl; } auto bench_for_random_keys = [&] { for (auto &key : bench_keyset) { bool ok = plain_da.contains(key); if (!ok) { std::cout << "ERROR! " << key << "\t is not contained!" << std::endl; return; } } }; { // Warm up bench_for_random_keys(); } auto lookup_time = ProcessTime([&] { for (int i = 0; i < LoopTimes; i++) { bench_for_random_keys(); } }); std::cout << "lookup_time: \t" << lookup_time/BenchKeyCounts/LoopTimes << " µs/key" << std::endl << std::endl; } } int main(int argc, char* argv[]) { if (argc < 2) { std::cout << "Usage: " << argv[0] << " [keyset]" << std::endl; exit(EXIT_FAILURE); } std::ifstream ifs(argv[1]); if (!ifs) { std::cerr << argv[1] << " is not found!" << std::endl; exit(EXIT_FAILURE); } plain_da::KeysetHandler keyset(ifs); plain_da::RawTrie trie(keyset); plain_da::KeysetHandler bench_keyset; for (int i = 0; i < BenchKeyCounts; i++) bench_keyset.insert(keyset[random()%keyset.size()]); bench_keyset.update_list(); // PLUS std::cout << "- MP+ - EmptyLink" << std::endl; Benchmark<plain_da::PlainDaMpTrie< plain_da::DoubleArrayBase< plain_da::da_plus_operation_tag, plain_da::ELM_xcheck_tag >, false >>(keyset, trie, bench_keyset); std::cout << "- MP+ - BitParallelism" << std::endl; Benchmark<plain_da::PlainDaMpTrie< plain_da::DoubleArrayBase< plain_da::da_plus_operation_tag, plain_da::WW_xcheck_tag >, false >>(keyset, trie, bench_keyset); std::cout << "- MP+ - BitParallelism + Empty-Link" << std::endl; Benchmark<plain_da::PlainDaMpTrie< plain_da::DoubleArrayBase< plain_da::da_plus_operation_tag, plain_da::WW_ELM_xcheck_tag >, false >>(keyset, trie, bench_keyset); std::cout << "- MP+ - Convolution" << std::endl; Benchmark<plain_da::PlainDaMpTrie< plain_da::DoubleArrayBase< plain_da::da_plus_operation_tag, plain_da::CNV_xcheck_tag >, false >>(keyset, trie, bench_keyset); std::cout << "- MP+ - Convolution + Empty-Link" << std::endl; Benchmark<plain_da::PlainDaMpTrie< plain_da::DoubleArrayBase< plain_da::da_plus_operation_tag, plain_da::CNV_ELM_xcheck_tag >, false >>(keyset, trie, bench_keyset); // XOR // std::cout << "- MPx - EmptyLink" << std::endl; // Benchmark<plain_da::PlainDaMpTrie< // plain_da::DoubleArrayBase< // plain_da::da_xor_operation_tag, // plain_da::ELM_xcheck_tag // >, // false // >>(keyset, trie, bench_keyset); // std::cout << "- MPx - BitParallelism" << std::endl; // Benchmark<plain_da::PlainDaMpTrie< // plain_da::DoubleArrayBase< // plain_da::da_xor_operation_tag, // plain_da::WW_xcheck_tag // >, // false // >>(keyset, trie, bench_keyset); // std::cout << "- MPx - BitParallelism + Empty-Link" << std::endl; // Benchmark<plain_da::PlainDaMpTrie< // plain_da::DoubleArrayBase< // plain_da::da_xor_operation_tag, // plain_da::WW_ELM_xcheck_tag // >, // false // >>(keyset, trie, bench_keyset); // std::cout << "- MPx - BitParallelism" << std::endl; // Benchmark<plain_da::PlainDaMpTrie< // plain_da::DoubleArrayBase< // plain_da::da_xor_operation_tag, // plain_da::WW_xcheck_tag // >, // false // >>(keyset, trie, bench_keyset); // std::cout << "- MPx - BitParallelism - Empty-Link" << std::endl; // Benchmark<plain_da::PlainDaMpTrie< // plain_da::DoubleArrayBase< // plain_da::da_xor_operation_tag, // plain_da::WW_ELM_xcheck_tag // >, // false // >>(keyset, trie, bench_keyset); // std::cout << "- MPx - Convolution" << std::endl; // Benchmark<plain_da::PlainDaMpTrie< // plain_da::DoubleArrayBase< // plain_da::da_xor_operation_tag, // plain_da::CNV_xcheck_tag // >, // false // >>(keyset, trie, bench_keyset); // std::cout << "- MPx - Convolution + Empty-Link" << std::endl; // Benchmark<plain_da::PlainDaMpTrie< // plain_da::DoubleArrayBase< // plain_da::da_xor_operation_tag, // plain_da::CNV_ELM_xcheck_tag // >, // false // >>(keyset, trie, bench_keyset); return 0; } <file_sep># Data sets are saved in GoogleCloud Data sets that used researches are placed on GoogleDrive. Please download it to current directory from follows: https://drive.google.com/file/d/1fu5EUJJb9dyepDcUviGDE6WMSLbh2rZd/view?usp=sharing or use script 'download.sh' which commands as follows:: ```bash FILE_ID=1fu5EUJJb9dyepDcUviGDE6WMSLbh2rZd FILE_NAME=basic_data_sets.tar.xz curl -sc /tmp/cookie "https://drive.google.com/uc?export=download&id=${FILE_ID}" > /dev/null CODE="$(awk '/_warning_/ {print $NF}' /tmp/cookie)" curl -Lb /tmp/cookie "https://drive.google.com/uc?export=download&confirm=${CODE}&id=${FILE_ID}" -o ${FILE_NAME} ``` <file_sep>// // Created by 松本拓真 on 2019/11/09. // #include "gtest/gtest.h" #include "bo/ctz.hpp" namespace { constexpr int N = 1<<16; uint64_t rand64() { return uint64_t(random()) | (uint64_t(random()) << 32); } } TEST(Ctz, 64) { for (int i = 0; i < N; i++) { auto val = rand64(); int ctz = 64; for (int j = 0; j < 64; j++) { if (val & (1ull << j)) { ctz = j; break; } } EXPECT_EQ(bo::ctz_u64(val), ctz); } } <file_sep># libbo C++ Header-only Library of Practical Bit Operations ## Supporting bit operations - ctz - count trailing zeros - clz - count leading zeros - popcnt - poplation count - bextr - bits extract - select - select nth bit - swapnext - swap next nth bits to each other ## LISENCE This library is lisenced by The Unlisence. ## Usage You can handle libbo only including header files. Install to your include directory by cmake as forrows: ```bash cmake . cmake --build . ctest cmake --install . ``` We recommend to compile your program with option `-march=native`
38aa36ffcedd3c1196e3a013d72c09738d84db1d
[ "Markdown", "CMake", "C++" ]
18
C++
MatsuTaku/plain-da-tries
95fc23e776bf35d462ec0c9ae21e657afbbe534c
97de836fc84a79c9db25f9978469843434cbd5e5
refs/heads/master
<repo_name>levanmanh/blog<file_sep>/app/controllers/comments_controller.rb class CommentsController < ApplicationController before_action :logged_in_user, only: [:create, :destroy] before_action :correct_user, only: [:destroy] def new @comment = Comment.new(parent_id: params[:parent_id]) @parent = Comment.find(params[:parent_id]) @entry = Entry.find(params[:entry_id]) @user = current_user end def create @comment = current_user.comments.build(comment_params) if @comment.save flash[:success] = 'Comment created!' if @parent.nil? redirect_to request.referer else entry = @parent.entry redirect_to entry end else flash[:danger] = 'Something went wrong!' redirect_to request.referer end end def destroy if @comment.destroy flash[:success] = "Comment deleted" redirect_to request.referrer || root_url end end private def comment_params params.require(:comment).permit :content, :user_id, :entry_id end def handle_exception flash[:danger] = 'No comment exits!' redirect_to request.referer end def correct_user begin @comment = current_user.comments.find(params[:id]) if @comment.nil? handle_exception end rescue Exception => e handle_exception end end end<file_sep>/db/seeds.rb # Users User.create!(name: "Example User", email: "<EMAIL>", password: "<PASSWORD>", password_confirmation: "<PASSWORD>", admin: true) # Following relationships # users = User.all # user = users.first # following = users[2..50] # followers = users[3..40] # following.each { |followed| user.follow(followed) } # followers.each { |follower| follower.follow(user) }
e1ac4c8836047804efa0ea930a0ae27632f4c968
[ "Ruby" ]
2
Ruby
levanmanh/blog
911d2956e98d7206810c72b34e77e8bb6b54a713
3b07b89f86e1a7ef4a0fae4c4defd1ff279ec3cd
refs/heads/master
<file_sep>class JobSystem ; #ifndef JOB_WORKER_H #define JOB_WORKER_H #include <thread> #include "jobPool.h" #include "jobQueue.h" class JobWorker{ public: enum Mode{ Background, Master }; enum class State{ Running, Stopping, }; JobWorker(JobSystem* jsystem, std::size_t maxJobs,Mode mode= Mode::Background); JobWorker(const JobWorker& worker); ~JobWorker(){}; inline Job* create_job(JobFunc job_func){return pool.create_job(job_func);} inline Job* create_job_as_child(JobFunc job_func , Job* parent){ return pool.create_job_as_child(job_func,parent);} void wait(Job* job); void loop(); void run(); void submit_job(Job* job); bool is_running(){return state==State::Running?true:false;} void set_state(State state); inline void join(){worker_thread.join();} private: JobPool pool; std::thread::id thread_id; std::thread worker_thread; State state; std::atomic<Mode> mode; JobSystem* job_system; JobQueue queue; private: Job* get_job(); JobPool* get_job_pool(){return &pool;} }; #endif <file_sep>#include "jobPool.h" static int job_count =0 ; JobPool::JobPool(std::size_t max_jobs): allocated_jobs(0), jobs{max_jobs}{ } Job* JobPool::allocate_job(){ if(!is_full()){ return &jobs[allocated_jobs++]; }else { return nullptr; } } void JobPool::clear(){ allocated_jobs=0; } bool JobPool::is_full() const{ return allocated_jobs == jobs.size(); } Job* JobPool::create_job(JobFunc job_func){ Job* job = allocate_job(); if(job != nullptr) { job->assign_func(job_func); job->set_num(job_count++); } return job; } Job* JobPool::create_job_as_child(JobFunc job_func , Job* parent){ Job* job = allocate_job(); if(job != nullptr) { job->assign_func(job_func); job->assign_parent(parent); parent->inc_unfinshed_jobs(); job->set_num(job_count++); } return job; } <file_sep>#include "job.h" void Job::run(){ function(this,nullptr); finish(); } void Job::finish (){ unfinishedJobs.fetch_sub(1,std::memory_order_relaxed); if(is_finished()){ if(parent!= nullptr){ parent->dec_unfinshed_jobs(); parent->is_finished(); } } } bool Job::is_finished() const{ return unfinishedJobs==0; } void Job::inc_unfinshed_jobs(){ unfinishedJobs.fetch_add(1,std::memory_order_relaxed); } void Job::dec_unfinshed_jobs(){ unfinishedJobs.fetch_sub(1,std::memory_order_relaxed); } Job::Job(JobFunc func , Job* parent): function{func}, parent{parent}, unfinishedJobs(1){ if(parent!=nullptr){ parent->unfinishedJobs++; } } <file_sep># jobSystem a lock-free work stealing job system based on Molecular's great blog [post](https://blog.molecular-matters.com/2015/08/24/job-system-2-0-lock-free-work-stealing-part-1-basics/) Building ------------- ``` mkdir build cd build cmake .. ``` this would build the provided example . <file_sep>#include "jobSystem.h" #include <random> JobSystem::JobSystem(std::size_t worker_threads_count , std::size_t jobs_per_thread) { workers.reserve(worker_threads_count); master_thread_id = std::this_thread::get_id(); std::size_t jobs_per_queue = jobs_per_thread; workers.emplace_back(this,jobs_per_queue,JobWorker::Mode::Master); master_worker = &workers[0]; master_worker->set_state(JobWorker::State::Running); for (std::size_t i=1;i< worker_threads_count;i++) { workers.emplace_back(this,jobs_per_queue,JobWorker::Mode::Background); } for (std::size_t i=1;i< worker_threads_count;i++) { workers[i].run(); } } JobSystem::~JobSystem(){ std::size_t worker_threads_count = workers.size(); for (std::size_t i=1;i< worker_threads_count;i++) { workers[i].set_state(JobWorker::State::Stopping); } for (std::size_t i=1;i< worker_threads_count;i++) { workers[i].join(); } } JobWorker* JobSystem::get_random_worker(){ static std::random_device rd; static std::mt19937 gen=std::mt19937{rd()}; static std::uniform_int_distribution<std::size_t> dist= std::uniform_int_distribution<std::size_t>{0, workers.size()-1}; int index =dist(gen); JobWorker* worker = &workers[index]; if(worker->is_running()) { return worker; } else { return nullptr; } } <file_sep>#include "jobQueue.h" #include <iostream> #include <thread> JobQueue::JobQueue(std::size_t max_jobs): top{0}, bottom{0}{ jobs.resize(max_jobs); } bool JobQueue::push(Job* job){ int _bottom = bottom.load(std::memory_order_relaxed); if(_bottom<jobs.size()){ // std::cout<< "job-pushed at"<<_bottom<<std::endl; jobs[_bottom]=job; bottom.store(_bottom+1,std::memory_order_release); // std::cout << "push "<<bottom <<std::endl; return true; } else return false ; } Job* JobQueue::pop(){ int _bottom = bottom.load(std::memory_order_acquire); // std::cout << "bottom val : " << _bottom <<std::endl; _bottom= std::max<int>(_bottom-1 ,0); bottom.store(_bottom,std::memory_order_relaxed); int _top = top.load(std::memory_order_relaxed); if(_top<= _bottom){ Job* job = jobs[_bottom]; if (!job) return nullptr; if(_top!=_bottom){ // std::cout << "returned2 Job index " << _bottom << std::endl; // std::cout<< "job-popped at "<<_bottom<<std::endl; return job; } else{ int expectedTop = _top; int desiredTop =std::min( _top+1,(int)jobs.size()); if (!top.compare_exchange_strong(expectedTop, desiredTop, std::memory_order_relaxed)){ job=nullptr; } bottom.store(_top+1,std::memory_order_relaxed); // std::cout<< "pop bottom "<<_top+1<<"bottom val"<< _bottom<<std::endl; // std::cout<< "job-popped main worker at "<<_bottom<<std::endl; // std::cout << "returned3 Job index " << _bottom << std::endl; return job; } } else { // std::cout<< "pop bottom store "<< _top <<" "<<_bottom <<" | "<<std::endl; bottom.store(_top , std::memory_order_relaxed); return nullptr; } } Job* JobQueue::steal(){ int _top = top.load(std::memory_order_relaxed); int _bottom = bottom.load(std::memory_order_relaxed); //std::cout << "steal ("<<std::this_thread::get_id()<<") "<< _top << ","<<_bottom <<std::endl; // std::cout << "steal" << _top <<"|"<< _bottom <<"|"<<std::endl; if (_top <_bottom) { // std::cout<< std::this_thread::get_id()<<" tring to steal a job "<<std::endl; // There's technically a data race here if _jobs is not an atomic<jobs*> array. Job* job = jobs[_top]; if (top.compare_exchange_weak(_top, _top + 1, std::memory_order_relaxed) == false) { return nullptr; } // std::cout<< std::this_thread::get_id()<<"job-stolen at "<<_top<<std::endl; // std::cout << "steal afer exchange ("<<std::this_thread::get_id()<<") "<< top << ","<<_bottom<<std::endl;; // if(job)4 // printf("job was stolen %d \n", job->get_job_id()); // std::cout << "job was stolen" << <<"|"<<std::endl; // std::cout << "returned1 Job index " << _top << std::endl; return job; } else { return nullptr; } } std::size_t JobQueue::size() const{ return jobs.size();} <file_sep>#ifndef JOB_H #define JOB_H #include <functional> #include <atomic> struct Job ; using JobFunc = std::function<void(Job*,const void*)>; class Job{ public: Job():unfinishedJobs{1},parent{nullptr}{}; Job(JobFunc job , Job* parent=nullptr); void run(); bool is_finished() const ; void assign_func(JobFunc func){ function=func;} void assign_parent(Job* _parent){parent=_parent; }; void set_num(int id1) {job_id = id1;} inline int get_job_id (){return job_id;} void inc_unfinshed_jobs(); void dec_unfinshed_jobs(); private: JobFunc function ; Job* parent ; int job_id; std::atomic_size_t unfinishedJobs ; char padding[4] ; void finish(); }; #endif <file_sep> #ifndef Job_System_H #define Job_System_H #include <thread> #include "jobWorker.h" class JobSystem{ public: JobSystem(std::size_t threads_count, std::size_t jobs_per_thread); ~JobSystem(); JobWorker* get_random_worker(); JobWorker* master_worker ; private: JobWorker* find_thread_worker(const std::thread::id thread_id); private: std::vector<JobWorker> workers; std::thread::id master_thread_id; }; #endif<file_sep>#ifndef JOB_QUEUE_H #define JOB_QUEUE_H #include<vector> #include "job.h" class JobQueue{ public: JobQueue(std::size_t max_jobs); bool push(Job* job); Job* pop(); Job* steal(); std::size_t size() const ; bool empty() const ; private : std::vector< Job*> jobs ; std::atomic<int> top, bottom ; }; #endif <file_sep> #include "jobWorker.h" #include "jobSystem.h" #include <iostream> JobWorker::JobWorker(JobSystem* jsystem, std::size_t maxJobs,Mode mode): job_system{jsystem}, queue{maxJobs}, pool{maxJobs}, mode{mode}, state{State::Stopping} { } JobWorker::JobWorker(const JobWorker& worker): job_system{worker.job_system}, pool{worker.queue.size()}, queue{worker.queue.size()} { } void JobWorker::run(){ state = State::Running; worker_thread = std::thread(&JobWorker::loop,this); } void JobWorker::submit_job(Job* job){ if(job) queue.push(job); } void JobWorker::loop(){ thread_id = std::this_thread::get_id(); state= State::Running; while(state==JobWorker::State::Running){ Job* job = get_job(); if(job){ job->run(); } } } void JobWorker::wait(Job* wait_job){ while(!wait_job->is_finished()){ Job* job = get_job(); if(job) job->run(); } } void JobWorker::set_state(State _state){ state = _state ; } Job* JobWorker::get_job(){ Job* job = queue.pop(); if(job){ return job; } else{ JobWorker* worker = job_system->get_random_worker(); if(worker!=this && worker){ // std::cout<< "trying to steal a job"<< std::endl; Job* job = worker->queue.steal(); if(job) { // std::cout<< "job steal"<< std::endl; return job; } else{ //no job to steal // std::cout<< "no job to steal"<< std::endl; std::this_thread::yield(); return nullptr; } }else { // std::cout<< "no worker to steal from"<< std::endl; std::this_thread::yield(); return nullptr; } } } <file_sep> #include <iostream> #include <chrono> #include <cmath> #include "jobSystem.h" #define JOB_COUNT 65000 std::atomic_int counter; void empty_job(Job* job, const void*) { int j =0; for (int i=0 ;i< 2000; i++){ j+=1+std::sin(i)*std::cos(i*j); } printf("job %d ,%d executed!\n" , job->get_job_id(),j); } int main (){ JobSystem job_system {8,JOB_COUNT }; JobWorker* worker = job_system.master_worker; #if 0 auto start = std::chrono::steady_clock::now(); for(std::size_t i = 0; i <JOB_COUNT; ++i) { Job* job = worker->create_job(&empty_job); worker->submit_job(job); worker->wait(job); } auto end = std::chrono::steady_clock::now(); std::cout << "Elapsed time in microseconds : " << std::chrono::duration_cast<std::chrono::microseconds>(end - start).count() << " µs" << std::endl; std:: cout << "Elapsed time in milliseconds : " <<std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << " ms" << std::endl; #else auto start1 = std::chrono::steady_clock::now(); Job* parent = worker->create_job(&empty_job); for(std::size_t i = 0; i <JOB_COUNT-1; ++i) { Job* job = worker->create_job_as_child(&empty_job,parent); worker->submit_job(job); } worker->submit_job(parent); worker->wait(parent); auto end1 = std::chrono::steady_clock::now(); std::cout << "Elapsed time in microseconds : " << std::chrono::duration_cast<std::chrono::microseconds>(end1 - start1).count() << " µs" << std::endl; std:: cout << "Elapsed time in milliseconds : " <<std::chrono::duration_cast<std::chrono::milliseconds>(end1 - start1).count() << " ms" << std::endl; #endif return 0; } /*#include <atomic> #include <iostream> #include <thread> #include <vector> std::vector<int> mySharedWork; std::atomic<bool> dataProduced(false); void dataProducer(){ mySharedWork={1,0,3}; dataProduced.store(true, std::memory_order_relaxed); } void dataConsumer(){ while(!dataProduced.load(std::memory_order_relaxed)); mySharedWork[1]= 2; } int main(){ std::cout << std::endl; std::thread t1(dataConsumer); std::thread t2(dataProducer); t1.join(); t2.join(); for (auto v: mySharedWork){ std::cout << v << " "; } std::cout << "\n\n"; }*/ <file_sep>cmake_minimum_required(VERSION 3.5) set (CMAKE_CXX_STANDARD 11) project(jobSystem) file (GLOB_RECURSE sources "src/*.cpp") message("${sources}") set(SOURCE ${sources} ) add_executable(jobSystem ${SOURCE}) target_include_directories(jobSystem PRIVATE ${PROJECT_SOURCE_DIR}/src) <file_sep>#pragma once #include "job.h" #include <vector> class JobPool{ public: JobPool(std::size_t max_jobs_count); Job* allocate_job(); bool is_full() const ; void clear(); Job* create_job(JobFunc job_func); Job* create_job_as_child(JobFunc job_func , Job* parent); template<typename Data> Job* create_job(JobFunc job_func ,const Data& data); template<typename Data> Job* create_job_as_child(JobFunc job_func,const Data& data , Job* parent); template<typename Function> Job* create_closure_Job(Function func); private: std::size_t allocated_jobs ; std::vector<Job> jobs; };<file_sep>#!/bin/sh cmake -DCMAKE_BUILD_TYPE=Release -S . -B ./build make -C ./build ./build/jobSystem
78154d289c6138d7e012f196992dd8a40f64e5e0
[ "Markdown", "CMake", "C++", "Shell" ]
14
C++
alimilhim/jobSystem
5476a8ff282981c2d26023570e22940b98a196b8
2846dd37643c765f6b5fca7b64d5466f48d2a9e0
refs/heads/master
<repo_name>wadelau/gMIS<file_sep>/inc/webapp.interface.php <?php /* WebApp Interface defintion for all of the implement classes * v0.1, * <EMAIL>, * 2011-07-10 15:27 */ interface WebAppInterface { function set($key, $value); function get($key); function setTbl($tbl); function getTbl(); function setId($id); function getId(); function setBy($fields, $conditions); function getBy($fields, $conditions); function execBy($fields, $conditions); function rmBy($conditions); function toString($object); /* function setLang($lang); function getLang(); function checkDB(); */ } ?> <file_sep>/xml/gmis-myote-20190715.sql CREATE TABLE `gmis_mynotetbl` ( `id` int(11) NOT NULL AUTO_INCREMENT, content text not null, notecode char(24) not null default '', `inserttime` datetime NOT NULL default '1001-01-01 00:00:00', `updatetime` datetime NOT NULL default '1001-01-01 00:00:00', `istate` char(10) NOT NULL, `operator` varchar(10) NOT NULL, primary KEY `id` (`id`), index k2(userid), index k3(inserttime) );<file_sep>/act/toexcel.php <?php # do convert hm records to csv used in excel file, Sat Jun 23 13:21:46 CST 2012 # print_r($hm); $dnld_dir = $appdir."/dnld"; $dnld_file = "data_".str_replace("gmis_","",$tbl)."_".date("Y-m-d-H-i").".csv"; $myfp = fopen($dnld_dir.'/'.$dnld_file, 'wb'); fwrite($myfp, chr(0xEF).chr(0xBB).chr(0xBF)); if($myfp){ $fieldsname = array(); $firstrow = $hm[0]; foreach($firstrow as $k=>$v){ $fieldsname[] = $gtbl->getCHN($k); } fputcsv($myfp, $fieldsname); /* foreach($hm as $fields){ fputcsv($myfp, $fields); } */ # retrieve data foreach($hm as $k=>$v){ $str = ""; foreach($v as $k2=>$v2){ #print "k2:$k2, v2:$v2\n"; if($gtbl->getInputType($k2) == "select"){ $v2 = $gtbl->getSelectOption($k2, $v2,'',1, $gtbl->getSelectMultiple($k2)); if(preg_match("/([^\-|\(]+)[\(|\-]*/", $v2, $matchArr)){ $v2 = $matchArr[1]; #debug($matchArr); } } else if(strpos($v2,",") !== false){ #$v2 = str_replace(",", "_", $v2); $v2 = str_replace("\"", "\"\"", $v2); $v2 = '"'.$v2.'"'; # see https://stackoverflow.com/questions/4617935/is-there-a-way-to-include-commas-in-csv-columns-without-breaking-the-formatting } $str .= str_replace("\n", "<br/>", $v2).","; } $str = substr($str, 0, strlen($str)-1); fwrite($myfp, $str."\n"); } } fclose($myfp); $out .= "<script type=\"text/javascript\">"; $out .= "parent.window.open('".$rtvdir."/dnld/".$dnld_file."','Excel File Download','scrollbars,toolbar,location=0,status=yes,resizable,width=600,height=400');"; $out .= "</script>"; ?> <file_sep>/class/xdirectory.class.php <?php if(!defined('__ROOT__')){ define('__ROOT__', dirname(dirname(__FILE__))); } require_once(__ROOT__.'/inc/webapp.class.php'); class XDirectory extends WebApp{ private $dirLevelLength = 2; # default private $maxLevelDepth = 10; # code width: 10 x 2 = 20 public $lang = null; function __construct($tbl = ''){ # db $db = $reqdb = trim($_REQUEST['db']); if($reqdb != ''){ $args = array('dbconf'=>($db==GConf::get('maindb')? '' : $db)); if($args['dbconf'] == 'newsdb'){ $args['dbconf'] = 'Config_Master'; } # other args options parent::__construct($args); } else{ $this->dba = new DBA(); } # tbl if($tbl != ''){ if($_CONFIG['language'] && $_CONFIG['language'] == "en_US"){ //$this->setTbl(GConf::get('tblpre').'en_'.$tbl); $this->setTbl('en_'.$tbl); } else{ //$this->setTbl(GConf::get('tblpre').$tbl); $this->setTbl($tbl); } } # lang if(true){ #debug("mod/pagenavi: lang: not config. try global?"); global $lang; $this->lang = $lang; # via global? } } # get dir list, expand all of directories above the target dir or its same level, "open all to target" function getList($targetDir, $levelLen){ $lastNode = ''; $dirList .="<div class=\"cv_fcv node\">"; $parentCode = $this->get('parentCode'); $selectOnly = Wht::get($_REQUEST, 'selectOnly'); //- added 11:44 2022-03-25 foreach($targetDir as $k=>$v){ $ilevel = 0; $codeArr = str_split($k,$levelLen); foreach($codeArr as $kd=>$vd){ $ilevel++; } $i = $this->getNextDir($targetDir, $levelLen, $ilevel, $k); $j = $this->getSubDir($targetDir, $levelLen, $ilevel, $k); #$nodeContent = $ilevel."-".$k."-".$v; $nodeContent = $k."-".$v; //debug("extra/xdir: k:$k parentCode:$parentCode eq:".strcmp($k, $parentCode)); $hasRed = 0; if(strcmp($k,$parentCode)==0){ $hasRed=1; } else if(strpos($parentCode, $k)===0){ $hasRed=1; } $nodeContent = "<div class=\"tree\" id=\"".$k."\" onmouseover=\"xianShi('".$k."');\" onmouseout=\"yinCang('".$k."');\"".($hasRed==1?' style="color:red;font-weight:strong;"':'').">".$nodeContent; # $nodeContent .= "&nbsp;&nbsp;<span id=\"nodelink".$k."\">"; if($selectOnly != 1){ $nodeContent .= "<a href=\"javascript:void(0);\" onclick=\"javascript:parent.sendLinkInfo('".$k."', 'w', current_link_field); parent.copyAndReturn(current_link_field); changeBgc('".$k."');\">".$this->lang->get("xdir_this_item")."</a>"; } $nodeContent .= "&nbsp;&nbsp;<a href=\"javascript:void(0);\" onclick=\"javascript:parent.sendLinkInfo('".$k."-".$v."', 'w', current_link_field); parent.copyAndReturn(current_link_field); changeBgc('".$k."');\">".$this->lang->get("xdir_this_item_and_value")."</a>"; if($selectOnly != 1){ $nodeContent .= "&nbsp;&nbsp;<a href=\"javascript:void(0);\" onclick=\"javascript:parent.sendLinkInfo('".$i."', 'w', current_link_field); parent.copyAndReturn(current_link_field);\">+".$this->lang->get("xdir_same_level")."</a>"; $nodeContent .= "&nbsp;&nbsp;<a href=\"javascript:void(0);\" onclick=\"javascript:parent.sendLinkInfo('".$j."', 'w', current_link_field); parent.copyAndReturn(current_link_field);\">+".$this->lang->get("xdir_sub_level")."</a>"; } $nodeContent .= "</span></div>"; if($lastNode == ''){ $dirList .= $nodeContent; } else if(strlen($k)==$levelLen){ if(strlen($lastNode)==$levelLen){ $dirList .= $nodeContent; }else{ $n = substr($lastNode,$levelLen); $codeArr = str_split($n,$levelLen); foreach($codeArr as $kd=>$vd){ $dirList .= " </li> </ul>"; } $dirList .= $nodeContent; } } else{ if(strlen($lastNode) == strlen($k)){ $dirList .= $nodeContent; }else if(strlen($lastNode) < strlen($k)){ $dirList .="<ul class=\"node\"> <li>"; $dirList .= $nodeContent; }else{ $n = substr($lastNode,0,strlen($lastNode)-strlen($k)); $codeArr = str_split($n,$levelLen); foreach($codeArr as $kd=>$vd){ $dirList .= " </li> </ul>"; } $dirList .= $nodeContent; } } $lastNode = $k; } $dirList .="</div>"; return $dirList; } # get next dir code, 2c after 2b, 10 after 0z, in base36, i.e. 0-9, a-z function getNextDir($currentDir, $levelLen, $ilevel, $currentVal){ $max = $currentVal; $len = $levelLen * $ilevel; foreach($currentDir as $k=>$v){ if(strlen($k)==$len && substr($k,0,strlen($k)-$levelLen)==substr($max,0,strlen($k)-$levelLen) ){ //条件:同级且在同一个节点下 //$max = $k; $max = $this->maxByBase36($max, $k); } } $lastnumber = substr($max,strlen($max)-$levelLen,strlen($max)); $lastnumber = base_convert($lastnumber,36,10); //36进制转成10进制 $lastnumber++; $lastnumber = base_convert($lastnumber,10,36); //10进制转成36进制 if(strlen($lastnumber)<$levelLen){ //开头做加0处理 $temp = ''; for($i=0; $i<($levelLen-strlen($lastnumber)); $i++){ $temp .='0'; } $lastnumber = $temp.$lastnumber; } return substr($max,0,strlen($max)-$levelLen).$lastnumber; } # get sub dir under currentDir, a1b200 for a1b2 function getSubDir($currentDir, $levelLen, $ilevel, $currentVal){ $nextlen = $levelLen * ($ilevel+1); $currentlen = $levelLen * $ilevel; $exist = false; foreach($currentDir as $k=>$v){ if(strlen($k)==$nextlen && substr($k,0,$currentlen)==$currentVal){ //$max = $k; $max = $this->maxByBase36($max, $k); $exist = true; //当前菜单项存在子级 } } if($exist){ $lastnumber = substr($max,strlen($max)-$levelLen,strlen($max)); $lastnumber = base_convert($lastnumber,36,10); //36进制转成10进制 $lastnumber++; $lastnumber = base_convert($lastnumber,10,36); //10进制转成36进制 if(strlen($lastnumber)<$levelLen){ //开头做加0处理 $temp = ''; for($i=0; $i<($levelLen-strlen($lastnumber)); $i++){ $temp .='0'; } $lastnumber = $temp.$lastnumber; } return substr($max,0,strlen($max)-$levelLen).$lastnumber; } else{ //当前菜单项不存在子级 for($i=0; $i<$levelLen; $i++){ $currentVal .='0'; } return $currentVal; } } //- extract all possible upside dirs from a dir //- Xenxin@ufqi, Wed Apr 24 13:09:17 HKT 2019 function extractDir($dir, $dirLevelLen=null){ $rtnDirList = array($dir); $dirLen = strlen($dir); if($dirLevelLen == null || $dirLevelLen < 1){ $dirLevelLen = $this->dirLevelLength; } for($ilen=$dirLevelLen; $ilen<$dirLen; $ilen+=$dirLevelLen){ $rtnDirList[] = substr($dir, 0, $ilen); } return $rtnDirList; } //- sort same layer by iname //- <EMAIL>, Sat May 22 21:37:49 CST 2021 function sortDir($targetDir, $icode, $iname, $dirLevelLength=2){ $treeList = array(); $codeLen = $dirLevelLength; $theCode = ''; //-sort foreach($targetDir as $k=>$v){ $theCode = $v[$icode]; $codeLen = strlen($theCode); $keyLenArr[$codeLen]["$theCode"] = $v[$iname]; #debug("k:$k $theCode len:$codeLen"); } $keyLenArr2 = array(); foreach($keyLenArr as $k=>$v){ $v = $this->sortByGbk($v); // sort all items within same layer $keyLenArr2[$k] = $v; #debug("k:$k sort:".serialize($keyLenArr2[$k])); } $keyLenArr = $keyLenArr2; //- re-group $keyLenArr2 = array(); $tmpArr = $keyLenArr; $maxDepth = $this->maxLevelDepth + $dirLevelLength; foreach($keyLenArr as $keyLen=>$arr){ foreach($arr as $k2=>$v2){ $keyLenArr2[] = array("$icode"=>$k2, "$iname"=>$v2); #debug("keyLen:$keyLen, k2:$k2 v2:$v2 icode:".$v2[$icode]); $myLevel=$keyLen+$dirLevelLength; $childArr = $this->getChild($keyLenArr, $k2, $myLevel, $icode, $iname); foreach($childArr as $ck=>$cv){ $keyLenArr2[] = $cv; } } } $keyLenArr = $keyLenArr2; return $keyLenArr; } //- iterate all children looply //- travel all dirs with depth first function getChild($keyLenArr, $pcode, $myLevel, $icode, $iname){ $rtnArr = array(); $tmpArr = $keyLenArr[$myLevel]; foreach($tmpArr as $k3=>$v3){ if(startsWith($k3, $pcode)){ #debug("\t\tmyLevel:$myLevel pcode:$pcode k3-icode:$k3 iname:$v3"); $rtnArr[] = array("$icode"=>$k3, "$iname"=>$v3); $tmpLevel = $myLevel + $this->dirLevelLength; if($tmpLevel <= $this->maxLevelDepth){ $rtnArr2 = $this->getChild($keyLenArr, $k3, $tmpLevel, $icode, $iname); foreach($rtnArr2 as $k4=>$v4){ $rtnArr[] = $v4; } } else{ #debug("class/xdirectory: myLevel:$tmpLevel > ".$this->maxLevelDepth); } } } return $rtnArr; } //- sort with gbk? function sortByGbk($arr){ $needGBK = 0; global $_CONFIG; if(strtolower($_CONFIG['character_code_for_sort']) == 'gbk'){ $needGBK = 1; } $tmpArr = array(); if($needGBK == 1){ foreach($arr as $k=>$v){ $tmpArr[$k] = iconv('UTF-8', 'GBK', $v); } } else{ $tmpArr = $arr; } asort($tmpArr, SORT_STRING); // sort by value with string $arr = array(); if($needGBK == 1){ foreach($tmpArr as $k=>$v){ $arr[$k] = iconv('GBK', 'UTF-8', $v); } } else{ $arr = $tmpArr; } return $arr; } //- //- added by <EMAIL>, Tue Jul 27 16:19:50 CST 2021 function maxByBase36($a, $b){ $a = $a=='' ? "0" : $a; $b = $b=='' ? "0" : $b; $a10 = base_convert($a, 36, 10); $b10 = base_convert($b, 36, 10); if($a10 > $b10){ return $a; } else{ return $b; } } } ?><file_sep>/extra/extra_example.php <?php # extra name and function # <EMAIL> on Sun Jan 31 10:22:15 CST 2016 # require("../comm/header.inc.php"); //$gtbl = new GTbl($tbl, array(), $elementsep); include("../comm/tblconf.php"); # main actions $out = 'my output content...'; # or $data['respobj'] = array('output'=>'content'); # module path $module_path = ''; include_once($appdir."/comm/modulepath.inc.php"); # without html header and/or html footer $isoput = false; require("../comm/footer.inc.php"); ?> <file_sep>/act/dodelete.php <?php # do delete for act=list-dodelete, Fri Apr 6 20:46:13 CST 2012 $Max_Allow_Count_Delete = 999; $fieldlist = array(); if(!isset($fieldargv) || !is_array($fieldargv)){ $fieldargv = array(); } if($hasid){ $gtbl->setId($id); $tmpVal = $gtbl->getMyId()."=?"; $fieldargv[] = $tmpVal; } else{ #$fieldargv = ""; for($hmi=$min_idx; $hmi<=$max_idx; $hmi++){ $field = $gtbl->getField($hmi); if($field == null | $field == '' || $field == $gtbl->getMyId()){ continue; } if(array_key_exists($field, $_REQUEST)){ $gtbl->set($field, $_REQUEST[$field]); $fieldargv[] = $field."=?"; } $fieldlist[] = $field; } } $hmorig = $gtbl->getBy("*", implode(" and ", $fieldargv)); if($hmorig[0]){ $hmorig = $hmorig[1][0]; # the first row } include("./act/checkconsistence.php"); //- allow deletion $hm = $gtbl->rmBy(implode(" and ", $fieldargv)); #print_r(__FILE__.": delete:[".$hm."]\n"); $doDeleteResult = true; # some triggers bgn, added on Sat May 26 10:22:14 CST 2012 include("./act/trigger.php"); # some triggers end, added on Sat May 26 10:22:27 CST 2012 //- check linktbl, Tue Jul 6 15:50:34 CST 2021 if(true){ for($hmi=$min_idx; $hmi<=$max_idx;$hmi++){ $field = $gtbl->getField($hmi); $fieldInputType = $gtbl->getInputType($field); $hasDefaultVal = 0; $extraInput = $gtbl->getExtraInput($field, $hmorig); if($field == null || $field == ''){ continue; } else if($extraInput != ''){ if(inString('extra/linktbl.php', $extraInput)){ $paramArr = explode('&', substr($extraInput, strpos($extraInput, '?'))); $linkTbl = ''; $linkField = ''; $tmpArr = array(); foreach($paramArr as $k=>$v){ if(inString('tbl=', $v)){ $tmpArr = explode('=', $v); $linkTbl = $tmpArr[1]; } else if(inString('linkfield=', $v)){ $tmpArr = explode('=', $v); $linkField = $tmpArr[1]; } } if($linkTbl != '' && $linkField != ''){ $linkId = $hmorig['id']; # assume hasId? $tmpSql = "delete from $linkTbl where $linkField=$linkId limit $Max_Allow_Count_Delete"; $hmResult = $gtbl->execBy($tmpSql, null, null); debug("act/dodelete: linktbl: sql:[$tmpSql] result:".serialize($hmResult)); } } #debug("act/dodelete: field:$field input:$fieldInputType extraInput:$extraInput linktbl:$linkTbl linkfield:$linkField params:".serialize($paramArr)." hmorig:".serialize($hmorig)); } } } //- clean $gtbl->setId(''); $_REQUEST[$gtbl->getMyId().'.old'] = $_REQUEST[$gtbl->getMyId()]; $_REQUEST[$gtbl->getMyId()] = ''; # remedy Thu Apr 17 08:41:11 CST 2014 $id = ''; //- resp if($hm[0] && $doDeleteResult){ $out .= "<script> parent.sendNotice(true, '".$lang->get('notice_success')."'); parent.switchArea('contentarea_outer','off'); </script>"; } else{ if(!$doDeleteResult){ $out .= "<script> parent.sendNotice(false, '".$lang->get('notice_success').".".$out."');</script>"; } else{ $out .= "<script> parent.sendNotice(false, '".$lang->get('notice_success')."');</script>"; $deleteErrCode = '201811241202'; } } ?><file_sep>/index.php <?php $_REQUEST['tbl'] = ''; # 'fin_todotbl'; Wed Oct 22 09:10:01 CST 2014 require("./comm/header.inc.php"); $data['title'] = $data['lang']['agentname']; $out = str_replace('TITLE', $data['title'], $out); $gtbl = new WebApp(); $module_list = ""; $hm_module_order = array(); $hm_module_name = array(); $hm_todo_list = array(); $hm_module_db = array(); $moduleNeedDb = ''; $userGroup = $user->getGroup(); $hm = $gtbl->execBy($sql="select * from ".$_CONFIG['tblpre']."fin_todotbl where 1=1 and ((togroup in (" # for multiple groups .$userGroup.") or touser=".$user->getId()." or triggerbyparent in (".$userGroup.") or triggerbyparentid=" .$user->getId().") or $userGroup=1) and istate in (1,2) order by istate desc, id desc limit 7 ", null, $withCache=array('key'=>'info_todo-select-'.$user->getId())); # give overall data to admin grouplevel=1, Nov 10, 2018 #debug("sql:$sql"); if($hm[0]){ $hm = $hm[1]; foreach ($hm as $k=>$v){ $hm_todo_list[$v['id']] = $v; } } $data['todo_state'] = array('0'=>$lang->get('work_task_state_done'), '1'=>$lang->get('work_task_state_todo'), '2'=>$lang->get('work_task_state_doing'), '3'=>$lang->get('work_task_state_pending'), '4'=>$lang->get('work_task_state_cancel')); $data['user_list'] = $user->getUserList(); $mycachedate=date("Y-m-d", time()-(86400*60)); $hm = $gtbl->execBy("select count(parenttype) as modulecount, parenttype from " .$_CONFIG['tblpre']."fin_operatelogtbl where inserttime > '" .$mycachedate." 00:00:00' and parenttype not in ('gmis_info_usertbl', 'gmis_fin_todotbl')" ." group by parenttype order by modulecount desc limit 11", null, $withCache=array('key'=>'fin_operatelog-select-'.$mycachedate)); if($hm[0]){ $hm = $hm[1]; if(is_array($hm)){ foreach($hm as $k=>$v){ $module_list .= "'".$v['parenttype']."',"; $hm_module_order[$k] = $v['parenttype']; } } $module_list = substr($module_list, 0, strlen($module_list)-1); $hm = $gtbl->execBY("select objname,tblname from " .$_CONFIG['tblpre']."info_objecttbl where tblname in ($module_list)", null, $withCache=array('key'=>'info_object-select-'.$module_list)); if($hm[0]){ $hm = $hm[1]; if(is_array($hm)){ foreach($hm as $k=>$v){ $hm_module_name[$v['tblname']] = $v['objname']; } } } $moduleNeedDb = $module_list; } # $hm = $gtbl->execBy("select objname,tblname from " .$_CONFIG['tblpre']."info_objecttbl where addtodesktop > 0 order by addtodesktop", null, $withCache=array('key'=>'info_object-select-desktop')); if($hm[0]){ $hm = $hm[1]; $data['module_list_byuser'] = $hm; #Todo add2desktop by user } else{ $hm = $gtbl->execBy("select objname,tblname from ".$_CONFIG['tblpre']."info_objecttbl order by rand() limit 11", null, $withCache=array('key'=>'info_object-select-desktop-rand')); if($hm[0]){ $hm = $hm[1]; $data['module_list_byuser'] = $hm; } else{ $data['module_list_byuser'] = array(); } } # $module_list = ''; foreach($data['module_list_byuser'] as $k=>$v){ $module_list .= "'".$v['parenttype']."',"; $module_list = substr($module_list, 0, strlen($module_list)-1); } if($moduleNeedDb == ''){ $moduleNeedDb = '\'\''; } if($module_list != ''){ $moduleNeedDb .= ','.$module_list; } $hm = $gtbl->execBY("select modulename,thedb from ".$_CONFIG['tblpre'] ."info_menulist where modulename in ($moduleNeedDb)", null, $withCache=array('key'=>'info_menulist-select-'.$module_list)); if($hm[0]){ $hm = $hm[1]; foreach($hm as $k=>$v){ $hm_module_db[$v['modulename']] = $v['thedb']; } } # $hm = $gtbl->execBy("select count(*) as modulecount from ".$_CONFIG['tblpre']."info_objecttbl where istate=1", null, $withCache=array('key'=>'info_object-select-count')); if($hm[0]){ $hm = $hm[1]; $data['module_count'] = $hm[0]['modulecount']; } $userListOL = array(); $hm = $gtbl->execBy("select id, email from " .$_CONFIG['tblpre']."info_usertbl where istate=1", null, $withCache=array('key'=>'info_user-select-count')); if($hm[0]){ $hm = $hm[1]; $data['user_count'] = count($hm); foreach($hm as $k=>$v){ $userListOL[$v['id']] = $v['email']; } } $hm = $gtbl->execBy("select * from ".$_CONFIG['tblpre']."fin_operatelogtbl order by ".$gtbl->getMyId()." desc limit 7", null, $withCache=array('key'=>'info_user-select-log')); if($hm[0]){ $hm = $hm[1]; $data['log_list'] = $hm; } # dir list, added by <EMAIL>, Sat Mar 12 12:45:24 CST 2016 $navidir = $_REQUEST['navidir']; if($navidir != ''){ $hm = $gtbl->execBy("select * from ".$_CONFIG['tblpre']."info_menulist where levelcode='".$navidir ."' or levelcode like '".$navidir."__' order by levelcode", null, $withCache=array('key'=>'info_menulist-select-by-level-'.$navidir)); if($hm[0]){ $hm = $hm[1]; $data['navidir_list'] = $hm; } else{ $data['navidir_list'] = array(); } #debug($hm, '', 1); } $fp = fopen("./ido.php", "r"); if($fp){ $fstat = fstat($fp); fclose($fp); $mtime = $fstat['mtime']; $data['system_lastmodify'] = date("Y-m-d", $mtime); } $data['start_date'] = $_CONFIG['start_date']; # today's users count $logged_user_count = 1; $mycachedate=date("Y-m-d", time()-(86400*1)); $hm = $gtbl->execBy("select userid from " .$_CONFIG['tblpre']."fin_operatelogtbl where inserttime >= '" .$mycachedate." 00:00:00'" # ." group by userid", null, $withCache=array('key'=>'fin_operatelog-select-usercount-'.$user->getId().'-'.$mycachedate)); if($hm[0]){ #debug($hm); $hm = $hm[1]; $logged_user_count = count($hm); } # module path $module_path = ''; $levelcode = ''; $codelist = ''; include_once($appdir."/comm/modulepath.inc.php"); if(true){ $out .= "<script type=\"text/javascript\">currenttbl='".$tbl."';\ncurrentdb='" .$mydb."';\n currentlistid= {};\n currentpath='".$rtvdir."';\n userinfo={" ."'id':'".$userid ."','email':'".$user->getEmail() ."','group':'".$user->getGroup() ."','branch':'".$user->get('branchoffice') ."','sid':'".$sid ."'};\n </script>\n"; } $data['logged_user_count'] = $logged_user_count; $data['module_list_order'] = $hm_module_order; $data['module_list_name'] = $hm_module_name; $data['module_list_db'] = $hm_module_db; $data['todo_list'] = $hm_todo_list; $data['module_path'] = $module_path; $data['user_list_ol'] = $userListOL; $data['lang']['welcome_back'] = $lang->get('welcome_back'); $data['lang']['navi_homepage'] = $lang->get('navi_homepage'); $data['lang']['navi_dir'] = $lang->get('navi_dir'); $data['lang']['todayis'] = $lang->get('todayis'); $data['lang']['work_todo'] = $lang->get('menu_desktop_todo'); $data['lang']['work_task'] = $lang->get('work_task'); $data['lang']['state'] = $lang->get('state'); $data['lang']['demand'] = $lang->get('demand'); $data['lang']['supply'] = $lang->get('supply'); $data['lang']['updatetime'] = $lang->get('updatetime'); $data['lang']['more'] = $lang->get('more'); $data['lang']['user'] = $lang->get('user'); $data['lang']['object'] = $lang->get('object'); $data['lang']['module'] = $lang->get('module'); $data['lang']['sys_online'] = $lang->get('sys_online'); $data['lang']['online_user'] = $lang->get('online_user'); $data['lang']['homesite'] = $lang->get('open_homesite'); $data['lang']['operation'] = $lang->get('operation'); $data['lang']['mostused'] = $lang->get('navi_mostused'); $data['lang']['mostused_hint'] = $lang->get('navi_mostused_hint'); $data['lang']['desktop_shortcut'] = $lang->get('navi_desktop'); $data['lang']['desktop_shortcut_hint'] = $lang->get('navi_desktop_hint'); $data['lang']['operatelog'] = $lang->get('navi_operatelog'); $data['lang']['operatelog_hint'] = $lang->get('navi_operatelog_hint'); $smttpl = getSmtTpl(__FILE__, $act); $smt->assign('agentname', $_CONFIG['agentname']); $smt->assign('welcomemsg',$welcomemsg); $smt->assign('desktopurl', $url); $smt->assign('url', $url); $smt->assign('ido', $ido); $smt->assign('jdo', $jdo); $smt->assign('today', date("Y-m-d")); $smt->assign('historyurl', $ido.'&tbl=info_operatelogtbl&tit='.$lang->get('menu_desktop_operatelog').'&a1=0&pnsktogroup=' .$userGroup.'&pnskuserid='.$userid); $navi = new PageNavi(); $pnsc = "state=? and (touser like '".$user->getId()."' or togroup like '".$userGroup."')"; $smt->assign('todourl','ido.php?tbl=fin_todotbl&tit='.$lang->get('menu_desktop_todo').'&a1=1&pnskistate=0&pnsm=1&pnsktouser='.$userid .'&pnsc='.$pnsc.'&pnsck='.$navi->signPara($pnsc).'&pnsktogroup='.$userGroup); $smt->assign('sid', $sid); $smt->assign('userid', $userid); $smt->assign('content',$out); $smt->assign('rtvdir', $rtvdir); $smt->assign('isheader', $isheader); $smt->assign('watch_interval', $_CONFIG['watch_interval']); $watchRld = Wht::get($_REQUEST, 'watchRld'); $watchRld = $watchRld=='' ? 1 : $watchRld; $smt->assign('watch_interval_reload', $watchRld); require("./comm/footer.inc.php"); ?><file_sep>/comm/header.inc.php <?php //- embedded in app entry global $appdir, $userid, $user, $gtbl, $out, $data, $lang; date_default_timezone_set("GMT"); # UTC+0000 $docroot = $_SERVER['DOCUMENT_ROOT']; $rtvdir = dirname(dirname(__FILE__)); # relative dir $rtvdir = str_replace($docroot, "", $rtvdir); $appdir = $docroot.$rtvdir; if(false){ //- due to soft links in os $appdir = $docroot; $dirArr = explode("/", $rtvdir); $rtvdir = "/".$dirArr[count($dirArr)-1]; $appdir .= $rtvdir; } if($rtvdir == ''){ $tmpDirArr = explode("/", $_SERVER['PHP_SELF']); $rtvdir = '/'.$tmpDirArr[1]; $tmpDirArr = null; } #print "docroot:[$docroot] rtvdir:[$rtvdir] appdir:[$appdir]."; #exit(0); $dirArr = explode("/", $rtvdir); $shortDirName = $dirArr[count($dirArr)-1]; # the name of gMIS subdir, i.e. admin, mgmt ...Sat May 23 22:43:21 CST 2015 require_once($appdir."/inc/config.class.php"); $is_debug = $_CONFIG['is_debug']; if($is_debug){ header("Cache-Control: no-store, no-cache, must-revalidate"); header("Expires: Thu, 01 Jan 1970 00:00:00 GMT"); error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING); error_reporting(-1); ini_set('error_reporting', E_ALL ^ E_NOTICE); ini_set("display_errors", 1); } else{ header("Cache-Control: public, max-age=604800"); # a week? error_reporting(E_ERROR | E_PARSE); ini_set('error_reporting', E_ERROR | E_PARSE); ini_set("display_errors", 0); } header("X-Frame-Options: sameorigin"); //- 10:11 2020-12-25 require_once($appdir."/class/user.class.php"); require_once($appdir."/comm/tools.function.php"); require($appdir."/class/gtbl.class.php"); require($appdir."/class/pagenavi.class.php"); require_once($appdir."/class/base62x.class.php"); require_once($appdir."/class/language.class.php"); #session_start(); # in initial stage, using php built-in session manager # implemented with no storage session by <EMAIL>, Tue, 7 Mar 2017 22:54:31 +0800 #const UID = 'UID'; const SID = 'SID'; define("UID", $_CONFIG['agentalias'].'_user_id'); define("SID", 'sid'); $_CONFIG['client_ip'] = Wht::getIp(); # imprv4ipv6 $_CONFIG['is_ipv6'] = strpos($_CONFIG['client_ip'], ':')>0 ? 1 : 0; #debug("comm/header: is_ipv6:".$_CONFIG['is_ipv6']." ip:".$_CONFIG['client_ip']); if(!isset($user)){ $user = new User(); $user->setTbl($_CONFIG['tblpre']."info_usertbl"); } $userid = ''; $out = ''; $htmlheader = ''; $data = array(); $reqUri = $_SERVER['REQUEST_URI']; $reqUri = startsWith($reqUri, '/') ? $reqUri : '/'.$reqUri; $reqUri = str_replace('jdo.php', 'ido.php', $reqUri); $thisUrl = 'http' . (isset($_SERVER['HTTPS']) ? 's' : '') . '://' . "{$_SERVER['HTTP_HOST']}{$reqUri}"; $sid = Wht::get($_REQUEST, SID); if(true){ $dotPos = strpos($sid, '.'); if($dotPos > 0){ $tmpArr = explode('.', $sid); $pureSid = $tmpArr[0]; $_REQUEST['sid'] = $pureSid; if(!isset($_REQUEST['lang'])){ $_REQUEST['lang'] = $tmpArr[1]; } } } # user $isLogin = false; if(strpos($_SERVER['PHP_SELF'],'signupin.php') > 0){ $isLogin = true; } if(!$isLogin){ $userid = $user->getUserBySession($_REQUEST); } //- @todo: workspace id, see inc/config if($userid != ''){ $user->setId($userid); } else if(!$isLogin){ header("Location: ".$rtvdir."/extra/signupin.php?act=signin&bkl=".Base62x::encode($thisUrl)); exit(0); } else{ //debug("comm/header: empty userid, to signupin. what next? thisUrl:$thisUrl "); } # language $ilang = "zh"; if(true){ $icoun = "CN"; $langconf = array(); $reqtlang = Wht::get($_REQUEST, 'lang'); if($reqtlang == ''){ $langs = trim($_SERVER['HTTP_ACCEPT_LANGUAGE']); $sepPos = strpos($langs, ','); if($sepPos > 0){ $langs = substr($langs, 0, $sepPos); } if(strpos($langs, '-') > 0){ $tmpArr = explode('-', $langs); $ilang = $tmpArr[0]; $tmpArr[1]; } else{ $ilang = "zh"; } } else{ $ilang = $reqtlang; } $langconf['language'] = $ilang; $lang = new Language($langconf); if($is_debug){ debug("comm/header: ilang:".$lang->getTag()." welcome:".$lang->get("welcome")); } $data['lang']['welcome'] = $lang->get('welcome'); $tmpAgent = $lang->get('lang_agentname'); if($tmpAgent == $lang->get('lang_agentname_orig') && $_CONFIG['agentname'] != '' ){ $tmpAgent = $_CONFIG['agentname']; } $data['lang']['agentname'] = $tmpAgent; $data['lang']['appchnname'] = $lang->get('lang_appchnname'); $data['lang']['ilang'] = $ilang; //- set to cookie if necessary, @todo } if($_REQUEST['lang'] != ''){ $sid = Wht::get($_REQUEST, 'sid').'.'.Wht::get($_REQUEST, 'lang'); } $ido = $rtvdir.'/ido.php?'.SID.'='.$sid; $jdo = $rtvdir.'/jdo.php?'.SID.'='.$sid; $url = $rtvdir.'/?'.SID.'='.$sid; if(!isset($isoput)){ $isoput = true; } # convert user input data to variables, tag#userdatatovar $base62xTag = 'b62x.'; if(true){ foreach($_REQUEST as $k=>$v){ $k = trim($k); if($k != '' && !inList($k, 'user,lang,userid,appdir,data,out')){ if(preg_match("/([0-9a-z_]+)/i", $k, $matcharr)){ $k_orig = $k = $matcharr[1]; if(is_string($v)){ $v = trim($v); if(stripos($v, "<") !== false){ # <script , <embed, <img, <iframe, etc. Mon Feb 1 14:48:32 CST 2016 $v = str_ireplace("<", "&lt;", $v); } if(inString($base62xTag, $v)){ if(inString(',', $v)){ $tmpArr = explode(',', $v); $v = ''; foreach($tmpArr as $tmpk=>$tmpv){ if(startsWith($tmpv, $base62xTag)){ $tmpv = Base62x::decode(substr($tmpv, 5)); } $tmpArr[$tmpk] = $tmpv; } $v = implode(',', $tmpArr); } else{ if(startsWith($v, $base62xTag)){ $v = Base62x::decode(substr($v, 5)); } } } $_REQUEST[$k] = $v; } $data[$k] = $v; if(true){ # preg_match("/[^\x20-\x7e]+/", $v) #eval("\${$k} = \"$v\";"); # risky, Tue Aug 28 19:40:10 CST 2018 ${$k} = $v; } else{ # @todo } } else{ # @todo } } else{ # @todo } } } if(isset($_REQUEST['isoput'])){ if($_REQUEST['isoput'] == 1){ $isoput = true; } else{ $isoput = false; } } if(!isset($isheader)){ $isheader = true; } if(isset($_REQUEST['isheader'])){ if($_REQUEST['isheader'] == 1){ $isheader = true; } else{ $isheader = false; } } if($isoput){ if(!$isheader){ # another place at view/header.html! $htmlheader = '<!DOCTYPE html><html lang="'.$ilang.'"> <head> <!-- other stuff in header.inc --> <meta http-equiv="Content-Type" content="text/html;charset=utf-8" /> <meta charset="utf-8"/> <title>TITLE - '.$_CONFIG['appname'].' -'.$_CONFIG['agentname'].'</title> <link rel="stylesheet" type="text/css" href="'.$rtvdir.'/comm/default.css" /> <script type="text/javascript" src="'.$rtvdir.'/comm/GTAjax-5.7.js" charset=\"utf-8\" async></script> <script type="text/javascript" src="'.$rtvdir.'/comm/ido.js?i=' .($is_debug==1?rand(0,9999):'').'" charset=\"utf-8\" async></script> <script type="text/javascript" src="'.$rtvdir.'/comm/ido_proj.js?i=' .($is_debug==1?rand(0,9999):'').'" charset=\"utf-8\" async></script> <script type="text/javascript" src="'.$rtvdir.'/comm/popdiv.js" charset=\"utf-8\" async></script> <script type="text/javascript" src="'.$rtvdir.'/comm/navimenu/navimenu.js" charset=\"utf-8\" async></script> <script type="text/javascript" src="'.$rtvdir.'/comm/Base62x.class.js" charset=\"utf-8\" async></script> <link rel="stylesheet" type="text/css" href="'.$rtvdir.'/comm/navimenu/navimenu.css" /> <link href="'.$rtvdir.'/comm/skin.css?i=" rel="stylesheet" type="text/css"/> </head> <body> <!-- style="'.($isheader==0?"":"width:880px").'" -->'; } if($isheader){ if($userid != ''){ $welcomemsg .= $lang->get('welcome').", "; $welcomemsg .= "<a href='".$rtvdir."/ido.php?tbl=info_usertbl&id=".$userid ."&act=view' class='whitelink'>"; $welcomemsg .= $user->getEmail()." $userid</a> !</b>&nbsp; "; $welcomemsg .= "<a href=\"".$rtvdir."/extra/signupin.php?act=resetpwd&userid=" .$userid."\" class='whitelink'>".$lang->get('user_reset_pwd')."</a>"; $welcomemsg .= "&nbsp;&nbsp;<select name='langselect' style='background-color:silver;'" ." onchange=\"javascript:window.location.href='".$url."&lang='+this.options[this.selectedIndex].value;\"> <option value='en'".($ilang=='en'?' selected':'').">English</option> <option value='zh'".($ilang=='zh'?' selected':'').">中文</option> <option value='fr'".($ilang=='fr'?' selected':'').">Français</option> <option value='ja'".($ilang=='ja'?' selected':'').">日本語</option> </select>" ."&nbsp;&nbsp;<a href=\"".$rtvdir."/extra/signupin.php?act=signout&bkl=".Base62x::encode($thisUrl) ."\" class='whitelink'>".$lang->get('user_sign_out')."</a> &nbsp;"; $menulist = ''; include($appdir."/comm/navimenu/navimenu.php"); $out .= "<div style=\"width:100%;clear:both\" id=\"navimenu\">".$menulist."</div>"; //show message number if there are new messages. $out .= "<div id=\"a_separator\" style=\"height:10px;margin-top:25px;clear:both\"></div>" ."<!-- height:15px;margin-top:8px;clear:both;text-align:center;z-index:99 -->"; $data['lang']['copyright'] = $lang->get('copyright'); } } else if(!startsWith($act, "modify") && !inString('-addform', $act) && !inString("/extra", $thisUrl)){ $out .= "<style>html{background:white;}</style><!--$thisUrl-->"; } } # initialize new parameters $i = $j = $id = 0; $randi =0; $tbl = $field = $fieldv = $fieldargv = $act = ''; $xmlpathpre = $appdir."/xml"; $elementsep = $_CONFIG['septag']; $db = $_REQUEST['db']; # data db which may differs from $mydb, see ido.php and comm/tblconf.php $mydb = $_CONFIG['dbname']; # main db on which the app relies $db = $db=='' ? $mydb : $db; $tit = $_REQUEST['tit']; $tbl = $_REQUEST['tbl']; $tblrotate = $_REQUEST['tblrotate']; $act = $_REQUEST['act']; $tit = $tit==''?$tbl:$tit; $id = isset($_REQUEST['pnskid']) ? $_REQUEST['pnskid'] : $_REQUEST['id']; $fmt = isset($_REQUEST['fmt'])?$_REQUEST['fmt']:''; # by wadelau on Tue Nov 24 21:36:56 CST 2015 if($fmt == ''){ header("Content-type: text/html;charset=utf-8"); } else if($fmt == 'json'){ header("Content-type: application/json;charset=utf-8"); } $randi = rand(100000, 999999); if(strpos($tbl,$_CONFIG['tblpre']) !== 0){ $tbl = $_CONFIG['tblpre'].$tbl; //- default is appending tbl prefix } # tbl test, see inc/webapp.class::setTbl if(true){ # used in mix mode to cover all kinds of table with or without tbl prefix $oldtbl = $tbl; #$tbl = (new GTbl($tbl, null, ''))->setTbl($tbl); $tmpgtbl = new GTbl($tbl, null, ''); $tbl = $tmpgtbl->getTbl(); if($tbl != $oldtbl){ $_REQUEST['tbl'] = $tbl; } $tmpgtbl = null; } if(isset($_REQUEST['parent'])){ $tmpnewk = 'pnsk'.$_REQUEST['parent']; $_REQUEST[$tmpnewk] = $_REQUEST[$_REQUEST['parent']]; # print "tmpnewk:[$tmpnewk] value:[".$_REQUEST[$_REQUEST['parent']]."]"; } # check access control $superAccess = ''; include($appdir."/act/checkaccess.inc.php"); # template file info require($_CONFIG['smarty']."/Smarty.class.php"); $smt = new Smarty(); $viewdir = $appdir.'/view'; $smt->setTemplateDir($viewdir); $smt->setCompileDir($viewdir.'/compile'); $smt->setConfigDir($viewdir.'/config'); $smt->setCacheDir($viewdir.'/cache'); $smttpl = ''; function exception_handler($exception) { echo '<div class="alert alert-danger">'; echo '<b>Fatal error</b>: Uncaught exception \'' . get_class($exception) . '\' with message '; echo $exception->getMessage() . ' .<br/> <!--- please refer to server log. --> Please report this to administrators.'; # hide sensitive information about server and script location from public. error_log($exception->getTraceAsString()); error_log("thrown in [" . $exception->getFile() . "] on line:[".$exception->getLine()."]."); echo '</div>'; } set_exception_handler('exception_handler'); ?> <file_sep>/comm/gMISPivotDraw.js /** * gMIS Pivot Draw * work with act/pivot.php * Xexnin@<EMAIL> * ver 0.1 * Fri, 4 Aug 2017 21:08:12 +0800 */ function gMISPivotDraw(dataTbl, calList, grpList, sumList, statList, targetTbl){ var dtbl = dataTbl; //console.log("dtbl:"+dtbl+", calList:["+calList+"] grpList:["+grpList+"] sumList:[" // +sumList+"] statList:["+statList+"]"); console.log("dtbl:"+dtbl+", calList:["+calList+"]"); var widthWeight = 1.8; // more space for calculate fields var barPercent = 0.92; // bar width percent, leave space for chars right var objtbl = document.getElementById(dtbl); calList = JSON.parse(calList); grpList = JSON.parse(grpList); sumList = JSON.parse(sumList); statList = JSON.parse(statList); var diagramStr = '<table id="gmis_pivot_draw_tbl" style="border:1px solid black; ' +'width:96%; margin-left:auto; margin-right:auto;" class="gmis_pivot_draw_tbl">'; if(objtbl){ var rowLen = objtbl.rows.length; var statColArr = new Array(); for(var i=0; i<rowLen; i++){ var cells = objtbl.rows[i].cells; var cellLen = cells.length; diagramStr += '<tr>'; for(var j=0; j<cellLen; j++){ var tdv = cells[j].innerText; //console.log("tr:"+i+", td:"+j+", val:"+tdv); if(i==1){ // very first row if(statList.hasOwnProperty(tdv)){ statColArr[j] = tdv; } else{ statColArr[j] = ''; } //console.log('j:'+j+' tdv:'+tdv+', colName:'+statColArr[j]); } else if(tdv == 'GrandTotal' || tdv == 'Average.of' || tdv == 'Max.of' || tdv == 'Min.of' || tdv == 'ALL'){ //- sensitive fields, skip break; } if(i> 1 && statColArr[j] != ''){ // from 2nd row var colName = statColArr[j]; var maxN = statList[colName]['max']; var minN = statList[colName]['min']; var prtofsum = shortenDecimal(tdv*100/(sumList[colName])); //- sumList? var prtofmax = shortenDecimal(tdv*100/(maxN)); //- statList? var tdWidth = 100/(cellLen/widthWeight); var perctChar = prtofsum + '%'; if(tdv == maxN){ perctChar = '<span style="color:red;"><b>'+prtofsum+'%</b></span>'; } else if(tdv == minN){ perctChar = '<span style="color:silver;">'+prtofsum+'%</span>'; } diagramStr += '<td style="overflow:hidden;width:'+tdWidth+'%;"><span style="width:' +(prtofmax*barPercent)+'%;" title="'+tdv+'" class="spanbar">' +shortenDecimal(tdv)+'</span> '+perctChar+'</td>'; } else{ diagramStr += '<td>'+tdv+'</td>'; } } diagramStr += '</tr>'; } } else{ console.log('objtbl failed. 201708042105.'); } diagramStr += '</table>'; var tgttbl = document.getElementById(targetTbl); if(tgttbl){ tgttbl.innerHTML = diagramStr; } else{ console.log('targettbl failed. 201708042208.'); } return true; } //- simple sprintf //- Mon, 7 Aug 2017 22:42:32 +0800 function shortenDecimal(f){ var fa = f + ''; var dotPos = fa.indexOf('.'); if(dotPos > -1){ var fi = fa.substring(0,dotPos); fa = fi + fa.substr(dotPos, 2); } return fa; } <file_sep>/class/insitesearch.class.php <?php /* In-site Search class * v0.1, * <EMAIL> * Tue May 29 19:58:37 CST 2018 */ if(!defined('__ROOT__')){ define('__ROOT__', dirname(dirname(__FILE__))); } require_once(__ROOT__.'/inc/webapp.class.php'); class InSiteSearch extends WebApp{ var $ver = 0.01; var $currTime = ''; const SID = 'sid'; # public function __construct($args=null){ $this->setTbl(GConf::get('tblpre').'insitesearchtbl'); //- init parent parent::__construct($args); $this->currTime = date("Y-m-d H:i:s", time()); } # public function __destruct(){ } # # public function saveInfo($rowList, $itbl, $idb){ $rtn = 0; $isep = "\t\t"; $targetList = array(); $md5List = '"0"'; $fieldList = array(); # rows foreach($rowList as $k=>$v){ # fields foreach($v as $k2=>$v2){ $ifield = $k2; if(!isset($fieldList[$ifield])){ $fieldList[$ifield] = 1; $targetList[$ifield]['emptyc'] = 0; $targetList[$ifield]['numberc']++; $targetList[$ifield]['inblacklist'] = 0; } $v2 = trim($v2); if($v2 == ''){ $targetList[$ifield]['emptyc']++; continue; } else if(is_numeric($v2)){ $targetList[$ifield]['numberc']++; continue; } else if(startsWith($v2, 'http')){ $targetList[$ifield]['inblacklist'] = 1; continue; } } } # remove unwelcome #debug("bfr trim targetList:".serialize($fieldList)); $rowCount = count($rowList); $tmpFieldList = array(); foreach($fieldList as $k=>$v){ $ifield = $k; $needRm = false; if($targetList[$ifield]['inblacklist'] == 1){ $needRm = true; } else if($targetList[$ifield]['emptyc'] > $rowCount * 0.8){ # why .6? $needRm = true; } else if($targetList[$ifield]['numberc'] > $rowCount * 0.5){ # why .1? $needRm = true; } if(!$needRm){ $tmpFieldList[$ifield] = 1; } } $fieldList = $tmpFieldList; # save new #debug("reach targetList:".serialize($fieldList)); #print_r($fieldList); $succi = 0; foreach($fieldList as $k=>$v){ $ifield = $k; $imd5 = md5($tmps=$idb.$isep.$itbl.$isep.$ifield); $hm = $this->execBy($sql="select id from ".$this->getTbl() ." where imd5='".$imd5."' limit 1", null); if($hm[0]){ $hm = $this->execBy($sql="update ignore ".$this->getTbl() ." set updatetime='".$this->currTime."'" ." where imd5='$imd5'", null); debug("imd5:$imd5, update sql:$sql\n"); #$rtn .= $tmps . " save succ\n"; debug($tmps . " update succ\n"); $succi++; } else{ $hm2 = $this->execBy($sql="insert ignore into ".$this->getTbl() ." set idb='$idb', itbl='$itbl'," ." ifield='$ifield', ivalue=''," ." imd5='$imd5', updatetime='".$this->currTime."'" ." ", null); if($hm2[0]){ debug($tmps . " update failed. try to insert, succc."); } else{ debug($tmps . " update failed. try to insert,but failed again."); } } } $rtn = $succi; return $rtn; } # public function rmOldField(){ $rtn = 0; $hm = $this->execBy($sql="delete from ".$this->getTbl() ." where updatetime < '".$this->currTime."'", null); if($hm[0]){ $hm = $hm[1]; debug("rmOld: succ with sql:$sql\n"); } else{ debug("rmOld: failed with sql:$sql\n"); } } # # } ?> <file_sep>/comm/ido_proj.js //- //- proj specified funcs //- added by <EMAIL>, 10:34 Sunday, January 10, 2016 //- //- fill default value //- <EMAIL>, 19:03 27 November 2017 //- randType = string, number, date, [sys values] //- e.g. //- <delayjsaction>onload::3::fillDefault('apikey','string',16);</delayjsaction> //- if(typeof userinfo == 'undefined'){ userinfo = {}; } //- function fillDefault(fieldId, randType, randLen){ var f = document.getElementById(fieldId); if(f){ var oldv = f.value; if(oldv == ''){ if(randType == null || randType == ''){ randType = 'string'; } if(randLen == null || randLen == 0 || randLen == ''){ radnLen = 16 } if(randType == 'string'){ var randVal = ''; var sDict = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; for (var i = 0; i < randLen; i++){ randVal += sDict.charAt(Math.floor(Math.random() * sDict.length)); } } f.value = randVal; console.log(' randVal:['+randVal+'] fillDefault succ.'); } else{ console.log('oldv not empty. fillDefault stopped.'); } } else{ console.log('fieldId:['+fieldId+'] invalid. fillDefault failed.'); } } //- //- fillSubInput, xenxin@ufqi, Sun Jun 13 11:13:44 CST 2021 //- switch child input type by parent select option, as supper for fillSubSelect /* <field name="fieldid"> <chnname>属性名称</chnname> <selectoption>fromtable::item_fieldtbl::fieldname::itype=THIS_itype::id</selectoption> <jsaction>onchange::fillSubInput('fieldid', 'fieldvalue', 'itemField', './extra/readtblfield.php');</jsaction> <memo>如果列表中没有,可以去 扩展属性定义 中新增</memo> </field> <field name="fieldvalue"> <chnname>属性值</chnname> <inputtype>textarea</inputtype> <jsaction>ondblclick::fillSubInput('fieldid', 'fieldvalue', 'itemField', './extra/readtblfield.php');</jsaction> <memo>数值型直接录入数字, 不用单位; 选择性的 是/有 选数字1, 否/无 选数字0; 文本内容的直接录入文字内容. &amp;nbsp;双击可转换> 输入方式</memo> </field> */ function fillSubInput(parentId, childId, logicId, myUrl){ var fieldv = _g(parentId).options[_g(parentId).selectedIndex].value; var fieldorig = _g(childId+'_select_orig').value; fieldorig = fieldorig == null ? '' : fieldorig; console.log("currentVal:["+fieldv+"]"); console.log("fillSubInput: fieldv:["+fieldv+"] logicId:["+logicId+"] orig_value:["+fieldorig+"]"); if(fieldv != ''){ //- if(logicId == 'itemField'){ var gta = new GTAjax(); gta.set('targetarea', 'addareaextradiv'); gta.set("callback", function(){ //window.alert("getresult:["+this+"]"); var resp = this; if(resp.indexOf('<pre') > -1){ var resp_1 = /<pre[^>]*>([^<]*)<\/pre>/g; var resp_2 = resp_1.exec(resp); resp = resp_2[1]; } //console.log("getresult:["+resp+"]"); var jsonResp = JSON.parse(JSON.parse(resp)); //- <pre>"REAL_JSON_STRING"</pre> //console.log("getresult:["+resp+"] jsonResp:"+jsonResp+" "); var fieldInfo = jsonResp.result_list[0] ; console.log("fieldInfo:["+fieldInfo+"] str:"+JSON.stringify(fieldInfo)); var childObj = _g(childId); var childOrigVal = childObj.value; if(fieldInfo.fieldtype == 4 || fieldInfo.fieldtype == 3){ //- multiple or single select var myInput = "<select id='"+childId+"' name='"+childId+"'>"; var myOptions = ""; if(fieldInfo.fieldoption.indexOf('|') > -1){ var tmpOptions = fieldInfo.fieldoption.split('|'); var tmmj = 0; for(var tmpi in tmpOptions){ if(tmpOptions[tmpi]=='\u662f' || tmpOptions[tmpi] == '有'){ tmpj = 1; } else if(tmpOptions[tmpi]=='\u5426' || tmpOptions[tmpi] == '无'){ tmpj = 0; } else{ tmpj = tmpi; } myOptions += "<option value='"+(tmpj)+"'"+(tmpj==childOrigVal?" selected":"")+">" +tmpOptions[tmpi]+"("+tmpj+")</option>" } } else{ myOptions += "<option value='0'"+(0==childOrigVal?" selected":"")+">否, 无(0)</option>" +"<option value='1'"+(1==childOrigVal?" selected":"")+">是, 有(1)</option>"; } myInput += myOptions + "</select>"; var newSpan = document.createElement('span'); newSpan.innerHTML = myInput; var childUpObj = childObj.parentNode; childUpObj.insertBefore(newSpan, childObj); childUpObj.removeChild(childObj); } else if(fieldInfo.fieldtype == 2 || fieldInfo.fieldtype == 1){ //- single line input var myInput = "<input id='"+childId+"' name='"+childId+"' value='"+childOrigVal+"'/>"; var newSpan = document.createElement('span'); newSpan.innerHTML = myInput; var childUpObj = childObj.parentNode; childUpObj.insertBefore(newSpan, childObj); childUpObj.removeChild(childObj); } else{ //- textarea as default... } //console.log("?-fieldtype:"+fieldInfo.fieldtype); }); gta.get(appendSid(myUrl+'?objectid='+fieldv+'&isoput=0&logicid='+logicId+'&tbl=item_fieldtbl')); } //- } else{ console.log("ido.js::fillSubInput::fieldv:["+fieldv+"] is empty."); } } <file_sep>/class/xtree.class.php <?php /* * XTree class for unlimited tree-like directory with parentid and id * <EMAIL>, * Sat May 8 10:51:12 CST 2021 * */ if(!defined('__ROOT__')){ define('__ROOT__', dirname(dirname(__FILE__))); } require_once(__ROOT__.'/inc/webapp.class.php'); class XTree extends WebApp{ public $lang = null; function __construct($tbl = ''){ # db $db = $reqdb = trim($_REQUEST['db']); if($reqdb != ''){ $args = array('dbconf'=>($db==GConf::get('maindb')? '' : $db)); if($args['dbconf'] == 'newsdb'){ $args['dbconf'] = 'Config_Master'; } # other args options parent::__construct($args); } else{ $this->dba = new DBA(); } # tbl if($tbl != ''){ if($_CONFIG['language'] && $_CONFIG['language'] == "en_US"){ //$this->setTbl(GConf::get('tblpre').'en_'.$tbl); $this->setTbl('en_'.$tbl); } else{ //$this->setTbl(GConf::get('tblpre').$tbl); $this->setTbl($tbl); } } # lang if(true){ #debug("mod/pagenavi: lang: not config. try global?"); global $lang; $this->lang = $lang; # via global? } } # get dir list, expand all of directories above the target dir or its same level, "open all to target" function getList($targetDir, $levelLen){ $dirList .=""; return $dirList; } } ?><file_sep>/comm/ido.js //- //- init from Mon Jul 28 15:38:37 CST 2014 //- Fri Aug 1 13:58:12 CST 2014 //-- Thu Sep 11 09:30:12 CST 2014 //-- Thu Sep 25 16:07:58 CST 2014 //-- Mon Sep 29 16:01:21 CST 2014 //-- Mon Oct 27 15:58:46 CST 2014 //-- 09:48 Wednesday, July 01, 2015 //- with ido_proj.js , 10:37 Sunday, January 10, 2016 //- wrap iId as string, 09:03 09 October 2016 //- imprvs on searchbytime, Thu, 2 Mar 2017 16:32:06 +0800 //- bugfix on firefox with event, 23:34 02 August 2017 //- bugfix for async, 19:14 Thursday, 15 March, 2018 //- imprvs on pivot with addgroupbyseg, 17 August, 2018 //- imprvs on pickup, Fri Sep 21 21:09:34 CST 2018 //- imprvs on todo/filedir, Sat Oct 20 CST 2018 //- imprvs with userinfo.$lang, Tue Nov 5 03:39:27 UTC 2019 //- bugfix for getUrlByTime and PickUp, 13:33 Saturday, March 28, 2020 var currenttbl = currenttbl ? currenttbl : ''; var currentdb = currentdb ? currentdb : ''; var currentpath = currentpath ? currentpath : ''; var currentlistid = currentlistid ? currentlistid : {}; //-- associative array var userinfo = userinfo ? userinfo : {}; //- userinfo.$lang = userinfo.$lang ? userinfo.$lang : {}; userinfo.pickUpFromTag = '&frompickup=1'; if(!window.console){ console = { log:function(){}}; } //-- script used in /manage/items/index.jsp, 20090303, wadelau function pnAction(url){ if(url.indexOf("act=") == -1 && url.indexOf("?") > -1){ url += "&act=list"; } doAction(url); } //- function doAction(strUrl){ var rtn = true; var sActive = "actarea"; var myAjax = new GTAjax(); myAjax.set('targetarea',sActive); myAjax.set('forceframe',true); myAjax.set('nobacktag','nobacktag'); var tmps = myAjax.get( appendTab(strUrl) ); if(typeof strUrl == 'string'){ if(strUrl.indexOf('needautopickup=no') < 0){ //- see extra/linktbl if(strUrl.indexOf('&act=list') > -1 && strUrl.indexOf(userinfo.pickUpFromTag) == -1){ var pickUpUrl = strUrl.replace('&act=list', '&act=pickup'); var doActionPickUpTimer=window.setTimeout(function(){ doActionEx(pickUpUrl, 'contentarea'); }, 2*1000); //console.log('doAction: found list refresh, trigger pickup reload.... timer:'+doActionPickUpTimer+' purl:'+pickUpUrl); if(typeof userinfo.PickUpList == 'undefined'){ userinfo.PickUpList = {}; } userinfo.PickUpList.latestUrl = pickUpUrl; } } } if(typeof userinfo.time2Quit != 'undefined'){ userinfo.time2Quit = (new Date()).getTime() + parseInt(userinfo.time4Renew); } return rtn; } function doActionEx(strUrl,sActive){ if(sActive=='addareaextra'){ //document.getElementById('addareaextradiv').style.display='block'; switchArea('addareaextradiv', 'on'); } if(sActive == 'contentarea'){ /* document.getElementById('contentarea_outer').style.display='block'; document.getElementById('contentarea').style.display='block'; */ switchArea('contentarea_outer', 'on'); switchArea('contentarea', 'on'); } var myAjax = new GTAjax(); myAjax.set('targetarea',sActive); myAjax.set('nobacktag','nobacktag'); myAjax.set('forceframe',true); var tmps = myAjax.get( appendTab(strUrl) ); if(typeof strUrl == 'string'){ if(strUrl.indexOf('needautopickup=no') < 0){ //- see extra/linktbl if(sActive == 'actarea' && strUrl.indexOf('&act=list') > -1 && strUrl.indexOf(userinfo.pickUpFromTag) == -1){ var pickUpUrl = strUrl.replace('&act=list', '&act=pickup'); var doActionPickUpTimer=window.setTimeout(function(){ doActionEx(pickUpUrl, 'contentarea'); }, 2*1000); //console.log('doActionEx: found list refresh, trigger pickup reload.... timer:'+doActionPickUpTimer+' purl:'+pickUpUrl); if(typeof userinfo.PickUpList == 'undefined'){ userinfo.PickUpList = {}; } userinfo.PickUpList.latestUrl = pickUpUrl; } } if(strUrl.indexOf('_Updt_Clit_Urlp=1') > -1){ if(typeof userinfo.urlParams == 'undefined'){ userinfo.urlParams={}; }; var tmpTimerId = window.setTimeout(function(){ userinfo.urlParams = getUrlParams(strUrl); console.log("strUrl:["+strUrl+"] try to reload urlparams"); }, 2*1000); } } if(typeof userinfo.time2Quit != 'undefined'){ userinfo.time2Quit = (new Date()).getTime() + parseInt(userinfo.time4Renew); } return tmps; } //- function _g( idName ){ //return document.getElementById( str ); var obj = document.getElementById(idName); var myObj = new Object(); if(obj != null && typeof obj != 'undefined'){ myObj = obj; } else{ var objs = document.getElementsByName(idName); if(objs != null && typeof objs != 'undefined'){ if(objs[0] != null && typeof objs[0] != 'undefined'){ myObj = objs[0]; } } } //console.log("comm/ido: _g idName:"+idName+" myObj:"+JSON.stringify(myObj)); return myObj; } // function appendTab(strUrl){ if(typeof strUrl == 'string'){ if(strUrl.indexOf(".php")>-1){ if(strUrl.indexOf("tbl")==-1){ //window.alert('need to append acctab.'); if(strUrl.indexOf("?")==-1){ strUrl+="?tbl="+currenttbl; } else{ strUrl+="&tbl="+currenttbl; } } if(strUrl.indexOf("db")==-1){ //window.alert('need to append acctab.'); strUrl+="&db="+currentdb; //window.alert('need to append acctab.done:['+strUrl+']'); } } } return appendSid(strUrl); } //- display an area or not function switchArea(sArea, onf){ if(sArea == null || sArea == ''){ sArea = 'contentarea'; } oldv = document.getElementById(sArea).style.display; newv = ''; if(onf == null || onf == ''){ if(oldv == 'block'){ newv = 'none'; }else if(oldv == 'none'){ newv = 'block'; } }else if(onf == 'on'){ newv = 'block'; }else if(onf == 'off'){ newv = 'none'; } document.getElementById(sArea).style.display=newv; } //-- search by a field in navigator menu //-- updt with security enhancement, Spet 08, 2018 function searchBy(url){ var fieldlist = document.getElementById('fieldlist').value; var fieldlisttype = document.getElementById('fieldlisttype').value; var fieldarr = fieldlist.split(","); var fieldtypearr = fieldlisttype.split(","); var typearr = new Array(); for(var i=0; i<fieldtypearr.length; i++){ var tmparr = fieldtypearr[i].split(":"); typearr[tmparr[0]] = tmparr[1]; } var appendquery = ''; var reg1055 = new RegExp(",", 'gm'); var reg1608 = new RegExp("\\\\", 'gm'); var reg1559 = new RegExp("'", 'gm'); if(typeof urlParamList == 'undefined'){ urlParamList = userinfo.urlParams = getUrlParams(); } for(var i=0;i<fieldarr.length;i++){ var fieldv = null; eval("var obj = document.getElementById('pnsk_"+fieldarr[i]+"');"); if(obj != null){ if(typearr[fieldarr[i]] == 'select'){ eval("fieldv = document.getElementById('pnsk_"+fieldarr[i]+"').options[document.getElementById('pnsk_"+fieldarr[i]+"').selectedIndex].value;"); //window.alert('field:'+fieldarr[i]+' select:fieldv:['+fieldv+']'); console.log('field:'+fieldarr[i]+' select:fieldv:['+fieldv+']'); if(fieldv == ""){ var reg = new RegExp("&pnsk"+fieldarr[i]+"=([^&]*)", 'gm'); url = url.replace(reg, ""); reg = new RegExp("&oppnsk"+fieldarr[i]+"=([^&]*)", 'gm'); url = url.replace(reg, ""); continue; } } else{ eval("fieldv = document.getElementById('pnsk_"+fieldarr[i]+"').value;"); } //if(fieldv != fieldarr[i]){ if(fieldv != '~~~'){ var fieldopv = ''; if(document.getElementById('oppnsk_'+fieldarr[i]) != null){ eval("fieldopv = document.getElementById('oppnsk_"+fieldarr[i]+"').options[document.getElementById('oppnsk_"+fieldarr[i]+"').selectedIndex].value;"); console.log('fieldv:['+fieldv+'] fieldop:'+fieldarr[i]+' select:fieldopv:['+fieldopv+']'); if(fieldopv != '----'){ if((fieldopv == 'inrange' || fieldopv == 'inlist') && fieldv == ''){ //- omit } else{ fieldv = fieldv.replace(reg1055, ","); fieldv = fieldv.replace(reg1608, ""); fieldv = fieldv.replace(reg1559, "\\\'"); appendquery += "&pnsk"+fieldarr[i]+"="+fieldv; appendquery += "&oppnsk"+fieldarr[i]+"="+fieldopv; } } else{ //var reg = new RegExp("&oppnsk"+fieldarr[i]+"=([^&]*)"); //url = url.replace(reg, ""); } } else{ fieldv = fieldv.replace(reg1055, ","); appendquery += "&pnsk"+fieldarr[i]+"="+fieldv; } var reg = new RegExp("&pnsk"+fieldarr[i]+"=([^&]*)", 'gm'); url = url.replace(reg, ""); reg = new RegExp("&oppnsk"+fieldarr[i]+"=([^&]*)", 'gm'); url = url.replace(reg, ""); } } else{ var tmpPnsk = 'pnsk'+fieldarr[i]; //- hidden query para, Wed Apr 28 08:25:32 UTC 2021 if(typeof urlParamList[tmpPnsk] != 'undefined'){ appendquery += '&' + tmpPnsk + "=" + urlParamList[tmpPnsk]; } } } //window.alert("fieldlist:"+fieldlist+", url:["+url+"]"); console.log("fieldlist:"+fieldlist+", url:["+url+"]"); //- @todo var reg = new RegExp("&pntc=([0-9]*)", 'gm'); url = url.replace(reg, ""); reg = new RegExp("&pnpn=([0-9]*)", 'gm'); url = url.replace(reg, ""); reg = new RegExp("&pnsk[0-9a-zA-Z]+=([^&]*)", 'gm'); url = url.replace(reg, ""); reg = new RegExp("&oppnsk"+fieldarr[i]+"=([^&]*)", 'gm'); url = url.replace(reg, ""); reg = new RegExp("&id=([^&]*)", 'gm'); //- remove old id query, Mon, 12 Dec 2016 13:41:21 +0800 url = url.replace(reg, ""); doAction(url+appendquery); console.log("fieldlist:"+fieldlist+",last_url:["+url+appendquery+"]"); } //-- 挂表操作传递参数 function sendLinkInfo(vars, rw, fieldtag){ if(rw == 'w'){ if(parent.currentlistid){ //parent.currentlistid[fieldtag] = vars; parent.currentlistid[fieldtag] = decodeURIComponent(vars.replace(/\+/g,' ')); }else{ //window.alert('parent.currentlistid is ['+parent.currentlistid+'].'); } } //window.alert('sendLinkInfo:'+currentlistid[fieldtag]+', 22-:'+parent.currentlistid[fieldtag]+', 33-:'+currentlistid.fieldtag+', 44-:'+parent.currentlistid.fieldtag+', win.href:['+window.location.href+'], rw:['+rw+'] fieldtag:['+fieldtag+']'); if(rw == 'r'){ tmpid = parent.currentlistid[fieldtag]==undefined?'':parent.currentlistid[fieldtag]; parent.currentlistid[fieldtag] = ''; return tmpid; } //console.log('sendLinkInfo: vars:['+vars+'] rw:['+rw+'] fieldtag:['+fieldtag+']'); return true; } //-- auto calculate numbers, designed by <EMAIL>, BGN //-- 16/02/2012 23:11:28 /* example: * onclick="x_calcu_onf(this);" * onchange="x_calcu(this, 'zongzhichu', {'*':'peitongfangshu','+':'otherid'});" * means: zongzhichu = this.value * peitongfangshu + otherid */ var x_currentCalcu = {}; function x_calcu_onf(thisfield){ //window.alert('oldv: ['+thisfield.value+']'); var fieldid = thisfield.id; x_currentCalcu.fieldid = thisfield.value==''?0:thisfield.value; } function x_calcu(thisfield, targetx, otherlist){ var fieldid = thisfield.id; if(x_currentCalcu.fieldid == null || x_currentCalcu.fieldid == undefined || x_currentCalcu.fieldid == 'null'){ var tmpobj = document.getElementById(fieldid); x_currentCalcu.fieldid = tmpobj.value == ''?0:tmpobj.value; } var thisfieldv = thisfield.value==''?0:thisfield.value; var bala = thisfieldv - x_currentCalcu.fieldid; var tgt = document.getElementById(targetx); var formulax = ''; if(tgt != null && isNumber(x_currentCalcu.fieldid) && isNumber(thisfieldv)){ var oldv = tgt.value==''?0:tgt.value; oldv = parseInt(oldv); for(var k in otherlist){ //window.alert('k:['+k+'] val:['+otherlist[k]+']'); var tmpobj = document.getElementById(otherlist[k]); var tmpval = 1; if(tmpobj != null){ tmpval = tmpobj.value==''?0:tmpobj.value; }else if(k == '+' || k == '-'){ tmpval = 0; } formulax += ' ' + k + ' ' + tmpval; } //window.alert('formulax:['+formulax+']'); var balax = eval(bala+formulax); var newv = oldv + parseInt(balax); tgt.value = parseInt(newv); //window.alert('oldv:['+x_currentCalcu.fieldid+'] new-field: ['+thisfield.value+'] bala:['+bala+'] formula:['+formulax+'] balax:['+balax+'] newv:['+newv+']'); //x_currentCalcu.fieldid = null; }else{ window.alert('Javascript:x_calcu: Error! targetx:['+targetx+'] is null or x_currentCalcu.'+fieldid+':['+x_currentCalcu.fieldid+'] is not numeric. \n\tClick an input field firstly.'); thisfield.focus(); } } function isNumber(n){ return !isNaN(parseFloat(n)) && isFinite(n); } //- added Wed Apr 4 19:57:23 CST 2012 function x_calcuTbl(theform, targetx, f){ var id = theform.id; if(typeof id != 'string'){ id = theform.name; } //window.alert('this.id:['+id+'] name:['+theform.name+'] method:['+theform.method+'] formula:['+f+']'); var fArr = f.split(" "); //-- use space to separate each element in the formula var symHm = {'=':'','+':'','-':'','*':'','/':'','(':'',')':''}; for(var i=0; i<fArr.length; i++){ //window.alert('i:['+i+'] f:['+fArr[i]+']'); if(fArr[i] != null && fArr[i] != ''){ if(fArr[i] in symHm){ //- }else{ if(isNumber(fArr[i])){ //- }else{ var field = document.getElementById(fArr[i]); var fVal = null; if(field != null){ fVal = field.value==''?0:field.value; fVal = parseInt(fVal); fVal = fVal == NaN?0:fVal; f = f.replace(new RegExp(' '+fArr[i],"gm"), ' '+fVal); f = f.replace(new RegExp(fArr[i]+' ',"gm"), fVal+' '); }else{ window.alert('x_calcuTbl: Unknown field:['+fArr[i]+']'); } //window.alert('field:['+fArr[i]+'] val:['+fVal+'] new formula:['+f+']'); } } } } //window.alert('new formula:['+f+']'); var targetx = document.getElementById(targetx); if(targetx != null){ targetx.value = eval(f); } } //-- auto calculate numbers, designed by <EMAIL>, END //- dynammic select, bgn, Sun Mar 11 11:36:44 CST 2012 function fillSubSelect(parentId, childId, logicId, myUrl){ var fieldv = document.getElementById(parentId).options[document.getElementById(parentId).selectedIndex].value; var fieldorig = _g(childId+'_select_orig').value; fieldorig = fieldorig == null?'':fieldorig; console.log("currentVal:["+fieldv+"]"); console.log("fieldv:["+fieldv+"] logicId:["+logicId+"] orig_value:["+fieldorig+"]"); if(fieldv != ''){ if(logicId == 'xiane'){ var gta = new GTAjax(); gta.set('targetarea', 'addareaextradiv'); gta.set("callback", function(){ //window.alert("getresult:["+this+"]"); var s = this; //console.log("getresult:["+s+"]"); var sArr = s.split("\n"); for(var i=0;i<sArr.length;i++){ //console.log('i:['+i+'] line:['+sArr[i]+']'); var tmpArr = sArr[i].split(':::'); console.log('key:['+tmpArr[0]+'] val:['+tmpArr[1]+']'); if(tmpArr[0] != '' && tmpArr[0] != 'id' && tmpArr[1] != undefined){ var issel = false; if(fieldorig.indexOf(tmpArr[0]) > -1){ issel = true; } document.getElementById(childId).options[i] = new Option(tmpArr[1]+'('+tmpArr[0]+')',tmpArr[0], true,issel); } } }); gta.get(appendSid(myUrl+'?objectid='+fieldv+'&isoput=0&logicid='+logicId)); }else if(logicId == 'mingcheng'){ var gta = new GTAjax(); gta.set('targetarea', 'addareaextradiv'); gta.set("callback", function(){ //window.alert("getresult:["+this+"]"); var s = this; console.log("getresult:["+s+"]"); var sArr = s.split("\n"); for(var i=0;i<sArr.length;i++){ //console.log('i:['+i+'] line:['+sArr[i]+']'); var tmpArr = sArr[i].split(':::'); console.log('key:['+tmpArr[0]+'] val:['+tmpArr[1]+']'); if(tmpArr[0] != '' && tmpArr[0] != 'id' && tmpArr[1] != undefined){ document.getElementById(childId).options[i] = new Option(tmpArr[1]+'('+tmpArr[0]+')',tmpArr[0], true,false); } } }); gta.get(appendSid(myUrl+'?objectid='+fieldv+'&isoput=0&logicid='+logicId)); }else if(logicId == 'leibie'){ console.log("getinto leibie"); var gta = new GTAjax(); gta.set('targetarea', 'addareaextradiv'); gta.set("callback", function(){ //window.alert("getresult:["+this+"]"); var s = this; console.log("getresult:["+s+"]"); var sArr = s.split("\n"); for(var i=0;i<sArr.length;i++){ //console.log('i:['+i+'] line:['+sArr[i]+']'); var tmpArr = sArr[i].split(':::'); console.log('key:['+tmpArr[0]+'] val:['+tmpArr[1]+']'); if(tmpArr[0] != '' && tmpArr[0] != 'id' && tmpArr[1] != undefined){ var issel = false; if(fieldorig.indexOf(tmpArr[0]) > -1){ issel = true; } document.getElementById(childId).options[i+1] = new Option(tmpArr[1]+'('+tmpArr[0]+')',tmpArr[0], true,issel); } } }); gta.get(appendSid(myUrl+'?tbl=categorytbl&objectid='+fieldv+'&isoput=0&logicid='+logicId+'&parentid=' +parentId+'&childid='+childId)); }else if(logicId == 'area'){ console.log("getinto area"); var gta = new GTAjax(); gta.set('targetarea', 'addareaextradiv'); gta.set("callback", function(){ //window.alert("getresult:["+this+"]"); var s = this; console.log("getresult:["+s+"]"); var sArr = s.split("\n"); for(var i=0;i<sArr.length;i++){ //console.log('i:['+i+'] line:['+sArr[i]+']'); var tmpArr = sArr[i].split(':::'); console.log('key:['+tmpArr[0]+'] val:['+tmpArr[1]+']'); if(tmpArr[0] != '' && tmpArr[0] != 'id' && tmpArr[1] != undefined){ var issel = false; if(fieldorig.indexOf(tmpArr[0]) > -1){ issel = true; } document.getElementById(childId).options[i] = new Option(tmpArr[1]+'('+tmpArr[0]+')',tmpArr[0], true,issel); } } }); gta.get(appendSid(myUrl+'?tbl=areatbl&objectid='+fieldv+'&isoput=0&logicid='+logicId)); } } else{ console.log("ido.js::fillSubSelect::fieldv:["+fieldv+"] is empty."); } } //- dynammic select, end, Sun Mar 11 11:36:44 CST 2012 //-- setSelectIndex, bgn, Tue May 8 20:59:42 CST 2012 //-- 其中一个 select 变化时,其余 select 的 selectedIndex 也跟着动 function setSelectIndex(mySelect, myValue){ var objsel = document.getElementById(mySelect); if(objsel != null){ for(var i = 0; i < objsel.options.length; i++){ if(objsel.options[i].value == myValue){ if(objsel.selectedIndex != i){ objsel.selectedIndex = i; } break; } } } } //-- setSelectIndex, bgn, Tue May 8 20:59:42 CST 2012 userinfo.input2Select = {}; //- switchEditable, bgn, Thu Mar 15 20:14:02 CST 2012 //-- 增加对 select 点击即编辑的支持 function switchEditable(targetObj,fieldName,fieldType,fieldValue,myUrl,readOnly){ if(readOnly != ''){ console.log("field:["+fieldName+"] is not configed to edit in this view. e.g. multiple select, textarea."); return true; } var theobj = targetObj; targetObj = document.getElementById(theobj); targetObj.contentEditable = true; targetObj.style.background = "#ffffff"; var newSelId = theobj+'_new1425'; var newsel = null; var newseldiv = null; if(fieldType == 'select'){ //window.alert('is Select:['+fieldValue+']!'); newsel = document.createElement('select'); newsel.setAttribute('id', newSelId); var searsel = document.getElementById('pnsk_'+fieldName); if(searsel != null){ for(var i=0; i < searsel.length; i++){ //- 复制搜索栏里的select选项到当前 var isselected = false; if(searsel.options[i].value == fieldValue){ isselected = true; } //window.alert('is Select:['+fieldValue+'] currentVal:['+searsel.options[i].value+'] isselected:['+isselected+']!'); newsel.add(new Option(searsel.options[i].text, searsel.options[i].value, isselected, isselected)); } } targetObj.innerHTML = ''; targetObj.appendChild(newsel); } else if(fieldType == 'input2select'){ newseldiv = document.getElementById(newSelId); if(!newseldiv){ newseldiv = document.createElement('div'); newseldiv.setAttribute('id', newSelId); newseldiv.style.cssText = 'display:none;position:absolute;background:#fff;border:#777 solid 1px;margin:-1px 0 0;padding: 5px;font-size:12px; overflow:auto;z-index:49;'; //targetObj.appendChild(newseldiv); targetObj.parentNode.insertBefore(newseldiv, targetObj.nextSibling); } targetObj.onkeyup = function(evt){ evt = evt || window.event; input2Search(targetObj,fieldName, newSelId, 'NEED_OPTION_VALUE'); } //targetObj.onclick = function(evt){ evt = evt || window.event; userinfo.input2Select.makeSelect = 0; } if(!userinfo.input2Select){ userinfo.input2Select = {}; } userinfo.input2Select.makeSelect = 0; } else{ //- bugfix for disp shortening with non-select in list view var tmpv = targetObj.innerHTML; var fieldtmpv = Base62x.decode(fieldValue); if(tmpv.length < fieldtmpv.length){ targetObj.innerHTML = fieldtmpv; console.log("found disp shortenning and remedy..."); } } if(fieldType != 'input2select'){ if(!userinfo.input2Select){ userinfo.input2Select = {}; } userinfo.input2Select.makeSelect = 1; } var oldv = targetObj.innerHTML; var blurObj = targetObj; if(fieldType == 'select'){ oldv = fieldValue; blurObj = newsel; } userinfo.input2Select.originalValue = oldv; blurObj.onblur = function(newVal){ var newv = targetObj.innerHTML; var newvStr = ''; if(fieldType == 'select'){ newv = newsel.options[newsel.selectedIndex].value; newvStr = newsel.options[newsel.selectedIndex].text; } console.log('oldv:['+oldv+'] newv:['+newv+'] newvStr:['+newvStr+'] makeselect:['+userinfo.input2Select.makeSelect+']'); if(newv != oldv && userinfo.input2Select.makeSelect == 1){ //window.alert('newcont:['+newv+'] \noldv:['+oldv+']'); var gta = new GTAjax(); gta.set('targetarea', 'addareaextradiv'); gta.set("callback", function(){ var s = this; var noticeMsg = ''; if(s.indexOf('--SUCC--') > -1){ noticeMsg = userinfo.$lang['notice_success']; sendNotice(true, noticeMsg); } else{ noticeMsg = userinfo.$lang['notice_failure']; sendNotice(false, ''); } }); gta.get(appendSid(myUrl+'&'+fieldName+'='+encodeURIComponent(newv))); } else{ //window.alert('same content. unchanged.'); } targetObj.style.background = "#E8EEF7"; if(fieldType == 'select'){ targetObj.innerHTML = newvStr; }else{ targetObj.innerHTML = newv; } if(fieldType == 'input2select'){ userinfo.input2Select.makeSelect = 0; } userinfo.input2Select.originalValue = newv; } } //- switchEditable, end, Thu Mar 15 20:14:02 CST 2012 //-- notice bgn, Mon Mar 19 21:41:02 CST 2012 function sendNotice(isSucc, sMsg){ var obj = document.getElementById('top_notice_div'); if(obj != undefined && obj != null){ if(isSucc){ obj.innerHTML = '<span style="background-color:yellow; color:green">&nbsp; <b> '+sMsg+' </b> &nbsp;</span>'; } else{ obj.innerHTML = '<span style="background-color:yellow; color:red">&nbsp; <b> '+sMsg+' </b> &nbsp; </span>'; } window.setTimeout(function(){ obj.innerHTML = ''; }, 8*1000); } else{ window.alert(sMsg); } } //-- notice end, Mon Mar 19 21:41:02 CST 2012 //-- register an action to be run in a few seconds later, bgn //-- see xml/x_useraccesstbl.xml function registerAct(tObj){ if(tObj.status == 'onload'){ //window.addEventListener('load', function(){ if(true){ //window.alert('delaytime:['+tObj.delaytime+']'); /* var actx = unescape(tObj.action); actx = actx.replace('+', ' '); //- need to be replaced with -Base62x, 09:14 24 September 2016 actx = actx.replace('\+', ' '); //- need to be replaced with -Base62x, 09:14 24 September 2016 actx = actx.replace('%20', ' '); //- need to be replaced with -Base62x, 09:14 24 September 2016 */ var actx = Base62x.decode(tObj.action); //- imprv, July 26, 2018 var actxId = 0; if(!userinfo.registerAct){ userinfo.registerAct = {}; } actxId = userinfo.registerAct[tObj.action]; if(actxId){ window.clearTimeout(actxId); } actxId = window.setTimeout(actx, tObj.delaytime*1000); userinfo.registerAct[tObj.action] = actxId; };//, false); //console.log('register.action:['+unescape(tObj.action)+'] actx:['+actx+'] axtxId:['+actxId+']'); } else{ console.log((new Date())+" comm/ido: unsupported registerAct:"+tobj.status); } } //-- register an action to be run in a few seconds, end //-- act list, 执行动作, bgn, Sat Jun 2 19:19:12 CST 2012 function doActSelect(sSel, sUrl, iId, fieldVal){ var fieldv = fieldVal; if((fieldv == null || fieldv =='') && fieldv != 'ActOption'){ fieldv = document.getElementById(sSel).options[document.getElementById(sSel).selectedIndex].value; } console.log("doActSelect: fieldv:["+fieldv+"]"); var targetUrl = sUrl; if(fieldv != 'ActOption'){ targetUrl += "&act="+fieldv; } var actListDiv = document.getElementById('divActList_'+iId); var hideActListDiv = 1; if(fieldv != ''){ if(fieldv == 'list-dodelete'){ var deleteDelay = 10; // seconds if(!actListDiv){ console.log('actListDiv was lost.....') } var deleteTimerId = window.setTimeout(function(){ window.console.log('delay delete started.......'+(new Date())); var gta = new GTAjax(); gta.set('targetarea', 'addareaextradiv'); gta.set("callback", function(){ var resp = this; console.log('delete_resp:['+resp+']'); // copy from iframe document ? if(resp.indexOf('<pre') > -1){ var resp_1 = /<pre[^>]*>([^<]*)<\/pre>/g; var resp_2 = resp_1.exec(resp); //console.log('delete_resp_after:['+resp_2[1]+'] id:['+iId+']'); resp = resp_2[1]; } var json_resp = JSON.parse(resp); if(typeof json_resp.resultobj == 'undefined'){ json_resp.resultobj = {}; } var iId = json_resp.resultobj.targetid; //- anonymous func embeded in another anonymos func, cannot share variables in runtime. //console.log('delete_resp_after-2:['+resp+'] id:['+iId+']'); if(json_resp.resultobj.resultcode == 0){ sendNotice(true, userinfo.$lang['notice_success']+' TargetId:['+iId+']'); var its_list_tr = document.getElementById('list_tr_'+iId); if(its_list_tr){ its_list_tr.style.backgroundColor = '#404040'; } var actListDiv = document.getElementById('divActList_'+iId); //- if(actListDiv){ actListDiv.style.display = 'none'; } var parentDataTbl = parent._g('gmisjdomaintbl'); if(typeof parentDataTbl != 'undefined'){ parentDataTbl.deleteRow((parseInt(iId)-1)+3); //- first 3 rows are funcs console.log("found main tbl:["+parentDataTbl+"] and delete tr-id:["+iId+"]"); } else{ console.log("not found main tbl:["+parentDataTbl+"] with tr-id:["+iId+"]"); } } else{ iId = json_resp.resultobj.resulttrace; sendNotice(false, userinfo.$lang['notice_failure']+' ErrCode:'+iId); } }); gta.get(appendSid(targetUrl+'&async=1&fmt=json&targetLineId='+iId)); }, deleteDelay * 1000); actListDiv.innerHTML = '<span style="color:red"> &nbsp; ' + iId + userinfo.$lang['notice_delete_soon'] +deleteDelay+' seconds, [<a href="javascript:window.clearTimeout('+deleteTimerId+');switchArea(\'divActList_' +iId+'\',\'off\');console.log(\'delete is canceled.\'+(new Date())); ">'+userinfo.$lang['func_cancel']+'</a>]...</span>'; hideActListDiv = 0; //if(isconfirm){ //} } else if(fieldv == 'print'){ window.open(sUrl+'&act=print&isoput=1&isheader=0','PrintWindow','scrollbars,toolbar,location=0'); } else{ doActionEx(targetUrl, 'contentarea'); } } else{ //-- } if(actListDiv && hideActListDiv == 1){ actListDiv.style.display = 'none'; } } //-- act list, end, Sat Jun 2 19:19:12 CST 2012 //-- getUrlByTime, Sat Jun 23 11:15:09 CST 2012 function getUrlByTime(baseUrl, timepara, timeop, timeTag){ var url = baseUrl; var myDate = new Date(); var today = myDate.getDay(); var now = myDate.getTime(); var fromd = 0; var tod = 0; var fromD = new Date(fromd); var toD = new Date(tod); var fromDStr = ''; var toDStr = ''; if(timeTag == 'TODAY'){ today = myDate.getDate(); fromd = now; // + (-today)*86400*1000; tod = now; // + (+today)*86400*1000; } else if(timeTag == 'YESTERDAY'){ //today = myDate.getDate(); //now = now - 86400*1000*30; fromd = now + (-1)*86400*1000; tod = now + (-1)*86400*1000; } else if(timeTag == 'THIS_WEEK'){ fromd = now + (-today+1)*86400*1000; tod = now + (7-today)*86400*1000; } else if(timeTag == 'LAST_WEEK'){ now = now - 86400*1000*7; fromd = now + (-today+1)*86400*1000; tod = now + (7-today)*86400*1000; } fromD = new Date(fromd); toD = new Date(tod); fromDStr = fromD.getFullYear()+'-'+(fromD.getMonth()+1)+'-'+fromD.getDate(); toDStr = toD.getFullYear()+'-'+(toD.getMonth()+1)+'-'+toD.getDate(); if(timepara.indexOf('time') > -1 || timepara.indexOf('hour') > -1){ fromDStr += ' 00:00:00'; toDStr += ' 23:59:59'; } if(timeop == 'inrange'){ url += '&pnsk'+timepara+'='+fromDStr+','+toDStr+'&oppnsk'+timepara+'='+timeop+'&pnsm=1'; } else{ console.log('unknown timeop:['+timeop+'].1703021921.'); } //window.alert('now:['+now+'] fromd:['+fromd+'] tod:['+tod+'] url:['+url+']'); doAction(url); } //-- getUrlByTime, Sat Jun 23 11:15:09 CST 2012 //-- old functions function updateTag(tagtype,tagid,str){ try{ if(tagtype=='div' || tagtype=='span'){ document.getElementById(tagid).innerHTML=str; } else{ document.getElementById(tagid).value=str; } } catch(err){ //-- window.alert('update err.'); } } //- function checkAll(){ var boxValue=""; for(var i=0;i<document.all.checkboxid.length;i++){ document.all.checkboxid[i].checked = true; boxValue= boxValue +document.all.checkboxid[i].value+","; } window.clipboardData.setData('text',boxValue); window.alert("Something wrong. 03061743."); } //- function uncheckAll(){ var box1=""; for(var i=0;i<document.all.checkboxid.length;i++){ if(document.all.checkboxid[i].checked == false) { document.all.checkboxid[i].checked = true; box1 = box1+document.all.checkboxid[i].value+","; } else { document.all.checkboxid[i].checked = false; } } window.clipboardData.setData('text',box1); window.alert("Something wrong. 03061744."); } //- function batchDelete(url,checkboxid){ var box=""; for(var i=0;i<document.all.checkboxid.length;i++){ if(document.all.checkboxid[i].checked == true){ box = box+document.all.checkboxid[i].value+","; } } var url1 = url+"&checkboxid="+box; if(box==""){ if(document.all.copyid.value=="??"){ alert("Something wrong. 03061745."); } else{ alert("Something wrong. 03061746."); } } else{ if(document.all.copyid.value=="??"){ if(confirm("Are you sure:"+box)){ doAction(url1); } } else if(document.all.copyid.value=="??"){ if(confirm("Are you sure:"+box)){ doAction(url1); } } } } //- function WdatePicker(){ var evt; if(navigator.userAgent.toLowerCase().indexOf('firefox/') > -1){ // firefox var evtarg = arguments[0]; if(!evtarg){ console.log('firefox has no global event, please invoke as \"WdatePicker(event);\" .201708022320.'); } evt = window.event ? window.event : evtarg; } else{ evt = window.event ? window.event : event; } //var obj = getElementByEvent(event); var obj = getElementByEvent(evt); obj = document.getElementById(obj); //window.alert('obj.id:['+obj.id+'] this.name:['+obj.name+']'); if(obj && obj.id != null){ var newId = (obj.id).replace(new RegExp('-','gm'), '_'); var myDatePicker = new DatePicker('_tmp'+newId,{ inputId: obj.id, separator: '-', className: 'date-picker-wp' }); } else{ sendNotice(userinfo.$lang['notice_datap_invalid']+' Object:['+obj+']'); } } //- var DatePicker = function () { var $ = function (i) {return document.getElementById(i)}, addEvent = function (o, e, f) {o.addEventListener ? o.addEventListener(e, f, false) : o.attachEvent('on'+e, function(){f.call(o)})}, getPos = function (el) { for (var pos = {x:0, y:0}; el; el = el.offsetParent) { pos.x += el.offsetLeft; pos.y += el.offsetTop; } return pos; } var init = function (n, config) { window[n] = this; Date.prototype._fd = function () {var d = new Date(this); d.setDate(1); return d.getDay()}; Date.prototype._fc = function () {var d1 = new Date(this), d2 = new Date(this); d1.setDate(1); d2.setDate(1); d2.setMonth(d2.getMonth()+1); return (d2-d1)/86400000;}; this.n = n; this.config = config; this.D = new Date; this.el = $(config.inputId); this.el.title = this.n+'DatePicker'; this.update(); this.bind(); } init.prototype = { update : function (y, m) { var con = [], week = ['Su','Mo','Tu','We','Th','Fr','Sa'], D = this.D, _this = this; fn = function (a, b) {return '<td title="'+_this.n+'DatePicker" class="noborder hand" onclick="'+_this.n+'.update('+a+')">'+b+'</td>'}, _html = '<table cellpadding=0 cellspacing=2>'; y && D.setYear(D.getFullYear() + y); m && D.setMonth(D.getMonth() + m); var year = D.getFullYear(), month = D.getMonth() + 1, date = D.getDate(); for (var i=0; i<week.length; i++) con.push('<td title="'+this.n+'DatePicker" class="noborder">'+week[i]+'</td>'); for (var i=0; i<D._fd(); i++ ) con.push('<td title="'+this.n+'DatePicker" class="noborder">?</td>'); for (var i=0; i<D._fc(); i++ ) con.push('<td class="hand" onclick="'+this.n+'.fillInput('+year+', '+month+', '+(i+1)+')">'+(i+1)+'</td>'); var toend = con.length%7; if (toend != 0) for (var i=0; i<7-toend; i++) con.push('<td class="noborder">?</td>'); _html += '<tr>'+fn("-1, null", "<<")+fn("null, -1", "<")+'<td title="'+this.n+'DatePicker" colspan=3 class="strong">'+year+'/'+month+'/'+date+'</td>'+fn("null, 1", ">")+fn("1, null", ">>")+'</tr>'; for (var i=0; i<con.length; i++) _html += (i==0 ? '<tr>' : i%7==0 ? '</tr><tr>' : '') + con[i] + (i == con.length-1 ? '</tr>' : ''); !!this.box ? this.box.innerHTML = _html : this.createBox(_html); }, fillInput : function (y, m, d) { var s = this.config.separator || '/'; this.el.value = y + s + m + s + d; this.box.style.display = 'none'; }, show : function () { var s = this.box.style, is = this.mask.style; s['left'] = is['left'] = getPos(this.el).x + 'px'; s['top'] = is['top'] = getPos(this.el).y + this.el.offsetHeight + 'px'; s['display'] = is['display'] = 'block'; is['width'] = this.box.offsetWidth - 2 + 'px'; is['height'] = this.box.offsetHeight - 2 + 'px'; }, hide : function () { this.box.style.display = 'none'; this.mask.style.display = 'none'; }, bind : function () { var _this = this; addEvent(document, 'click', function (e) { e = e || window.event; var t = e.target || e.srcElement; if (t.title != _this.n+'DatePicker') {_this.hide()} else {_this.show()} }) }, createBox : function (html) { var box = this.box = document.createElement('div'), mask = this.mask = document.createElement('iframe'); box.className = this.config.className || 'datepicker'; mask.src = 'javascript:false'; mask.frameBorder = 0; box.style.cssText = 'position:absolute;display:none;z-index:9999'; mask.style.cssText = 'position:absolute;display:none;z-index:9998'; box.title = this.n+'DatePicker'; box.innerHTML = html; document.body.appendChild(box); document.body.appendChild(mask); return box; } } return init; }(); //- getElementByEvent works well with MS Edge && Google Chrome, but uncertain with Mozilla Firefox //- remedy by Xenxin@Ufqi on 23:42 02 August 2017 function getElementByEvent(e){ var targ; var evt = e; if (!evt){ evt = window.event; } if (evt && evt.target){ targ = evt.target;} else if (evt && evt.srcElement){ targ = evt.srcElement }; if (targ && targ.nodeType == 3){ // defeat Safari bug targ = targ.parentNode } //window.alert('targ:['+targ+']'); var tId; if(targ){ tId=targ.id; if(tId == null || tId == '' || tId == undefined){ tId = targ.name; } } else{ console.log('getElementByEvent failed. ev:['+ev+'] e:['+e+'] targ:['+targ+']'); } //window.alert('targ:['+targ+'] id:['+tId+']'); return tId; } //- added on Thu Jul 25 09:13:23 CST 2013 //- by <EMAIL> //- for html editor function getCont(sId){ var obj = document.getElementById(sId); var objtype = ''; var cont = ''; if(obj){ objtype = obj.tagName.toLowerCase(); if(objtype == 'div'){ cont = obj.innerHTML; }else{ cont = obj.value; } } console.log('./comm/ido.js: getCont: sId:['+sId+'] cont:['+cont+']'); return cont; } //- function setCont(sId, sCont){ var obj = document.getElementById(sId); var objtype = ''; if(obj){ objtype = obj.tagName.toLowerCase(); if(objtype == 'div'){ obj.innerHTML = sCont; }else{ obj.value = sCont; } } console.log("setCont: ["+sCont+"]"); //window.alert("setCont once"); return 0; } //- function openEditor(sUrl, sField){ document.getElementById(sField+"_myeditordiv").innerHTML = "<iframe name=\'myeditoriframe\' id=\'myeditoriframe\' src=\'"+sUrl+"\' width=\'680px\' height=\'450px\' border=\'0px\' frameborder=\'0px\'></iframe>"; } //-- select to input & search, Sun Jul 27 21:25:39 CST 2014 function changeBGC(obj, onoff){ if(onoff==1){ obj.style.background='silver'; } else{ obj.style.background='#fff'; } } //- 10:37 2020-07-26 function switchBgc(obj, newBgc){ var currBgc = obj.style.background; if(currBgc != ''){ obj.style.background=''; } else{ obj.style.background=newBgc; } } //- function makeSelect(sId, sCont, sDiv, sSele, iStop){ //-- this would be called after targetObj.onblur setCont(sId, sCont); if(!iStop){ var hidesele = document.getElementById(sSele); if(hidesele != null){ for(var i=0; i < hidesele.length; i++){ //- 复制搜索栏里的select选项到当前 var seleText = hidesele.options[i].text; if(seleText == sCont){ hidesele.selectedIndex = i; break; } } console.log('makeSelect: i:'+i); } } if(!iStop || iStop == '2' || iStop == '4'){ var objDiv = document.getElementById(sDiv) objDiv.style.display='none'; objDiv.innerHTML = ''; } if(iStop == '1' || iStop == '4'){ userinfo.input2Select.makeSelect = 1; } if(iStop == '2' || iStop == '3'){ userinfo.input2Select.makeSelect = 0; } } //- function input2Search(inputx, obj, div3rd, valueoption){ var lastSearchTime = userinfo.lastInput2SearchTime; var lastSearchItem = userinfo.lastInput2SearchItem; var nowTime = (new Date()).getTime(); var balaTime = nowTime - lastSearchTime; var inputVal = inputx.value==null?inputx.innerText:inputx.value; var destobj = 'input2sele_'+obj; //-- where selected content would be copied to var selelistdiv = 'pnsk_'+obj+'_sele_div'; //-- where items would be listed on var obj1737 = ''; if(userinfo.input2Select != null && userinfo.input2Select.obj1737 != null){ obj1737 = userinfo.input2Select.obj1737; } else{ obj1737 = document.getElementById(selelistdiv); if(userinfo.input2Select == null){ userinfo.input2Select = {}; } userinfo.input2Select.obj1737 = obj1737; } if(div3rd != null){ selelistdiv = div3rd; obj1737 = document.getElementById(selelistdiv); destobj = div3rd.replace(new RegExp('_new1425', 'gm'), ''); //-- there are two modes to invoke input2Search, one is on search bar, the other is on each record line. 'div3rd' is the latter tag. } var origdestvalue = ''; if(!userinfo.input2Select){ userinfo.input2Select = {}; } origdestvalue = userinfo.input2Select.originalValue; //-- the value which display as the page loaded. obj1737.style.display = 'block'; if(inputVal.length < 2 || balaTime < 8 || inputVal == lastSearchItem){ // || balaTime < 100 //console.log('input-length:'+inputVal.length+', balaTime:'+balaTime+', lastItem:'+lastSearchItem+', thisItem:'+inputVal+', bypass'); //obj1737.innerHTML = ''; return 0; } else{ console.log('input-length:'+inputVal.length+', balaTime:'+balaTime+', lastItem:'+lastSearchItem+', thisItem:'+inputVal); var iInputX = inputVal.toLowerCase(); var hidesele = ''; if(userinfo.input2Select.hideSele != null){ hidesele = userinfo.input2Select.hideSele; } else{ hidesele = document.getElementById('pnsk_'+obj+''); userinfo.input2Select.hideSele = hidesele; } var odata = ""; selectLength = 0; var dataarr = []; var j = 0; if(userinfo.input2Select.selectLength != null){ selectLength = userinfo.input2Select.selectLength; } else{ selectLength = hidesele.length; userinfo.input2Select.selectLength = selectLength; } //-- cacheOptionList, added by wadelau, Tue Oct 13 08:22:55 CST 2015 var cacheOptionList = document.getElementById('pnsk_'+obj+'_optionlist'); //- see lazyLoad and class/gtbl.class //console.log(cacheOptionList.value); if(cacheOptionList != null && cacheOptionList != ''){ console.log("use high-speed cacheOptionList...."); var col = JSON.parse(cacheOptionList.value); for(var opti in col){ var seleText = col[opti]; var seleVal = opti; //console.log("text:["+seleText+"] val:["+seleVal+"]"); if(seleText.toLowerCase().indexOf(iInputX) > -1){ //-- if(valueoption == null || valueoption == ''){ dataarr[j++] = '<span onmouseover=parent.changeBGC(this,1); onmouseout=parent.changeBGC(this,0);'+ +' onclick=parent.makeSelect(\''+destobj+'\',this.innerText,\''+selelistdiv+'\',\'pnsk_' +obj+'\');>'+seleText+'-('+seleVal+')</span>'; } else if(valueoption == 'NEED_OPTION_VALUE'){ //-- div3rd mode dataarr[j++] = '<span onmouseover=parent.changeBGC(this,1);parent.makeSelect(\''+destobj+'\',\'' +seleVal+'\',\''+selelistdiv+'\',\'pnsk_'+obj+'\',1); onmouseout=parent.changeBGC(this,0);'+ +'userinfo.input2Select.makeSelect=0; onclick=parent.makeSelect(\''+destobj+'\',this.innerText,\'' +selelistdiv+'\',\'pnsk_'+obj+'\',4);>'+seleText+'-('+seleVal+')</span>'; } if(j>30){ dataarr[j++] = userinfo.$lang['more']+'....'; break; } } } } else if(hidesele != null){ for(var i=0; i < selectLength; i++){ //- 复制搜索栏里的select选项到当前 var seleText = hidesele.options[i].text; var seleVal = hidesele.options[i].value; if(seleText.toLowerCase().indexOf(iInputX) > -1){ //-- if(valueoption == null || valueoption == ''){ dataarr[j++] = '<span onmouseover=parent.changeBGC(this,1); onmouseout=parent.changeBGC(this,0); onclick=parent.makeSelect(\''+destobj+'\',this.innerText,\''+selelistdiv+'\',\'pnsk_'+obj+'\');>'+seleText+'</span>'; } else if(valueoption == 'NEED_OPTION_VALUE'){ //-- div3rd mode dataarr[j++] = '<span onmouseover=parent.changeBGC(this,1);parent.makeSelect(\''+destobj+'\',\''+seleVal+'\',\''+selelistdiv+'\',\'pnsk_'+obj+'\',1); onmouseout=parent.changeBGC(this,0);userinfo.input2Select.makeSelect=0; onclick=parent.makeSelect(\''+destobj+'\',this.innerText,\''+selelistdiv+'\',\'pnsk_'+obj+'\',4);>'+seleText+'</span>'; } if(j>30){ dataarr[j++] = userinfo.$lang['more']+'....'; break; } } } } if(dataarr.length == 0){ j=0; //dataarr[j] = "......Not Found...."; dataarr[j] = "......Searching...."; } if(true){ //-- close action j++; dataarr[j] = '<span onmouseover="parent.changeBGC(this,1);parent.makeSelect(\''+destobj+'\',\''+origdestvalue+'\',\''+selelistdiv+'\',\'pnsk_'+obj+'\',3);" onmouseout="parent.changeBGC(this,0);" onclick="javascript:userinfo.input2Select.makeSelect=0;parent.makeSelect(\''+destobj+'\',\''+origdestvalue+'\',\''+selelistdiv+'\',\'pnsk_'+obj+'\',2);">'+userinfo.$lang['func_cancel']+'</span>'; } odata = dataarr.join('<br/>'); //console.log(odata); obj1737.innerHTML = odata; userinfo.lastInput2SearchTime = (new Date()).getTime(); userinfo.lastInput2SearchItem = inputVal; userinfo.input2Select.makeSelect = 0; //-- clear makeSelect } } //- function showActList(nId, isOn, sUrl, dataId){ var divId = 'divActList_'+nId; //console.log((new Date())+": divId:["+divId+"]"); var divObj = document.getElementById(divId); var dispVal = divObj.style.display; if(isOn == 1){ dispVal = 'block'; }else{ dispVal = 'none';} divObj.style.display = dispVal; divObj.onmouseover = function(){ this.style.display='block'; }; divObj.onmouseout = function(){ this.style.display='none'; }; var sCont = '<p>'; var targetAreaId = '#contentarea_outer'; sCont += '&nbsp; &nbsp;&nbsp;<a href="'+targetAreaId+'" onclick="javascript:doActSelect(\'\', \''+sUrl+'\', \'' +nId+'\', \'view\');"> - '+userinfo.$lang['func_view']+'</a>&nbsp; &nbsp;&nbsp;'; sCont += '<br/>&nbsp; &nbsp;&nbsp;<a href="'+targetAreaId+'" onclick="javascript:doActSelect(\'\', \''+sUrl+'\', \'' +nId+'\', \'modify\');"> - '+userinfo.$lang['func_edit']+'</a>&nbsp; &nbsp;&nbsp;'; sCont += '<br/>&nbsp; &nbsp;&nbsp;<a href="'+targetAreaId+'" onclick="javascript:doActSelect(\'\', \''+sUrl+'\', \'' +nId+'\', \'print\');"> - '+userinfo.$lang['func_print']+'</a>&nbsp; &nbsp;&nbsp;'; sCont += '<br/>&nbsp; &nbsp;&nbsp;<a href="'+targetAreaId+'" onclick="javascript:doActSelect(\'\', \''+sUrl+'\', \'' +nId+'\', \'list-dodelete\');"> - '+userinfo.$lang['func_delete']+'</a>&nbsp; &nbsp;&nbsp;'; sCont += '<br/>&nbsp; &nbsp;&nbsp;<a href="'+targetAreaId+'" onclick="javascript:doActSelect(\'\', \''+sUrl+'\', \'' +nId+'\', \'addbycopy\');"> - '+userinfo.$lang['func_copy']+'</a>&nbsp; &nbsp;&nbsp;'; //- add more options on popup menu, Fri Apr 26 10:58:24 HKT 2019 if(typeof userinfo.actListOption != 'undefined'){ var actArr = userinfo.actListOption; var tmpName, tmpUrl; var tmpRecord = {}; //- userinfo.dataList init in ido.php and load data in jdo.php for(var ri=0; ri<userinfo.dataList.length; ri++){ if(userinfo.dataList[ri].id==dataId){ tmpRecord = userinfo.dataList[ri]; //console.log("dataList:"+tmpRecord+" id:"+tmpRecord['id']); break; } } for(var ai=0; ai<actArr.length; ai++){ tmpName = actArr[ai].actName; tmpUrl = actArr[ai].actUrl; if(tmpUrl != null && tmpUrl != ''){ //console.log("comm/ido: tmpUrl:"+tmpUrl); var tmpk = ''; var fieldRe = /THIS_([a-zA-Z]+)/gm; var match; var tmpUrl2 = tmpUrl; while(match = fieldRe.exec(tmpUrl)){ //console.log(match); tmpk = match[1]; if(tmpk=='ID'){ tmpk = 'id'; } // due to 'field' 'fieldx' 'fieldxxxx' tmpUrl2 = tmpUrl2.replace((new RegExp(match[0]+"([&|'|$]+)", "gm")), tmpRecord[tmpk]+'$1'); } tmpUrl = tmpUrl2; } sCont += '<br/>&nbsp; &nbsp;&nbsp;<a href="'+targetAreaId+'" onclick="javascript:doActSelect(\'\', \''+tmpUrl+'\', \'' +nId+'\', \'ActOption\');"> - '+tmpName+'</a>&nbsp; &nbsp;&nbsp;'; } } sCont += '</p>'; divObj.innerHTML = sCont; } //-- lazy load long list, Wed Oct 14 09:08:51 CST 2015 function lazyLoad(myObj, myType, myUrl){ window.console.log("lazyload is starting.... myurl:["+myUrl+"] myobj:["+myObj+"]"); if(true){ //document.onreadystatechange = function(){ //window.onload = function(){ window.setTimeout(function(){ if(document.readyState == 'complete' || document.readyState == 'interactive'){ sendNotice(true, userinfo.$lang['lazyloading']+'.... myObj:['+myObj+']'); var gta = new GTAjax(); gta.set('targetarea', 'addareaextradiv'); gta.set("callback", function(){ //window.alert("getresult:["+this+"]"); var s = this; var resultList = JSON.parse(s); var fieldName = resultList.thefield; var dispField = resultList.dispfield; //var mySele = document.getElementById(resultList.thefield); console.log("thefield:["+resultList.thefield+"] "+(new Date())); var optionList = {}; for(var i=0;i<resultList.result_list.length;i++){ var aresult = resultList.result_list[i]; //mySele.options[i] = new Option(aresult.sitename+'('+aresult.id+')',aresult.id, true,issel=false); optionList[aresult.id] = eval('aresult.'+dispField); } var myOptionList = document.getElementById('pnsk_'+fieldName+'_optionlist'); myOptionList.value = JSON.stringify(optionList); console.log("thefield:["+resultList.thefield+"] completed......"+(new Date())); //console.log(JSON.stringify(myOptionList.value)); sendNotice(true, userinfo.$lang['notice_lazyload_success']+'.... myObj:['+myObj+']'); }); gta.get(appendSid(myUrl)); } else{ sendNotice(false, userinfo.$lang['notice_lazyloading']+'....'); } }, 3*1000); } } //- copy and return, //- <EMAIL>, Sat Feb 13 10:52:35 CST 2016 function copyAndReturn(theField){ var iId = parent.userinfo.targetId; var theAct = parent.userinfo.act; console.log('copyAndReturn: iId:['+iId+'] theAct:['+theAct+']'); //if(iId != ''){ //- ? if( true ){ var linkobj = document.getElementById(theField); if(linkobj != null){ document.getElementById(theField).value = document.getElementById('linktblframe').contentWindow.sendLinkInfo('', 'r', theField); } } //document.getElementById('extrainput_'+theAct+'_'+theField).style.display='none'; //document.getElementById('extendicon_'+iId+'_'+theField).src='./img/plus.gif'; } //- show pivot list //- Xenxin@Ufqi, 18:23 05 December 2016 userinfo.showList = {}; //- holder of current active showing div function showPivotList(nId, isOn, sUrl, sName){ var divPrefix = 'divPivotList_'; var divId = divPrefix + nId; if(userinfo.showList){ var oldnId = userinfo.showList.divPrefix; if(oldnId && oldnId != nId){ //console.log("found oldnId:["+oldnId+"], try to switch off."); showPivotList(oldnId, 0, sUrl, sName); } } //console.log((new Date())+": divId:["+divId+"]"); var divObj = document.getElementById(divId); var dispVal = divObj.style.display; if(isOn == 1){ dispVal = 'block'; }else{ dispVal = 'none';} divObj.style.display = dispVal; divObj.onmouseover = function(){ this.style.display='block'; }; divObj.onmouseout = function(){ this.style.display='none'; }; var sCont = '<p> &nbsp; <b style="color:red;">'+nId+'. '+sName+'</b>: '; var groupCol = userinfo.$lang['func_pivot_group_col']; var valueCol = userinfo.$lang['func_pivot_value_col']; var orderCol = userinfo.$lang['func_pivot_order_col']; var opList = {'addgroupby':groupCol, 'addgroupbyymd':groupCol+'Ymd', 'addgroupbyseg':groupCol+'Seg', 'addgroupbyother':groupCol+'Other(?)', '__SEPRTa':1, 'addvaluebysum':valueCol+'Sum', 'addvaluebycount':valueCol+'Count', 'addvaluebycountdistinct':valueCol+'CountUniq', 'addvaluebyavg':valueCol+'Average', 'addvaluebymiddle':valueCol+'Median(?)', 'addvaluebymax':valueCol+'Max', 'addvaluebymin':valueCol+'Min', 'addvaluebystddev_pop':valueCol+'Stddev_Pop', 'addvaluebystddev_samp':valueCol+'Stddev_Samp', 'addvaluebyother':valueCol+'Other(?)', '__SEPRTb':1, 'addorderby':orderCol}; var opi = 1; for(var op in opList){ if(op.indexOf('__SEPRT') > -1){ sCont += "<br/>"; } else{ sCont += '&nbsp; &nbsp;'+nId+'.'+(opi++)+'&nbsp;<a href="javascript:void(0);" onclick="javascript:doPivotSelect(\'' +sUrl+'\', \'' +nId+'\', \''+op+'\', 1, \''+sName+'\');">+'+opList[op]+'</a>&nbsp; &nbsp;&nbsp;'; } } sCont += '</p>'; divObj.innerHTML = sCont; if(!userinfo.showList){ userinfo.showList = {}; } userinfo.showList.divPrefix = nId; } //- select/unselect pivot field //- Xenxin@Ufqi, 18:29 05 December 2016 function doPivotSelect(sField, iId, sOp, isOn, sName){ var rtn = true; var spanObj = _g('span_groupby'); var fieldObj = _g('groupby'); var fieldValue = fieldObj.value; if(sOp == 'addgroupby' || sOp == 'addgroupbyymd' || sOp == 'addgroupbyother' || sOp.indexOf('addgroupbyseg') > -1){ if(isOn == 1){ if(sOp == 'addgroupbyseg'){ var segPoints = window.prompt(userinfo.$lang['input']+sName+'/'+sField + userinfo.$lang['func_pivot_seg_range'], '1-4'); if(segPoints.indexOf('-') > 0){ sOp += segPoints.replace(' ', ''); } console.log("addgroupbyseg: "+sField+" +"+segPoints); } } spanObj = _g('span_groupby'); fieldObj = _g('groupby'); } else if(sOp == 'addorderby'){ spanObj = _g('span_orderby'); fieldObj = _g('orderby'); } else{ spanObj = _g('span_calculateby'); fieldObj = _g('calculateby'); } fieldValue = fieldObj.value; //console.log("span:["+spanObj.innerHTML+"] field:["+fieldValue+"]"); var tmps = sName+'('+sField+') '+sOp+' <a href="javascript:void(0);" onclick="javascript:doPivotSelect(\'' +sField+'\', \''+iId+'\', \''+sOp+'\', 0, \''+sName+'\');" title="'+userinfo.$lang['func_delete']+'"> X(Rm) </a>' +' <a href="javascript:void(0);" onclick="javascript:doPivotSelect(\'' +sField+'\', \''+iId+'\', \'addorderby\', 1, \''+sName+'\');" title="'+userinfo.$lang['func_orderby']+'"> ↿⇂(Od) </a><br>'; if(isOn == 1){ if(fieldValue.indexOf(sField+sOp) == -1){ spanObj.innerHTML += tmps; fieldObj.value += ','+sField+'::'+sOp; } } else{ fieldValue = fieldValue.replace(','+sField+'::'+sOp, ''); fieldObj.value = fieldValue; var spanValue = spanObj.innerHTML; if(fieldValue == '' && spanValue != ''){ spanValue = ''; //- in case of non-ascii replace failed, Fri Jun 18 12:38:46 CST 2021 } else{ console.log("doPivotSelect: spanValue:["+spanValue+"] tmps:["+tmps+"] indexOf:"+spanValue.indexOf(tmps)); spanValue = spanValue.replace(tmps, ''); } //spanValue = spanValue.replace(tmps, ''); spanObj.innerHTML = spanValue; } return rtn; } //- filter something of user input and replace with matched //- work with regexp by Xenxin@Ufqi //- 19:14 16 December 2016 /* e.g. <jsaction>onblur::filterReplace('pnsk_THISNAME', '[^0-9]*([0-9]+)[^0-9]*');|onkeyup::filterReplace('pnsk_THISNAME', '[^0-9]*([0-9]+)[^0-9]*');|onpaste::filterReplace('pnsk_THISNAME', '[^0-9]*([0-9]+)[^0-9]*');|</jsaction> */ userinfo.filterReplaceI = {}; function filterReplace(myField, myRegx){ var rtn = 0; var realdo = false; var frpk = myField + myRegx; if(!userinfo.filterReplaceI){ userinfo.filterReplaceI = {frpk:1}; window.setTimeout('filterReplace(\''+myField+'\', \''+myRegx+'\')', 10); //console.log("set a delay exec. 1612161417."); } else{ var sregi = userinfo.filterReplaceI.frpk; if(!sregi){ userinfo.filterReplaceI.frpk = 1; window.setTimeout('filterReplace(\''+myField+'\', \''+myRegx+'\')', 10); //console.log("set a delay exec. 1612161407."); } else if(sregi == 1){ userinfo.filterReplaceI.frpk = 0; realdo = true; } } if(realdo){ var obj = _g(myField); if(obj){ var isVal = true; var val = null; if(obj.value){ val = obj.value; } else if(obj.innerText){ val = obj.innerText; isVal = false; } else{ console.log("obj.value failed. 16121138."); } var regx = new RegExp(myRegx, 'gm'); // number: "[^0-9]*([0-9]+)[^0-9]*" // string: ? var mtch = regx.exec(val); if(mtch){ //console.log("0:"+mtch[0]); // whole matched string console.log("1:"+mtch[1]); // first group val = mtch[1]; } else{ console.log("mtch failed."); val = ''; } if(isVal){ obj.value = val; } else{ obj.innerText = val; } } else{ console.log("obj failed. 16121151."); } } return rtn; } //- append sid //- Tue, 7 Mar 2017 21:31:36 +0800 function appendSid(urlx){ if(typeof urlx != 'string'){ return urlx; } else if(urlx.indexOf('.') == -1 && urlx.indexOf('?') == -1){ //console.log('ido.js: invalid url:['+urlx+']'); return urlx; } var sidstr = 'sid='+userinfo.sid; if(urlx.indexOf('?sid=') > -1 || urlx.indexOf('&sid=') > -1){ //- goood } else{ if(urlx.indexOf('http') == 0){ // outside } else{ var hasFilled = false; var fileArr = ['ido.php', 'jdo.php', './', 'index.php']; for(var i=0; i<fileArr.length; i++){ var f = fileArr[i]; if(urlx.indexOf(f+'?') > -1){ urlx = urlx.replace(f+'?', f+'?'+sidstr+'&'); hasFilled = true; break; } else if(urlx.indexOf(f) > -1 && f != './'){ urlx = urlx.replace(f, f+'?'+sidstr); hasFilled = true; break; } } if(!hasFilled){ if(urlx.indexOf('?') > -1){ urlx += '&'+sidstr; } else{ urlx += '?'+sidstr; } } } } return urlx; } //- user agent detection //- 19:00 03 August 2017 //- @todo userinfo.userAgent = {}; (function(container){ var env = container==null ? window : container; var ua = navigator.userAgent.toLowerCase(); env.isChrome = false; env.isIE = false; env.isEdge = false; env.isFirefox = false; env.isOpera = false; if(ua.indexOf('chrome/') > -1 || ua.indexOf('chromium/') > -1){ env.isChrome = true; } else if(ua.indexOf('firefox/') > -1){ env.isFirefox = true; } else if(ua.indexOf('edge/') > -1){ env.isEdge = true; } else if(ua.indexOf('msie ') > -1){ env.isIE = true; } else if(ua.indexOf('opr/') > -1 || ua.indexOf('opera/') > -1){ env.isOpera = true; } else{ console.log('Unknown ua:['+ua+']'); } var isLog = false; if(isLog){ Object.keys(env).forEach(function(k){ console.log('ua k:'+k+', v:'+env[k]); }); } return container = env; })(userinfo.userAgent); //- //- pick up and make a reqt //- Fri Sep 21 19:59:08 CST 2018 //- see class/pagenavi //userinfo.PickUpList = {}; if(typeof userinfo.PickUpList == 'undefined'){ userinfo.PickUpList = {}; } function fillPickUpReqt(myUrl, field, fieldv, opStr, linkObj){ console.log("url:"+myUrl+", field:"+field+" link-text:"+linkObj.text); var linkText = ''; var base62xTag = 'b62x.'; //var pickUpFromTag = userinfo.pickUpFromTag; var pickUpFromTag = userinfo.pickUpFromTag ? userinfo.pickUpFromTag : '&frompickup=1'; if(linkObj){ linkText = linkObj.text; if(linkText.substring(0, 1) == '+'){ linkText = '-' + linkText.substring(1); linkObj.style.color = '#ffffff'; linkObj.style.backgroundColor = '#1730FD'; } else{ linkText = '+' + linkText.substring(1); linkObj.style.color = ''; linkObj.style.backgroundColor = ''; } linkObj.text = linkText; } var fieldObj = {}; if(!userinfo.PickUpList){ userinfo.PickUpList = {}; } if(userinfo.PickUpList.field){ fieldObj = userinfo.PickUpList.field; } if(fieldObj[fieldv]){ //- have delete fieldObj[fieldv]; } else{ fieldObj[fieldv] = opStr; //- why? } userinfo.PickUpList.field = fieldObj; var latestUrl = myUrl; if(userinfo.PickUpList.latestUrl){ latestUrl = userinfo.PickUpList.latestUrl; } myUrl = latestUrl; console.log("latesturl:"+myUrl+", field:"+field+" fieldobj:"+JSON.stringify(userinfo.PickUpList.field)); var hasReqK = false; var hasReqKop = false; var hasReqV = false; var urlParts = myUrl.split('&'); if(opStr == 'inlist' || opStr == 'containslist' || opStr == 'inrangelist'){ var urlSize = urlParts.length; var paramParts = []; var pk = ''; var pv = ''; var tmpV = ''; var emptyList = {}; var newPList = []; //fieldv = fieldv.toLowerCase(); //- why? var isString = false; if(opStr == 'containslist'){ isString = true; } for(var i=0; i<urlSize; i++){ tmpV = urlParts[i]; emptyP = false; paramParts = urlParts[i].split('='); if(paramParts.length > 1){ pk = paramParts[0]; pv = paramParts[1]; if(pk == "pnsk"+field){ //pv = pv.toLowerCase(); //- why? if(true && isString){ if(pv.indexOf(',') > -1){ var tmpArr = pv.split(','); for(var tmpi=0; tmpi<tmpArr.length; tmpi++){ if(tmpArr[tmpi].indexOf(base62xTag) > -1){ } else{ tmpArr[tmpi] = base62xTag + Base62x.encode(tmpArr[tmpi]); } } pv = tmpArr.join(','); } else{ if(pv.indexOf(base62xTag) > -1){ //- okay } else{ pv = base62xTag + Base62x.encode(pv); } } } if(pv.indexOf(',') > -1){ if(pv.indexOf(','+fieldv) > -1){ pv = pv.replace(','+fieldv, ''); hasReqV = true; } else if(pv.indexOf(fieldv+',') > -1){ pv = pv.replace(fieldv+',', ''); hasReqV = true; } else if(pv == fieldv){ pv = ''; hasReqV = true; emptyList[pk] = true; } else{ pv += ','+fieldv; } } else if(pv == fieldv){ pv = ''; hasReqV = true; emptyList[pk] = true; } else{ pv += ','+fieldv; } hasReqK = true; } else if(pk == "oppnsk"+field){ if(emptyList['pnsk'+field]){ emptyList[pk] = true; } else{ pv = opStr; } hasReqKop = true; } } if(!emptyList[pk]){ tmpV = pk + '=' + pv; urlParts[i] = tmpV; newPList[i] = tmpV; } else{ //urlParts.splice(i, 1); console.log("\ti:"+i+" updt pk:"+pk+" pv:"+pv); } } myUrl = newPList.join('&'); if(!hasReqK){ myUrl += '&pnsk'+field+'='+fieldv; } if(!hasReqKop){ myUrl += '&oppnsk'+field+'='+opStr; } console.log("newurl:"+myUrl+' ->'+opStr); userinfo.PickUpList.latestUrl = myUrl; //- myUrl = myUrl.replace('&act=', '&dummyact='); doActionEx(myUrl+'&act=list&pnsm=1'+pickUpFromTag, 'actarea'); } else if(opStr == 'moreoption'){ console.log("newurl:"+myUrl+" ->"+opStr); doActionEx(myUrl+'&act=pickup&pnsm=1&pickupfieldcount='+fieldv, 'contentarea'); } else if(opStr == 'filterrollback'){ myUrl = myUrl.replace('&pnsk'+field, '&dummy'); myUrl = myUrl.replace('oppnsk'+field, '&dummy'); console.log("newurl:"+myUrl+" ->"+opStr); userinfo.PickUpList.latestUrl = myUrl; doActionEx(myUrl+'&act=pickup&pnsm=1&pickupfieldcount='+fieldv, 'contentarea'); } else{ console.log("Unknown opstr:["+opStr+"]."); } } //- fill reset value //- Thu Apr 12 10:36:27 CST 2018, tdid=537 function fillReset(fieldId, iType, myVal){ var f = document.getElementById(fieldId); if(typeof f != 'undefined'){ var oldv = f.value; if(true){ if(iType == null || iType == ''){ iType = 'input'; } if(iType == 'input'){ f.value = myVal; } else if(iType == 'select'){ parent.setSelectIndex(fieldId, myVal); } console.log(' myVal:['+myVal+'] fillReset succ.'); } else{ console.log('oldv not empty. filReset stopped.'); } } else{ console.log('fieldId:['+fieldId+'] invalid. fillReset failed.'); } } //- if(typeof userinfo.urlParams == 'undefined'){ userinfo.urlParams = {}; } function getUrlParams(tmpUrl){ var vars = {}; if(typeof tmpUrl == 'undefined' || tmpUrl == '' || tmpUrl == null){ tmpUrl = window.location.href; } var parts = tmpUrl.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m, key, value) { vars[key] = value; }); //console.log('vars:'+JSON.stringify(vars)); return vars; }; userinfo.urlParams = getUrlParams(); //- for triger by registerAct from child page, Tue Jul 16 17:28:40 HKT 2019 function addEvent(sId, sAct, sFunc){ var timerId0716=0; var tmpSelect=document.getElementById(sId); if(tmpSelect){ tmpSelect.addEventListener(sAct, sFunc); //console.log('evnt added:'+tmpSelect.sAct); window.clearTimeout(timerId0716); } else{ //console.log('tmpSelect:['+tmpSelect+'] is empty? try later..'); //timerId0716=window.setTimeout(addEvent(sId, sAct, sFunc), 15*1000); //- anti dead lock? timerId0716=window.setTimeout(function(){ addEvent(sId, sAct, sFunc); }, 10*1000); } } //- for select onchange in list view, Tue Jul 16 17:29:15 HKT 2019 function searchBySelect(){ var url = userinfo.searchBySelectUrl; searchBy(url); } //- image load async //- Mon Sep 2 20:55:57 HKT 2019 function imageLoadAsync(imgId, imgRealPath){ var image = _g(imgId); if(image && image.src == imgRealPath){ console.log((new Date())+" imgid:"+imgId+" path:"+imgRealPath+" img already loaded!"); } else{ var realImage = new Image(); //console.log("imgid:"+imgId+" path:"+imgRealPath+" imgobj:"+realImage); realImage.onload = function(){ var baseSize = 118; if(image){ image.src = this.src; image.onload = null; //- stop further refer to imageLoadAsync if(image.width > baseSize){ image.style.width = baseSize+'px'; } else if(image.height > baseSize){ image.style.height = baseSize+'px'; } //console.log((new Date())+"image load async succ...src:"+image.src); realImage = null; } else{ console.log((new Date())+" image is not ready...."); } }; //- anti empty src, Thu Mar 19 10:21:21 CST 2020 if(imgRealPath == ''){ imgRealPath = 'data:image/jpeg;base64,MA=='; } //window.setTimeout(function(){ realImage.src = imgRealPath; }, 1*1000); realImage.src = imgRealPath; } } <file_sep>/class/insitesearch.v1.class.php <?php /* In-site Search class * v0.1, * <EMAIL> * Tue May 29 19:58:37 CST 2018 */ if(!defined('__ROOT__')){ define('__ROOT__', dirname(dirname(__FILE__))); } require_once(__ROOT__.'/inc/webapp.class.php'); class InSiteSearch extends WebApp{ var $ver = 0.01; const SID = 'sid'; # public function __construct($args=null){ $this->setTbl(GConf::get('tblpre').'insitesearchtbl'); //- init parent parent::__construct($args); } # public function __destruct(){ } # # public function saveInfo($list, $itbl, $idb){ $rtn = 0; $isep = "\t\t"; $targetList = array(); $md5List = '"0"'; foreach($list as $k=>$v){ foreach($v as $k2=>$v2){ $ifield = $k2; $v2 = trim($v2); if($v2 == ''){ #debug($msg="$k: [$itbl] - [$k2] - [$v2] -> empty, skip\n"); #$rtn .= $msg; continue; } else if(is_numeric($v2)){ #debug($msg="$k: [$itbl] - [$k2] - [$v2] -> number, skip\n"); #$rtn .= $msg; continue; } else if(startsWith($v2, 'http')){ continue; } #debug($msg=($counti++)."-$k: [$itbl] - [$k2] - [$v2] validated.\n"); #$rtn .= $msg; $tmpVal = $idb.$isep.$itbl.$isep.$ifield.$isep.$v2; $imd5 = md5($tmpVal); $md5List .= ',"'.$imd5.'"'; $targetList[$imd5] = $tmpVal; } } # remove old $hm = $this->execBy($sql='select id, imd5 from '.$this->getTbl() ." where imd5 in ($md5List)", null, null); # too long key? $withCache=array('key'=>'read-data-2-'.$md5List) #debug("read old sql:$sql"); if($hm[0]){ $hm = $hm[1]; foreach($hm as $k=>$v){ #debug("try to unset v:".serialize($v)); unset($targetList[$v['imd5']]); } } else{ debug("$idb $itbl read old return empty."); } # save new debug("reach targetList:".serialize($targetList)); #print_r($targetList); foreach($targetList as $k=>$v){ $imd5 = $k; $tmpArr = explode($isep, $v); $idb = $tmpArr[0]; $itbl = $tmpArr[1]; $ifield = $tmpArr[2]; $ival = str_replace('\'', '\\\'', $tmpArr[3]); $hm = $this->execBy($sql="insert into ".$this->getTbl() ." set idb='$idb', itbl='$itbl'," ." ifield='$ifield', ivalue='$ival', imd5='$imd5'", null); debug("imd5:$imd5, insert sql:$sql\n"); if($hm[0]){ $rtn .= $v . " save succ\n"; } else{ $rtn .= $v . " save fail\n"; } } return $rtn; } # # } ?> <file_sep>/extra/sendmail.php <?php # invoked by trigger settings in xml # e.g. <trigger>ALL::extraact::extra/sendmail.php::Offer入口调整修改id=THIS_ID</trigger> if(true){ $args = explode('::', $args); # sendMail($to='<EMAIL>,<EMAIL>,'.$user->getEmail(), $title=$args[0], $bodyMsg=$args[0].'@'.date('Y-m-d-H:i:s', time()) .' by '.$user->getEmail().'. sent from '.$_CONFIG['agentname'].'.' .' Url: '.$thisUrl, $from='', $vialocal=1); debug($bodyMsg); } ?> <file_sep>/extra/xtree.php <?php /* * tree data management module * <EMAIL> on Sat May 8 10:44:26 CST 2021 * params: tbl: target table for tree-like data icode: id or parentid in the table iname: item name in the table pnskFieldName: field name in the table as condtion parentField: the field indicating parent id parentcode: parentid imode: read or writeback targetfield: field name to be writted back * * <field name="belongto"> <chnname>上级</chnname> <extrainput>extra/xtree.php?tbl=THIS_TBL&amp;icode=id&amp;iname=iname&amp;pnskitype=1,2&amp;oppnskitype=inlist&amp;parentcode=THIS_belongto&amp;imode=read&amp;targetfield=belongto</extrainput> </field> */ #$isoput = false; $isheader = 0; $_REQUEST['isheader'] = $isheader; #$out_header = $isheader; require("../comm/header.inc.php"); include("../comm/tblconf.php"); include_once($appdir."/class/xtree.class.php"); include_once($appdir."/class/pagenavi.class.php"); if(!isset($xTree)){ $xTree = new XTree($tbl); } $inframe = Wht::get($_REQUEST, 'inframe'); if($inframe == ''){ # re open in an iframe window $myurl = $rtvdir."/extra/xtree.php?inframe=1&".$_SERVER['QUERY_STRING'].'&'.SID.'='.$sid; $out .= "<iframe id=\"linktblframe\" name=\"linktblframe\" width=\"100%\" height=\"100%\" src=\"" .$myurl."&isheader=0\" frameborder=\"0\"></iframe>"; } else{ # main actions $rootId = 1; $parentCode = Wht::get($_REQUEST, 'parentcode'); if(inString('-', $parentCode)){ //- 0100-止疼药2级 $tmpArr = explode('-', $parentCode); $parentCode = $tmpArr[0]; } else if(inString('THIS_', $parentCode)){ //- THIS_belongto $parentCode = $rootId; } else{ $parentCode = $parentCode=='' ? $rootId : $parentCode; //- 1 as root $parentCode = $parentCode=='0' ? $rootId : $parentCode; //- 1 as root } $xTree->set('parentCode', $parentCode); $targetField = Wht::get($_REQUEST, 'targetfield'); $parentField = Wht::get($_REQUEST, 'parentfield'); #$sqlCondi = "1=1 order by $icode asc"; //- why unconditional? if(!isset($_REQUEST['pnsm'])){ $_REQUEST['pnsm'] = 1; //- default search mod: and } $myNavi = new PageNavi($args=array('lang'=>$lang)); $sqlCondi = $myNavi->getCondition($gtbl, $user); $hmVars = $gtbl->hmf; foreach($hmVars as $k=>$v){ $xTree->set($k, $v); //- override? } $sqlCondi .= " and ($parentField=$parentCode)"; #$sqlCondi .= " order by $icode asc"; //- why unconditional? $xTree->set("orderby", "convert($iname using gbk), $icode asc"); $hm = $xTree->getBy("$icode, $iname", "$sqlCondi", $withCache=array('key'=>"xtree-$tbl-$sqlCondi")); if($hm[0]){ $hm = $hm[1]; } else{ $hm = array(0=>array("$icode"=>$rootId, "$iname"=>'Root/根')); } # trace up to root. $hmParent = array(); $tmpId = $parentCode; $lastTmpId = 0; while($tmpId >= $rootId){ $tmpHm = $xTree->getBy("$icode, $iname, $parentField", "$icode=$tmpId", $withCache=array('key'=>"xtree-3-$tbl-$tmpId")); #debug("extra/xtree: tmpHm:".serialize($tmpHm)); if($tmpHm[0]){ $tmpHm = $tmpHm[1][0]; $hmParent[] = $tmpHm; $tmpId = $tmpHm[$parentField]; } if($tmpId == $lastTmpId){ $tmpId = 0; } else{ $lastTmpId = $tmpId; //- anti dead loop. } } $hmParent = array_reverse($hmParent); #debug("extra/xtree: ".serialize($hm)." sqlCondi:$sqlCondi hmParent:".serialize($hmParent)); # disp $myUrl = $thisUrl; $myUrl = preg_replace('/&parentcode=[0-9]+/', '', $myUrl); $out .= "<style>.selectedColor{ color:red; }</style><p>🍁"; $lastParent = $rootId; foreach($hmParent as $k=>$v){ $out .= "<span".(($v['id']==$parentCode)?" class=\"selectedColor\"":"").">".$v['iname']."(".$v['id'].")<a href='".$myUrl."&parentcode=".$lastParent."'><sup>X</sup></a></span> > "; $lastParent = $v['id']; } $out .= "<br/>"; foreach($hm as $k=>$v){ $out .= "<span".(($v['id']==$parentCode)?" class=\"selectedColor\"":"")."><a href='".$myUrl."&parentcode=".$v['id']."'>".$v['iname']."(".$v['id'].")</a>" ." <a href='javascript:void(0);' onclick=\"javascript:parent.sendLinkInfo('".$v['id']."', 'w', current_link_field); " ." parent.copyAndReturn(current_link_field); this.style.backgroundColor='yellow';\" title='" .$lang->get('choose')."'><input name='chkbox_".$v['id']."' type='checkbox'/></a> </span> . "; } $out .= "</p><p>".$lang->get("xtree-no-data")."</p>"; $imode = Wht::get($_REQUEST, "imode"); if($imode == 'read' && $targetField != $icode){ $icode = $targetField; } $out .= " <script type=\"text/javascript\"> var current_link_field='".$icode ."'; var tmpTimer0859=window.setTimeout(function(){parent.sendLinkInfo('".$parentCode."','w', current_link_field);}, 1*1000);</script> "; # positioning to selected, 17:42 6/11/2020 if($parentCode != ''){ $out .= '<script>if(true){ var tmpReloadTimer=window.setTimeout(function(){ var tmpObj=document.getElementById("'.$parentCode.'"); if(tmpObj){tmpObj.scrollIntoView(); parent.scrollTo(0,10);}}, 1*1000);};</script>'; } $out .='</script>'; } require("../comm/footer.inc.php"); ?> <file_sep>/extra/fdrename.php <?php # # file and name rename and its subdirectories # <EMAIL>, Mon Nov 12 16:14:56 CST 2018 # /* require("../comm/header.inc.php"); $gtbl = new GTbl($tbl, array(), $elementsep); include("../comm/tblconf.php"); */ # main actions # file dir rename if($args['triggertype'] == 'renamecheck'){ $out = ''; # 'fdrename: args:['.serialize($args).']'; $fdname = Wht::get($_REQUEST, 'filename'); if(!startsWith($fdname, '/')){ $fdname = '/'.$fdname; } $tmpObj = new WebApp(); $fdname_orig = ''; $hasSubContent = true; $hm = $tmpObj->execBy("select id, parentname, pparentname from ".$_CONFIG['tblpre']."filedirtbl where parentid=$id", ''); if($hm[0]){ $hm = $hm[1][0]; $parentname = $hm['parentname']; $pparentname = $hm['pparentname']; if($parentname != '' && $pparentname != ''){ $fdname_orig = str_replace($pparentname, "", $parentname); debug("extra/fdrename: id:".$hm['id']." parentname:$parentname pparentname:$pparentname orig:$fdname_orig new:$fdname"); } else{ debug("extra/fdrename: cannot found orig. id:".$hm['id']." parentname:$parentname pparentname:$pparentname new:$fdname"); } } else{ $hasSubContent = false; } if($fdname_orig != '' && $fdname_orig != $fdname){ $out .= updateSubDir($tmpObj, $id, $fdname, $fdname_orig); } else if($fdname_orig == '' && $hasSubContent){ $out .= "update subdir failed. 201811161902."; } else{ $out .= "same dirname $fdname. 201811162001."; } } else if($args['triggertype'] == 'deletecheck'){ # move into extra/fddelete.php $out = "trigger to deletecheck"; } else{ $out .= "unknown triggertype:[".$args['triggertype']."]"; debug($out); } #$out .= serialize($_REQUEST); # or #$data['respobj'] = array('output'=>'content'); /* # module path $module_path = ''; include_once($appdir."/comm/modulepath.inc.php"); # without html header and/or html footer $isoput = false; require("../comm/footer.inc.php"); */ # travel all subdir function updateSubDir($myObj, $xid, $dirname, $dirname_old){ $rtn = ''; global $_CONFIG; $hm = $myObj->execBy('select * from '.$_CONFIG['tblpre'].'filedirtbl where parentid='.$xid.' limit 9999', ''); # why cannot limit 9999? if($hm[0]){ $hm = $hm[1]; #debug(" read hm:".serialize($hm)); foreach($hm as $tmpk=>$tmpv){ #$rtn .= ' readdata:'.serialize($tmpv)."<br/>"; $tmpxid = $tmpv['id']; $parentname = $tmpv['parentname']; $pparentname = $tmpv['pparentname']; #debug(" $parentname , $pparentname will be update with $dirname for $dirname_old xid:$tmpxid\n "); # replace dir name if(inString($dirname_old, $parentname)){ $parentname = str_replace($dirname_old, $dirname, $parentname); } if(inString($dirname_old, $pparentname)){ $pparentname = str_replace($dirname_old, $dirname, $pparentname); } debug(" $parentname , $pparentname have been updated with $dirname for $dirname_old xid:$tmpxid\n "); # update sql $updtsql = "update ".$_CONFIG['tblpre']."filedirtbl set parentname='$parentname', pparentname='$pparentname' where id=$tmpxid limit 1"; $updthm = $myObj->execBy($updtsql, ''); if($updthm[0]){ $rtn .= "sub id $tmpxid updt succ."; # [$updtsql]"; } else{ $rtn .= "sub id $tmpxid updt fail."; # [$updtsql]"; } # check sub dir as follow if($tmpxid > 0){ updateSubDir($myObj, $tmpxid, $dirname, $dirname_old); } } } else{ #debug(" extra/fdname: read failed. hm:".serialize($hm)); } return $rtn; } ?> <file_sep>/act/doaddmodi.php <?php # save data from act=add|modify # watermark, Fri May 28 11:31:02 CST 2021 include("./class/WaterMark.class.php"); $fieldlist = array(); $fieldvlist = array(); # remedy for overrided by $obj->get during adding, need a tmp container for query string, Thu Jun 11 22:15:32 CST 2015 $filearr = array(); $disableFileExtArr = array('html','php','js','jsp','pl','shtml', 'sh', 'c', 'cpp', 'py'); /* * security double check for end-user's input * found illegal and empty it * Xenxin<EMAIL> * 14:05 12/9/2019 @param $rawInput, fk, fv @return $safeOutput */ function securityFileCheck4Tmp($fv){ $rtn = $fv; $rtn = securityFileCheck($rtn); $rtn = realpath($rtn); $tmpUploadDir = get_cfg_var('upload_tmp_dir'); $tmpUploadDir = $tmpUploadDir=='' ? '/tmp' : $tmpUploadDir; if(strpos($rtn, $tmpUploadDir) !== 0){ $rtn = ''; } if($rtn != '' && !file_exists($rtn)){ $rtn = ''; } if($rtn != '' && !is_uploaded_file($rtn)){ $rtn = ''; } debug('act/doaddmodi: fk4tmp-x:'.$fv.'->'.$rtn); return $rtn; } //- securityFileCheck , //- Xenxin@<EMAIL> // 11:17 Thursday, December 19, 2019 function securityFileCheck($fv){ $rtn = $fv; //$rtn = realpath($rtn); $badChars = array(';', '%3B', ' ', "%20", '&', "%26", "..", "//", './', "\\", '\.'); $rtn = str_replace($badChars, '', $rtn); if(preg_match("/\|\?/gmi", $rtn)){ $rtn = ''; } if(strpos($rtn, '/') === 0 && strpos($rtn, '/www') !== 0 && strpos($rtn, '/var') !== 0 && strpos($rtn, '/tmp') !== 0 && strpos($rtn, '/srv') !== 0){ $rtn = ''; } debug('act/doaddmodi: fk-x:'.$fv.'->'.$rtn); return $rtn; } //- safe checking if(strtoupper($_SERVER['REQUEST_METHOD']) != 'POST' ){ $tmpErr = "Error with REQUEST_METHOD:[".$_SERVER['REQUEST_METHOD']."]. POST needed. 202102251636."; $out .= " ".$tmpErr; debug("act/doaddmodi: ".$tmpErr); exit(1); } //- real processing.. $hasId = 0; if($id != ''){ $gtbl->setId($id); # speical field $hasId = 1; } for($hmi=$min_idx; $hmi<=$max_idx; $hmi++){ $field = $gtbl->getField($hmi); $fieldv = ''; # remedy by <EMAIL>, Wed Oct 17 12:46:16 CST 2012 $fieldInputType = $gtbl->getInputType($field); $fieldReadOnly = strtolower($gtbl->getReadOnly($field)); if($field == null | $field == '' || $field == $gtbl->getMyId()){ continue; }else if(!$user->canWrite($field) || ($hasId==1 && ($fieldReadOnly == 'readonly' || $fieldReadOnly == 'disabled'))){ $out .= "$field cannot be written.\n"; continue; }else if(in_array($field, $opfield)){ $fieldv = $userid; $fieldlist[] = $field; #$gtbl->set($field, $fieldv); $fieldvlist[$field] = $fieldv; } else if(in_array($field,$timefield)){ $fieldv = ''; if($id=='' || $id=='0'){ # insert if(inList($field, 'inserttime,insertime,insertd,created,starttime,dinserttime')){ # see comm/tblconf.php $fieldv = date("Y-m-d H:i:s", time()); # 'NOW()'; $fieldlist[] = $field; } } else{ # update if(inList($field, 'updatetime,endtime,editime,edittime,modifytime,updated,dupdatetime')){ $fieldv = date("Y-m-d H:i:s", time()); # 'NOW()'; $fieldlist[] = $field; } } if($fieldv != ''){ $fieldvlist[$field] = $fieldv; } else{ debug(__FILE__.": unclassified timefield:[$field]. 1611101112."); #$fieldv = date("Y-m-d H:i:s", time()); # 'NOW()'; #$fieldlist[] = $field; # remedy 19:13 Wednesday, April 15, 2020 if(isset($_REQUEST[$field])){ $fieldv = trim(Wht::get($_REQUEST, $field)); if($fieldv == ''){ $fieldv = date("Y-m-d H:i:s", time()); } $fieldlist[] = $field; $fieldvlist[$field] = $fieldv; } } continue; } #else if($field == 'password'){ else if(inString('password', $field) || inString('pwd', $field)){ if($_REQUEST[$field] != ''){ $fieldv = sha1($_REQUEST[$field]); $fieldlist[] = $field; #$gtbl->set($field, $fieldv); # 2014-10-26 21:33 $fieldvlist[$field] = $fieldv; } else{ continue; } debug("field:[$field] fieldv:[$fieldv]"); #print(__FILE__.": field:[$field] fieldv:[$fieldv]"); } else{ if($fieldInputType == 'file'){ $fieldv_orig = $_REQUEST[$field.'_orig']; $_FILES[$field]['name'] = securityFileCheck($_FILES[$field]['name']); $_FILES[$field]['tmp_name'] = securityFileCheck4Tmp($_FILES[$field]['tmp_name']); if($_FILES[$field]['name'] == ''){ $fileOnlineSrc = Wht::get($_REQUEST, $field.'_onlinesrc'); if($fileOnlineSrc != ''){ $fieldv = $fileOnlineSrc; # extra online src, 09:01 2021-03-28 } else if($fieldv_orig != ''){ if(strpos($fieldv_orig, $shortDirName) === false && !inString("//", $fieldv_orig)){ $fieldv_orig = $shortDirName."/".$fieldv_orig; } $fieldv = $fieldv_orig; } } else if($_FILES[$field]['name'] != ''){ # safety check $tmpFileNameArr = explode(".",strtolower($_FILES[$field]['name'])); $tmpfileext = end($tmpFileNameArr); if(in_array($tmpfileext, $disableFileExtArr)){ debug("found illegal upload file:[".$_FILES[$field]['name']."]"); $out .= "file:[".$_FILES[$field]['name']."] is not allowed. 201210241927"; continue; } $filedir = $_CONFIG['uploaddir']; if($gtbl->getId() != ''){ # remove old file if necessary $oldfile = $gtbl->get($field); # this might override what has been set by query string if($oldfile != ""){ $oldfile = str_replace($shortDirName."/","", $oldfile); unlink($appdir."/".$oldfile); } else{ debug("oldfile:[$oldfile] not FOUND. field:[$field]. 201810111959."); } } $filedir = $filedir."/".date("Ym"); # Fri Dec 5 14:19:05 CST 2014 if(!file_exists($appdir."/".$filedir)){ mkdir($appdir."/".$filedir); } $filename = basename($_FILES[$field]['name']); $filename = Base62x::encode($filename); $fileNameLength = strlen($filename); $fileNameLength = $fileNameLength > 128 ? 128 : $fileNameLength; $filename = date("dHis")."_".substr($filename, -$fileNameLength).".".$tmpfileext; #print __FILE__.": filename:[$filename]"; $finalRealFile = $appdir."/".$filedir."/".$filename; if(move_uploaded_file($_FILES[$field]['tmp_name'], $finalRealFile)){ $out .= "file:[$filedir/$filename] succ."; if($_CONFIG['watermark_for_upload_image'] != "" && isImg($finalRealFile)){ $waterMark = new WaterMark($finalRealFile); $waterMark->addString($_CONFIG['watermark_for_upload_image']); } } else{ // Check $_FILES['upfile']['error'] value. $tmpErrMsg = ''; switch ($_FILES[$field]['error']) { case UPLOAD_ERR_OK: break; case UPLOAD_ERR_NO_FILE: $tmpErrMsg = ('No file sent'); break; case UPLOAD_ERR_INI_SIZE: $tmpErrMsg = ('Exceeded filesize limit '.ini_get('upload_max_filesize').' in server-side'); break; case UPLOAD_ERR_FORM_SIZE: $tmpErrMsg = ('Exceeded filesize limit/'.$_REQUEST['MAX_FILE_SIZE'].' in client-side'); break; case UPLOAD_ERR_PARTIAL: $tmpErrMsg = 'Only partially uploaded'; break; case UPLOAD_ERR_EXTENSION: $tmpErrMsg = 'Stopped by other extensions'; break; default: $tmpErrMsg = ('Unknown errors ['.$_FILES[$field]['error'].']'); } $out .= " file:[$filename] fail for $tmpErrMsg. 201202251535."; } #$fieldv = $filedir."/".$filename; $fieldv = $shortDirName."/".$filedir."/".$filename; $filearr['filename'] = basename($_FILES[$field]['name']); # sometimes original name may be different with uploadedfile. $filearr['filesize'] = intval($_FILES[$field]['size']/1000 + 1); # KB $filearr['filetype'] = substr($_FILES[$field]['type'], 0, 64); # see filedirtbl definition $tmpFileName = Wht::get($_REQUEST, 'filename'); if($tmpFileName != '' && $tmpFileName != $filearr['filename']){ $filearr['filename'] = $tmpFileName.$filearr['filename']; } } } else if($gtbl->getSelectMultiple($field)){ if(is_array($_REQUEST[$field])){ $fieldv = implode(",", $_REQUEST[$field]); }else{ $fieldv = $_REQUEST[$field]; } } else{ $fieldv = trim(Wht::get($_REQUEST, $field)); if($fieldInputType == 'select' && ($fieldReadOnly == 'readonly' || $fieldReadOnly == 'disabled')){ $fieldv = Wht::get($_REQUEST, $field.'_select_orig'); } if($fieldv == ''){ if($gtbl->isNumeric($hmfield[$field]) == 1){ $fieldv = $hmfield[$field."_default"]; #print __FILE__.": field:[".$field."] type:[".$hmfield[$field]."] is int."; $fieldv = $fieldv=='' ? 0 : $fieldv; } } else{ if(strpos($fieldv,"<") !== false){ # added by wadelau on Sun Apr 22 22:09:46 CST 2012 if($fieldInputType == 'textarea'){ # allow all html tags except these below $fieldv = str_replace("<script","&lt;script", $fieldv); $fieldv = str_replace("<iframe","&lt;iframe", $fieldv); $fieldv = str_replace("<embed","&lt;embed", $fieldv); } else{ $fieldv = str_replace("<","&lt;", $fieldv); } } if(strpos($fieldv, "\n") !== false){ $fieldv = str_replace("\n", "<br/>", $fieldv); } } } $fieldlist[] = $field; #$gtbl->set($field, $fieldv); $fieldvlist[$field] = $fieldv; } #print(__FILE__.": field:[$field] fieldv:[$fieldv]"); } #print(__FILE__.": fieldlist:[".$gtbl->toString($fieldlist)."]"); foreach($fieldvlist as $k=>$v){ $gtbl->set($k, $v); } if(count($filearr)){ foreach($filearr as $k=>$v){ $gtbl->set($k, $v); } } $hm = $gtbl->setBy(implode(',', $fieldlist), null); #print_r($hm); if($hm[0]){ $hm = $hm[1]; if($gtbl->getId() == ''){ $gtbl->setId($hm['insertid']); $id = $gtbl->getId(); } # read newly-written data, Tue Sep 27 13:28:06 CST 2016 $hmNew = $gtbl->getBy('*', $gtbl->myId.'="'.$id.'"'); if($hmNew[0]){ $hmNew = $hmNew[1][0]; #debug(__FILE__.": resultset-tag:[".$gtbl->resultset."]"); $gtbl->set($gtbl->resultset, $hmNew); #debug($gtbl->get($gtbl->resultset)); } # some triggers bgn, added on Fri Mar 23 21:51:12 CST 2012 include("./act/trigger.php"); # some triggers end, added on Fri Mar 23 21:51:12 CST 2012 $out .= "<script> parent.sendNotice(true, '".$lang->get('notice_success')."'); parent.switchArea('contentarea_outer','off'); </script>"; } else{ $servResp = serialize($hm); $servResp = str_replace("'", "\'", $servResp); $foundErr = false; foreach($fieldlist as $k=>$v){ if(inString($v, $servResp)){ $servResp .= "<br/>".$gtbl->getCHN($v)."[$v]: ".$lang->get('notice_save_error'); $foundErr = true; } } if($foundErr){ if(inString('Data too long', $servResp)){ $servResp .= "<br/>".$lang->get("notice_save_error_data_too_long"); } else if(inString('Incorrect', $servResp)){ $servResp .= "<br/>".$lang->get("notice_save_error_incorrect_type"); } } if(!$foundErr){ if(inString('Duplicate entry', $servResp)){ $priuni = $gtbl->get($gtbl->PRIUNI); $servResp .= "<br/>".$lang->get('notice_save_error'); $hasCatched = false; foreach($priuni as $k=>$v){ if($k == 'PRI'){ continue; } # skip id? foreach($v as $k2=>$v2){ if(isset($_REQUEST[$v2])){ $servResp .= "<br/>".$gtbl->getCHN($v2)."[$v2]: ".$_REQUEST[$v2].""; $hasCatched = true; } } } if(!$hasCatched){ $servResp .= "<br/>Unknown error. 202111031159.<br/>".$lang->get('notice_upload_error'); } $foundErr = true; } } $out .= "<script> if(typeof parent.sendNotice !='undefined'){ parent.sendNotice(false, '".$lang->get('notice_failure')."'); }; if(true){ var servResp=parent._g('respFromServ'); if(servResp){ servResp.innerHTML='<p style=\"color:red;\">".$lang->get('notice_failure')."<br/>".$servResp."</p>';}} </script>"; debug("act/doaddmodi: ".$servResp); } $gtbl->setId(''); $id = ''; ?><file_sep>/extra/fddelete.php <?php # # file and name rename and its subdirectories # <EMAIL>, Mon Nov 12 16:14:56 CST 2018 # /* require("../comm/header.inc.php"); $gtbl = new GTbl($tbl, array(), $elementsep); include("../comm/tblconf.php"); */ # main actions # file dir rename if($args['triggertype'] == 'renamecheck'){ # move into extra/fdrename $out = ' trigger to fdrename...'; # 'fdrename: args:['.serialize($args).']'; } else if($args['triggertype'] == 'deletecheck'){ #$out = "trigger to deletecheck...."; #debug("trigger to deletecheck.... deleteresult:[$doDeleteResult] hmorig:".serialize($hmorig)); if(inString('dodelete', $act) && isset($hmorig) && $hmorig['itype'] == 1){ # dir deletion only $lastId = $hmorig['id']; $hm = $gtbl->getBy('id', "parentid=$lastId"); if($hm[0]){ $out .= "id:$lastId has sub contents. deletion will be refused."; $sql = "replace into ".$gtbl->getTbl()." set "; foreach($hmorig as $k=>$v){ if(!startsWith($k, 'pnsk') && !startsWith($k, 'oppnsk')){ $sql .= "$k='$v', "; } } $sql = substr($sql, 0, strlen($sql)-2); # rm ", " #$out .= " undo sql:[$sql]"; $hm2 = $gtbl->execBy($sql, null); if($hm2[0]){ $out .= " undo needed and succ."; $doDeleteResult = false; $deleteErrCode = '201811241145'; } else{ $out .= " undo failed."; } } else{ $out .= "id:$lastId is empty and deletion succ."; } } else{ $out .= "act:$act not deletion or itype:".$hmorig['itype']." not dir, deletecheck skip...."; } #debug('out:'.$out); } else{ $out .= "unknown triggertype:[".$args['triggertype']."]"; debug("unknown triggertype:[".$args['triggertype']."]"); } #$out .= serialize($_REQUEST); # or #$data['respobj'] = array('output'=>'content'); /* # module path $module_path = ''; include_once($appdir."/comm/modulepath.inc.php"); # without html header and/or html footer $isoput = false; require("../comm/footer.inc.php"); */ ?> <file_sep>/gmis.manualbackup.sh #!/bin/sh # create backup anytime from shell commands # since 20110414 # update on Wed Jul 13 17:48:50 UTC 2011 me=`whoami`; echo $me; #if [ "$me" != "root" ]; then # echo "This program needs root priviledges to run."; # exit; #fi curdate="`date +%Y%m%d-%H-%M`"; echo "current time:"$curdate ; #echo "test point."; #exit ; tmpdir="/var/tmp"; # rm old files rm -f $tmpdir/gtbl.* # files dir="/www/webroot/pages/gmis"; cd $dir tar czfh $tmpdir/gmis.$curdate.tar.gz ./* sz $tmpdir/gmis.$curdate.tar.gz # data mysqldump --opt -ugmisUSER -pgmisPWD gmisdb --default-character-set=utf8 > $tmpdir/gmis-db.$curdate.sql tar czfh $tmpdir/gmis-db.$curdate.tar.gz $tmpdir/gmis-db.$curdate.sql sz $tmpdir/gmis-db.$curdate.tar.gz echo "$curdate data backup succ." >> $tmpdir/manualbackup.log echo "databackup succ." ; <file_sep>/extra/importexcel.php <?php # import data from external excel file with .xlsx # tpl by <EMAIL> on Sun Jan 31 10:22:15 CST 2016 # remedy by <EMAIL>, Wed Jul 31 16:55:07 HKT 2019 # require("../comm/header.inc.php"); require("../class/SimpleXLSX.php"); $gtbl = new GTbl($tbl, array(), $elementsep); include("../comm/tblconf.php"); $myExtraTitle = "导入外部 Excel / SpreadSheet 数据"; # main actions $act = Wht::get($_REQUEST, "act"); if($act == ''){ $act = 'import'; } # check writeable include("../act/tblcheck.php"); $hasDisableW = false; if(true){ $accMode = $gtbl->getMode(); if($accMode == 'r'){ $hasDisableW = true; } else if($accMode == 'o-w'){ $hasDisableW = true; $recOwnerList = array('op', 'operator', 'ioperator', 'editor'); foreach($recOwnerList as $ownk=>$ownv){ $theOwner = $hmorig[$ownv]; if($theOwner == $userid){ $hasDisableW = false; #print "userid:$userid theowner:$theOwner ."; break; } } } else{ #debug("unkown accmode:[$accMode]."); } } if(startsWith($act, 'import') && $hasDisableW && !$isAddByCopy){ $out .= "Access to writing denied. 访问被拒绝. 201811111014."; $out .= "<br/><br/><a href=\"javascript:switchArea('contentarea_outer','off');\">关闭 并尝试其他操作.</a>"; } else{ # writeable okay... $out = ""; # clear bfr content if($act == 'import'){ $dataFieldStr = "<div id='rawdatadiv' style='text-align:center;'>". "<table name='datafields' name='datafields' style='border-spacing:0px;margin:0 auto;'>"; $dataRow = "<tr>"; $firstRow = "<tr>"; $secRow = "<tr>"; $columni = 1; $dataFields = array(); $dataSelect = array(); for($hmi=$min_idx; $hmi<=$max_idx;$hmi++){ $field = $gtbl->getField($hmi); $fieldinputtype = $gtbl->getInputType($field); $fieldExtraInput = $gtbl->getExtraInput($field, null); if($field == null || $field == ''){ continue; } else if($fieldinputtype == 'hidden'){ continue; } else if($gtbl->filterHiddenField($field, $opfield, $timefield)){ continue; } else if(!$user->canWrite($field)){ continue; } else if($fieldinputtype == 'file'){ continue; #? } else if($fieldExtraInput != '' && inString('linktbl',$fieldExtraInput)){ continue; #? allow xdirectory.... } $dataRow .= "<td style='border:1px solid black;color:blue;'>".$gtbl->getCHN($field)."</td>"; $firstRow .= "<td style='border:0px solid black;text-align:center;'>".($columni++)."</td>"; $secRow .= "<td style='border:1px solid black;'>&nbsp;</td>"; $dataFields[] = $field; # chk select options if($fieldinputtype == 'select'){ $dataSelect[$field] = $gtbl->getSelectOption($field, null); } } # figure out select $dataSelect2 = array(); foreach($dataSelect as $k=>$v){ if(preg_match_all("/ value=\"([^\"]*)\">([^\-|\(]+)[\(|\-]*/", $v, $matchArr)){ #print_r($matchArr); foreach($matchArr[0] as $k2=>$v2){ #debug($matchArr[1][$k2]." : ".$matchArr[2][$k2]); #$dataSelect2[$k][$matchArr[2][$k2]] = $matchArr[1][$k2]; $dataSelect2[$k][$matchArr[1][$k2]] = $matchArr[2][$k2]; } } } #debug("extra/importexcel: dataSelect2:".serialize($dataSelect2)); $dataSelect = $dataSelect2; # figure out select, end # retrieve example data $exampleRow = '<tr>'; $hmResult = $gtbl->execBy("select ".implode(',', $dataFields)." from $tbl where 1=1 order by rand() limit 1", '', null); if($hmResult[0]){ $hmResult = $hmResult[1][0]; foreach($hmResult as $k=>$v){ if(array_key_exists($k, $dataSelect)){ $v = $dataSelect[$k][$v]; } $exampleRow .= "<td style='border:1px solid black;'>$v</td>"; } } $dataFieldStr .= "$firstRow</tr>$dataRow</tr>$exampleRow</tr>$secRow</tr></table></div>"; $out .= "<fieldset><legend>$myExtraTitle: 步骤1</legend> <form id='addstepform' name='addstepform' action='extra/importexcel.php?sid=$sid&act=doimportpreview&tbl=$tbl&db=$db' method='post' enctype='multipart/form-data'>"; $out .= "<p style='text-align:center;'>当前可接受的外部数据表格式表头及样例:<br/>$dataFieldStr</p>"; $out .= "<p><strong>下载<button type='button' name='dnldexampledata' onclick=\"javascript:doActionEx('extra/importexcel.php?sid=$sid&act=doimportdownload&tbl=$tbl&db=$db', 'example_download_frame');\" title='下载数据格式样表'>数据样表</button> " ." --→ 另存为 .xlsx --→ 整理准备数据 --→ 上传数据来源文件</strong></p>"; $out .= "<div id='dnlddiv' style='display:none'><iframe id='example_download_frame' name='example_download_frame' width='0' height='0'></iframe></div>"; $out .= "<p>选择数据来源 Excel / SpreadSheet 文件( .xlsx):<br/><input name='myexcelfile' id='myexcelfile' type='file'/></p>"; $out .= "<p><strong>注意</strong>:" ."<br/><strong>批量导入外部数据便捷、高效</strong>, " ."<br/>同时, 批量导入外部数据流程也比较复杂, " ."<br/>解析过程受到文件格式、数据格式、字符编码、浏览器和操作系统设置等多重因素影响; " ."<br/>写入过程也涉及到选择项翻译、数据格式化、数据校验和数据表本身的约束与限制。" ."<br/><br/>这些过程可能存在格式识别或写入异常, <span style='color:blue;'>请 在数据导入后立即进行数据审核</span>." ."<br/>个别没有显示在样例表中的数据项表示无法通过批量导入程序处理, " ."<br/>&nbsp;&nbsp;或者可以通过导入程序自动生成,无需手工录入." ."<br/><br/>待上传的数据表需删除掉上述样例数据,仅保留表头及其顺序即可(<span style='color:blue;'>蓝色</span>, 第二行)." ."<br/>待导入外部数据表文件格式为 Microsoft Office Excel Open XML Format, 默认扩展名为 .xlsx " ."</p>"; $out .= "<p><hr/></p><p><input type='submit' value='保存 & 下一步' id='addmultistepsubmit' onclick=\"javascript:doActionEx(this.form.name,'contentarea');\"/></p>"; $out .= "</form></fieldset>"; } else if($act == 'doimportpreview'){ $dataFile = ""; $field = "myexcelfile"; $isSucc = true; # file upload $filearr = array(); $disableFileExtArr = array('html','php','js','jsp','pl','shtml', 'sh', 'c', 'cpp', 'py'); if($_FILES[$field]['name'] != ''){ # safety check $tmpFileNameArr = explode(".",strtolower($_FILES[$field]['name'])); $tmpfileext = end($tmpFileNameArr); if(in_array($tmpfileext, $disableFileExtArr)){ debug("found illegal upload file:[".$_FILES[$field]['name']."]"); $out .= "File:[".$_FILES[$field]['name']."] is not allowed. 201210241927"; $isAllow = false; $isSucc = false; } else{ # allowed $filedir = $_CONFIG['uploaddir']; if($gtbl->getId() != ''){ # remove old file if necessary $oldfile = $gtbl->get($field); # this might override what has been set by query string if($oldfile != ""){ $oldfile = str_replace($shortDirName."/","", $oldfile); unlink($appdir."/".$oldfile); } else{ debug("oldfile:[$oldfile] not FOUND. field:[$field]. 201810111959."); } } $filedir = $filedir."/".date("Ym"); # Fri Dec 5 14:19:05 CST 2014 if(!file_exists($appdir."/".$filedir)){ mkdir($appdir."/".$filedir); } $filename = basename($_FILES[$field]['name']); $filename = Base62x::encode($filename); $fileNameLength = strlen($filename); $fileNameLength = $fileNameLength > 128 ? 128 : $fileNameLength; $filename = date("dHi")."_".substr($filename, -$fileNameLength).".".$tmpfileext; #print __FILE__.": filename:[$filename]"; if(move_uploaded_file($_FILES[$field]['tmp_name'], $appdir."/".$filedir."/".$filename)){ $out .= "File:[$filedir/$filename] succ."; $dataFile = $filedir."/".$filename; } else{ // Check $_FILES['upfile']['error'] value. $tmpErrMsg = ''; switch ($_FILES[$field]['error']) { case UPLOAD_ERR_OK: break; case UPLOAD_ERR_NO_FILE: $tmpErrMsg = ('No file sent'); break; case UPLOAD_ERR_INI_SIZE: $tmpErrMsg = ('Exceeded filesize limit '.ini_get('upload_max_filesize').' in server-side'); break; case UPLOAD_ERR_FORM_SIZE: $tmpErrMsg = ('Exceeded filesize limit/'.$_REQUEST['MAX_FILE_SIZE'].' in client-side'); break; case UPLOAD_ERR_PARTIAL: $tmpErrMsg = 'Only partially uploaded'; break; case UPLOAD_ERR_EXTENSION: $tmpErrMsg = 'Stopped by other extensions'; break; default: $tmpErrMsg = ('Unknown errors ['.$_FILES[$field]['error'].']'); } $out .= " File:[$filename] fail for $tmpErrMsg. 201202251535."; $isSucc = false; } } # allowed end } else{ $out .= "File is empty / 数据文件为空, 请 返回重试. 201202251016."; $isSucc = false; } # file upload end # data parse if($dataFile != ''){ $xlsx = new SimpleXLSX(); $xlsx->debug = true; // display errors $xlsx->skipEmptyRows = true; // skip empty rows $result = $xlsx->parseFile($appdir."/".$dataFile); $maxRowPreview = 5; $rowCount = 0; if($result){ $rows = $xlsx->rows(); $totalCount = count($rows); #debug($rows); $out .= "<p><strong>待导入数据预览</strong><hr/></p><table id='rawdata' name='rawdata' ". " style='border-spacing:0px;margin:0 auto;'>"; foreach($rows as $k=>$row){ $out .= "<tr>"; foreach($row as $ck=>$col){ $out .= "<td style='border:1px solid black;'>$col</td>"; } $out .= "</tr>"; if($rowCount++ > $maxRowPreview){ $out .= "<tr><td colspan='6'><br/>....<br/><strong>共计 $totalCount 行, 余下还有 " .($totalCount-$maxRowPreview)." 行</strong></td></tr>"; break; } } if($rowCount < $maxRowPreview){ $out .= "<tr><td colspan='6'><br/><strong>共计 $totalCount 行</strong></td></tr>"; } $out .= "</table><p><hr/></p>"; } else{ $out .= "Parse file error. 201202251021."; $isSucc = false; } } else{ # no file. } # data parse end # ready to resp $rawOut = $out; $out = "<fieldset><legend>$myExtraTitle: 步骤2</legend> <form id='addstepform' name='addstepform' action='extra/importexcel.php?sid=$sid&act=doimportsave&tbl=$tbl&db=$db' method='post' enctype='multipart/form-data'>"; if($isSucc){ # next step $out .= "<p>$rawOut</p>"; $out .= "<p><input type='hidden' id='datafile' name='datafile' value='".$dataFile."'/></p>"; $out .= "<p>Data file read succ.... / 数据文件读取成功!</p>"; } else{ # back $out .= "<p>$rawOut</p>"; $out .= "<p style='color:red;'>Data file read fail.... / 数据文件读取失败! 请 返回重试... </p>"; $out .= "<p><a href='#' onclick='javascript:GTAj.backGTAjax('contentarea', 1);'><< Back / 返回</a></p>"; } $out .= "<p><hr/></p>"; $out .= "<p><input type='button' value='返回 & 上一步' id='addmultistepback' onclick=\"javascript:GTAj.backGTAjax('contentarea', 1);\"/>"; $out .= "&nbsp; &nbsp; <input type='submit' value='保存 & 下一步' id='addmultistepsubmit' onclick=\"javascript:doActionEx(this.form.name,'contentarea');\"/></p>"; $out .= "</form></fieldset>"; } else if($act == 'doimportsave'){ $isSucc = true; $dataFile = Wht::get($_REQUEST, 'datafile'); if($dataFile != ''){ if(file_exists($appdir."/".$dataFile)){ # collect fields $dataFields = array(); $dataSelect = array(); $opFieldStr = ''; $timeFieldStr = ''; $dataRow = "<tr>"; $firstRow = "<tr>"; $secRow = "<tr>"; $columni = 1; for($hmi=$min_idx; $hmi<=$max_idx;$hmi++){ $field = $gtbl->getField($hmi); $fieldinputtype = $gtbl->getInputType($field); $fieldExtraInput = $gtbl->getExtraInput($field, null); if($field == null || $field == ''){ continue; } else if($fieldinputtype == 'hidden'){ continue; } else if($gtbl->filterHiddenField($field, $opfield, $timefield)){ if(in_array($field, $opfield)){ $opFieldStr = "$field='$userid'"; } else if(in_array($field, $timefield)){ $timeFieldStr = "$field='".date("Y-m-d H:i:s", time())."'"; } continue; } else if(!$user->canWrite($field)){ continue; } else if($fieldinputtype == 'file'){ continue; #? } else if($fieldExtraInput != '' && inString('linktbl',$fieldExtraInput)){ continue; #? } $dataFields[] = $field; # chk select options if($fieldinputtype == 'select'){ $dataSelect[$field] = $gtbl->getSelectOption($field, null); } } #debug("extra/importexcel: dataSelect:".serialize($dataSelect)); $dataSelect2 = array(); foreach($dataSelect as $k=>$v){ if(preg_match_all("/ value=\"([^\"]*)\">([^\-|\(]+)[\(|\-]*/", $v, $matchArr)){ #print_r($matchArr); foreach($matchArr[0] as $k2=>$v2){ #debug($matchArr[1][$k2]." : ".$matchArr[2][$k2]); $dataSelect2[$k][$matchArr[2][$k2]] = $matchArr[1][$k2]; } } } #debug("extra/importexcel: dataSelect2:".serialize($dataSelect2)); $dataSelect = $dataSelect2; # parse data $xlsx = new SimpleXLSX(); $xlsx->debug = true; // display errors $xlsx->skipEmptyRows = true; // skip empty rows $result = $xlsx->parseFile($appdir."/".$dataFile); if($result){ $rows = $xlsx->rows(); $totalRows = count($rows); $sql = ""; $field1Name = $gtbl->getCHN($dataFields[0]); $field2Name = $gtbl->getCHN($dataFields[1]); $succCount = 0; $failCount = 0; $failArr = array(); foreach($rows as $k=>$row){ if($row[0]==='' && $row[1]==='' && $row[2]===''){ debug("extra/importexcel: found definition row, 3rd... skip....".serialize($row)); continue; } else if($row[0]=='1' && $row[1]=='2'){ debug("extra/importexcel: found definition row... skip....".serialize($row)); continue; } else if($row[0]==$field1Name && $row[1]==$field2Name){ debug("extra/importexcel: found definition row, 2nd... skip....".serialize($row)); continue; } $sql = "insert into $tbl set "; foreach($row as $ck=>$col){ $field = $dataFields[$ck]; if($field == ''){ debug("extra/importexcel: found illegal field, skip.... ck:$ck"); continue; } if(in_array($field, $timefield)){ $col = date("Y-m-d H:i:s", time()); } if(array_key_exists($field, $dataSelect)){ $col = $dataSelect[$field][$col]; #debug("extra/importexcel: found col:".$field." in selelct and convert...."); } if($col == '' && $col != '0'){ if($gtbl->isNumeric($hmfield[$field]) == 1){ $col = 0; $out .= "<br/><span style='color:red;'>".$gtbl->getCHN($field)."/$field 空值异常</span>, 发生在 [ " .implode(', ', $row)." ] , 已按默认值处理, 行: ".($k+1); } } $sql .= $field."='".addslashes($col)."',"; } if($opFieldStr != ''){ $sql .= $opFieldStr.','; } if($timeFieldStr != ''){ $sql .= $timeFieldStr.','; } $sql = substr($sql, 0, strlen($sql)-1); # rm , debug($sql); $dbResult = $gtbl->execBy($sql, null, null); debug($dbResult); if($dbResult[0]){ $succCount++; } else{ $errStr = '<br/> <span style="color:red;">异常信息: '.($servResp=htmlentities(serialize($dbResult))); if(inString('Duplicate entry', $servResp)){ $errStr .= " / 重复或冲突数据 "; } else{ $errStr .= " / 其他写入错误 "; } $errStr .= "</span>, 行: ".($k+1); $row[] = $errStr; $failArr[] = $row; $failCount++; } } #$out .= "<p>$k: $sql</p>"; $out .= "<p><strong>数据总条数: $totalRows , 有效数据: ".($totalCount=$succCount+$failCount) ." , 其中成功导入 $succCount , 失败条数: ".($failCount)." </strong>."; if($failCount > 0){ $out .= "<br/><br/>导入失败数据如下:<br/>"; foreach($failArr as $k=>$v){ $out .= "<br/>".implode(', ', $v); } $out .= "<br/><br/>请 修改调整后重试."; } else{ $out .= "<br/><br/>请 立即 <a href=\"#\" onclick=\"javascript:window.location.reload();\">刷新列表页</a> 进行数据审核."; # @todo rm dataFile ? } $out .= "</p>"; } else{ $out .= "Parse file:[$dataFile] error. 201202251021."; $isSucc = false; } # parse data end } else{ $isSucc = false; $out .= "Data file:[$dataFile] not exists. 201202251146."; } } else{ $isSucc = false; $out .= "Data file is empty. 201202251147."; } # ready to resp if(true){ $rawOut = $out; $out = "<fieldset><legend>$myExtraTitle: 步骤3</legend> <form id='addstepform' name='addstepform' action='../extra/importexcel.php?sid=$sid&act=doimportsave&tbl=$tbl&db=$db' method='post' enctype='multipart/form-data'>"; if($isSucc){ $out .= "<p><strong>外部数据导入结果</strong></p><hr/>".$rawOut; } else{ $out .= "<p style='color:red;'> 数据导入保存失败, 请 返回重试... </p>"; } $out .= "<p><hr/></p>"; $out .= "<p><input type='button' value='继续导入' id='addmultistepback' onclick=\"javascript:doActionEx('extra/importexcel.php?tbl=$tbl&sid=$sid', 'contentarea');\"/>"; $out .= "&nbsp; &nbsp; <input type='button' value='关闭' id='addmultistepclose' onclick=\"javascript:switchArea('contentarea_outer','off');\"/></p>"; $out .= "</form></fieldset>"; } # ready to resp, end } else if($act == 'doimportdownload'){ $dataFieldStr = ""; $dataRow = ""; $firstRow = ""; $secRow = ""; $columni = 1; $dataFields = array(); $dataSelect = array(); for($hmi=$min_idx; $hmi<=$max_idx;$hmi++){ $field = $gtbl->getField($hmi); $fieldinputtype = $gtbl->getInputType($field); $fieldExtraInput = $gtbl->getExtraInput($field, null); if($field == null || $field == ''){ continue; } else if($fieldinputtype == 'hidden'){ continue; } else if($gtbl->filterHiddenField($field, $opfield, $timefield)){ continue; } else if(!$user->canWrite($field)){ continue; } else if($fieldinputtype == 'file'){ continue; #? } else if($fieldExtraInput != '' && inString('linktbl',$fieldExtraInput)){ continue; #? allow xdirectory.... } $dataRow .= $gtbl->getCHN($field).","; $firstRow .= ($columni++).","; $secRow .= ","; $dataFields[] = $field; # chk select options if($fieldinputtype == 'select'){ $dataSelect[$field] = $gtbl->getSelectOption($field, null); } } # figure out select $dataSelect2 = array(); foreach($dataSelect as $k=>$v){ if(preg_match_all("/ value=\"([^\"]*)\">([^\-|\(]+)[\(|\-]*/", $v, $matchArr)){ #print_r($matchArr); foreach($matchArr[0] as $k2=>$v2){ #debug($matchArr[1][$k2]." : ".$matchArr[2][$k2]); #$dataSelect2[$k][$matchArr[2][$k2]] = $matchArr[1][$k2]; $dataSelect2[$k][$matchArr[1][$k2]] = $matchArr[2][$k2]; } } } $dataSelect = $dataSelect2; # figure out select, end # retrieve example data $exampleRow = ''; $hmResult = $gtbl->execBy("select ".implode(',', $dataFields)." from $tbl where 1=1 order by rand() limit 1", '', null); if($hmResult[0]){ $hmResult = $hmResult[1][0]; foreach($hmResult as $k=>$v){ if(array_key_exists($k, $dataSelect)){ $v = $dataSelect[$k][$v]; } $exampleRow .= "$v,"; } } $dataFieldStr .= "$firstRow\n$dataRow\n$exampleRow\n$secRow\n"; $isSucc = true; # prepare file $dnld_dir = $appdir."/dnld"; $dnld_file = "exampledata_".str_replace("gmis_","",$tbl)."_".date("Y-m-d-H-i").".csv"; $myfp = fopen($dnld_dir.'/'.$dnld_file, 'wb'); if($myfp){ fwrite($myfp, chr(0xEF).chr(0xBB).chr(0xBF)); fwrite($myfp, $dataFieldStr); } else{ debug("extra/importexcel: example data file:[$dnld_file] download failed. 201202251827."); $isSucc = false; } fclose($myfp); # prepare file, end if($isSucc){ $out .= "File:$dnld_file succ.<br/><script type=\"text/javascript\">"; $out .= "parent.window.open('".$rtvdir."/dnld/".$dnld_file."','Excel File Download','scrollbars,toolbar,location=0,status=yes,resizable,width=600,height=400');"; $out .= "</script>"; } else{ $out .= "File:$dnld_file fail. <script type=\"text/javascript\">"; $out .= "window.alert('样表数据准备未成功, 请稍后重试.');"; $out .= "</script>"; } $out .= "<!-- SUCC, OK, OKAY -->"; } } # end of writeable $out .= '<!-- my output timestamp: '.($myServTime=date("Y-m-d H:i:s", time())).' -->'; # or $data['respobj'] = array('output-timestamp'=>$myServTime); # module path $module_path = ''; include_once($appdir."/comm/modulepath.inc.php"); # without html header and/or html footer $isoput = false; require("../comm/footer.inc.php"); ?> <file_sep>/tmp/a.php <?php print "week-numw:".date("W")."\n"; ?> <file_sep>/act/pickup.php <?php /* * pick up/select on all avaliable values * added by <EMAIL> * init. Mon Sep 17 21:21:03 CST 2018 * updt. Sat Mar 28 11:16:55 CST 2020 */ //- module include_once($appdir.'/class/pickup.class.php'); # retrieve preset vars include("./act/preset-vars.inc.php"); $formid = "gmis_pickup"; $hiddenfields = ""; $colsPerRow = 1; $shortFieldCount = 4; $pickupFieldCount = Wht::get($_REQUEST, 'pickupfieldcount'); $pickupFieldCount = $pickupFieldCount < $shortFieldCount ? $shortFieldCount : $pickupFieldCount; $rowHeight = 40; $pickup = new PickUp($gtbl->get('args_to_parent')); # args see class/GTbl $pickup->setTbl($gtbl->getTbl()); $pickup->set('fieldlist', $gtbl->getFieldList()); $pickup->set('myid', $gtbl->getMyId()); $base62x = new Base62x(); $base62xTag = 'b62x.'; if(inString('&pntc=', $jdo)){ $jdo = preg_replace('/&pntc=[0-9]+/', '', $jdo); # remedy 09:31 2022-08-27 } $out .= "<fieldset style=\"border-color:#5f8ac5;border: 1px solid #5f8ac5; background:#E8EEF7;\">" ."<legend><h4>".$lang->get("func_pickup")."</h4></legend><form id=\"" .$formid."\" name=\"".$formid."\" method=\"post\" action=\"".$jdo."&act=list\" " .$gtbl->getJsActionTbl()."><table cellspacing=\"0\" cellpadding=\"0\" " ." style=\"border:0px solid black; width:98%; margin-left:auto; margin-right:auto; background:transparent;\">"; $out .= "<tr height='".($rowHeight/2)."px'><td width=\"1%\">&nbsp;</td> <td width=\"9%\"> </td> <td>&nbsp; </td> <td style='width:35px;'>"; if($pickupFieldCount <= $shortFieldCount){ $out .= "<a onclick=\"javascript:parent.fillPickUpReqt('" .$jdo."', '', $max_idx, 'moreoption', this);\" title=\"".$lang->get("more")."\"><b>+".$lang->get("more")."</b></a>"; } else{ $out .= "<a onclick=\"javascript:parent.fillPickUpReqt('" .$jdo."', '', $shortFieldCount, 'moreoption', this);\" title=\"-".$lang->get("more")."\" style=\"color:#ffffff;background-color:#1730FD;\"><b>-".$lang->get("more")."</b></a>"; } $out .= "</td></tr>"; $hmorig = array(); if(true){ foreach($_REQUEST as $k=>$v){ if(startsWith($k,"pnsk")){ $hmorig[substr($k,4)] = $v; } else if(startsWith($k, 'parent')){ # Attention! parentid $k2 = $v; $hmorig[$k2] = $_REQUEST[$k2]; } } for($hmi=$min_idx; $hmi<=$max_idx; $hmi++){ $field = $gtbl->getField($hmi); if($field == null | $field == '' || $field == 'id'){ continue; } $fielddf = $gtbl->getDefaultValue($field); if($fielddf != ''){ $tmparr = explode(":", $fielddf); if($tmparr[0] == 'request'){ # see xml/info_attachfiletbl.xml $hmorig[$field] = $_REQUEST[$tmparr[1]]; } else{ $hmorig[$field] = $tmparr[0]; # see xml/tuanduitbl.xml } } } } if($hmorig[0]){ $hmorig = $hmorig[1][0]; } # narrow down filter, Fri Apr 16 13:31:50 UTC 2021 $navi = new PageNavi(); $pageCondi = $navi->getCondition($gtbl, $user); $pageCondiVal = $pageCondi; for($hmi=$min_idx; $hmi<=$max_idx;$hmi++){ $field = $gtbl->getField($hmi); if(inString($field, $pageCondi)){ $tmpV = $gtbl->get($field); $pickup->set($field, $tmpV); $pageCondiVal .= '-'.$tmpV; } } $closedtr = 1; $opentr = 0; # just open a tr, avoid blank line, Sun Jun 26 10:08:55 CST 2016 $columni = 0; $my_form_cols = 4; $skiptag = $_CONFIG['skiptag']; for($hmi=$min_idx; $hmi<=$max_idx;$hmi++){ $field = $gtbl->getField($hmi); $fieldinputtype = $gtbl->getInputType($field); $filedtmpv = $_REQUEST['pnsk_'.$field]; if(isset($fieldtmpv)){ $hmorig[$field] = $fieldtmpv; } if($field == null || $field == ''){ continue; } #else if($field == 'password'){ else if(inString('password', $field) || inString('pwd', $field)){ $hmorig[$field] = ''; continue; } else if($fieldinputtype == 'file'){ continue; } # main fields if(true){ $options = ""; $prtFieldType = 'string'; $hasHitOption = 0; $optionListAll = $pickup->getOptionList($field, $fieldinputtype, $pageCondi, $pageCondiVal); $optionList = $optionListAll[0]; $prtFieldType = $optionListAll[1]; #debug("field:$field options:".serialize($optionList)); $opCount = count($optionList); if($opCount > 0){ $opi = 0; $lastopv = null; foreach($optionList as $ok=>$ov){ $urlParts = array(); if($fieldinputtype == 'select'){ $opv = $ov[$field.'_uniq_all']; # same with class/pickup $origopv = $opv; if($opv== ''){ $opv = '(Empty)'; } # === in case of '0' else{ $opv = str_replace('<', '&lt;', $opv); } $opv = $gtbl->getSelectOption($field, $opv, '', $needv=1, $isMultiple=0); $urlParts = fillPickUpReqt($jdo, $field, $origopv, 'inlist', $base62x); $options .= "<a href='javascript:void(0);' " ." onclick=\"javascript:parent.fillPickUpReqt('".$jdo."', '$field', '$origopv', 'inlist', this);\"" ." style=\"".$urlParts[2]."\">"; $options .= $urlParts[1].$opv.'('.$ov['icount'].')'; $options .= "</a> "; #debug(" select field:$field opv:$opv\n"); } else if($prtFieldType == 'string'){ $opv = $ov[$field.'_uniq_all']; # same with class/pickup if($opv== ''){ $opv = '(Empty)'; } # === in case of '0' else{ $opv = str_replace('<', '&lt;', $opv); } $origopv = $base62xTag.$base62x->encode($opv); $urlParts = fillPickUpReqt($jdo, $field, $origopv, 'containslist', $base62x); $options .= "<a href='javascript:void(0);' " ." onclick=\"javascript:parent.fillPickUpReqt('".$jdo."', '$field', '$origopv', 'containslist', this);\"" ." style=\"".$urlParts[2]."\">"; $options .= $urlParts[1].$opv; if(isset($ov['icount'])){ $options .= "(".$ov['icount'].")"; } $options .= "</a> "; } else if($prtFieldType == 'number'){ if(true){ $opv = $ov[$field]; if($opv === ''){ $opv = '0'; } # === in case of '0' if($lastopv !== null){ $origopv = $lastopv.'~'.$opv; $urlParts = fillPickUpReqt($jdo, $field, $origopv, 'inrangelist', $base62x); $options .= "<a href='javascript:void(0);' " ." onclick=\"javascript:parent.fillPickUpReqt('".$jdo."', '$field', '$origopv', 'inrangelist', this);\"" ." style=\"".$urlParts[2]."\">"; $options .= $urlParts[1].$lastopv."~".$ov[$field]; } else{ #$options .= "+~".$ov[$field]; # nothing < imin? } $options .= "</a> "; $lastopv = $ov[$field]; if($opi == $opCount-1){ $origopv = $lastopv.'~'; $urlParts = fillPickUpReqt($jdo, $field, $origopv, 'inrangelist', $base62x); $options .= "<a href='javascript:void(0);' " ." onclick=\"javascript:parent.fillPickUpReqt('".$jdo."', '$field', '$origopv', 'inrangelist', this);\"" ." style=\"".$urlParts[2]."\">"; $options .= $urlParts[1].$ov[$field]."~"; $options .= "</a> "; } } } else{ debug("unsupported prtFieldType:$prtFieldType from field:$field skip....\n"); } $opi++; if($hasHitOption == 0){ if(isset($urlParts[1]) && $urlParts[1] == '-'){ $hasHitOption = 1; } } } $reqv = Wht::get($_REQUEST, "pnsk$field"); if($reqv != '' && $hasHitOption == 0){ $opType = ""; $origReqv = $reqv; if($fieldinputtype == 'select'){ $opType = "inlist"; } else if($prtFieldType == 'string'){ $opType = "containslist"; $reqv = $base62xTag.$base62x->encode($reqv); } else if($prtFieldType == 'number'){ $opType = "inrangelist"; } $options .= "<a href='javascript:void(0);' " ." onclick=\"javascript:parent.fillPickUpReqt('".$jdo."', '$field', '$reqv', '$opType', this);\"" ." style=\"color:#ffffff;background-color:#1730FD;\">"; $options .= '-'.$origReqv; $options .= "</a> "; } } if($options != ''){ $out .= "<tr height=\"{$rowHeight}px\" valign=\"middle\" onmouseover=\"javascript:this.style.backgroundColor='" .$hlcolor."';\" onmouseout=\"javascript:this.style.backgroundColor='';\">"; $out .= "<td></td>"; $out .= "<td><b>".$gtbl->getCHN($field)."</b></td>"; $out .= "<td style='word-break:all;word-spacing:10px;line-height:25px;'> $options </td>"; $out .= "<td></td></tr>"; $rows++; $lastBlankTr = 0; $bgcolor = "#DCDEDE"; if($rows%2 == 0){ $bgcolor = ""; } } else{ #$pickupFieldCount++; #debug("\tfield:$field has no options. 1809191930. skip....\n"); } } $out .= $gtbl->getDelayJsAction($field); $columni++; if($columni % $colsPerRow == 0){ $out .= "</tr>"; $closedtr = 1; } if(true && $rows % 6 == 0 && $lastBlankTr == 0){ $out .= "<tr height=\"".($rowHeight/2)."px\" valign=\"middle\" onmouseover=\"javascript:this.style.backgroundColor='" .$hlcolor."';\" onmouseout=\"javascript:this.style.backgroundColor='';\" ><td style=\"border-top: 1px dotted #cccccc; " ."vertical-align:middle;\" colspan=\"".$my_form_cols."\"> </td> </tr>"; $lastBlankTr = 1; } if($rows >= $pickupFieldCount){ break; } } if(false){ $out .= "<tr height=\"10px\"><td style=\"border-top: 1px dotted #cccccc; vertical-align:middle;\" colspan=\"" .$my_form_cols."\"> </td></tr>"; } $out .= "<tr><td colspan=\"".$my_form_cols."\" align=\"center\">"; $out .= "<input type=\"hidden\" id=\"id\" name=\"id\" value=\"".$id."\"/>\n ".$hiddenfields."\n"; $out .= "</td></tr>"; $out .= "</table> </form> </fieldset> <br/>"; # # save as an alternative backup # use javascript in front-end instead. # function fillPickUpReqt($myurl, $field, $fieldv, $oppnsk, $base62x=null){ $newurl = $myurl; $urlParts = explode("&", $newurl); $hasReqK = false; $hasReqKop = false; $hasReqV = false; $tagPrefix = '+'; $stylestr = ''; $origFieldv = $fieldv; $reqVal = ''; $base62xTag = 'b62x.'; # for string only if($base62x == null){ $base62x = new Base62x(); } if(inList($oppnsk, 'inlist,containslist,inrangelist')){ #$fieldv = strtolower($fieldv); # why? $isString = false; if($oppnsk == 'containslist'){ $isString = true; } $urlPartsNew = array(); foreach($urlParts as $k=>$v){ $paraParts = explode("=", $v); if(count($paraParts) > 1){ $reqk = $paraParts[0]; $reqv = $paraParts[1]; if($reqk == "pnsk$field"){ #$reqv = strtolower($reqv); # why? if(true && $isString){ if(inString(',', $reqv)){ $tmpArr = explode(',', $reqv); foreach($tmpArr as $tmpk=>$tmpv){ if(!startsWith($tmpv, $base62xTag)){ $tmpArr[$tmpk] = $base62xTag.$base62x->encode($tmpv); } } $reqv = implode(',', $tmpArr); } else{ if(!startsWith($reqv, $base62xTag)){ $reqv = $base62xTag.$base62x->encode($reqv); } } } if($reqv != ''){ $reqVal = $reqv; } if(inList($fieldv, $reqv)){ $tmpArr = array(); if(is_array($reqv)){ $tmpArr=explode(',', $reqv); } foreach($tmpArr as $tmpk=>$tmpv){ if($tmpv == $fieldv){ unset($tmpArr[$tmpk]); # break; ? } } $reqv = implode(',', $tmpArr); $hasReqV = true; } else{ $reqv .= ",$fieldv"; } $hasReqK = true; } else if($reqk == "oppnsk$field"){ $reqv = $oppnsk; $hasReqKop = true; } $paraParts[0] = $reqk; $paraParts[1] = $reqv; } $v = implode('=', $paraParts); $urlPartsNew[$k] = $v; } #$newurl = implode('&', $urlParts); $newurl = implode('&', $urlPartsNew); if(!$hasReqK){ $newurl .= "&pnsk$field=$fieldv"; #$newurl .= "&pnsk$field=B62X.".Base62x::encode($fieldv); } if(!$hasReqKop){ $newurl .= "&oppnsk=$oppnsk"; } if($hasReqV){ $tagPrefix = '-'; $stylestr = 'color:#ffffff;background-color:#1730FD;'; } else{ if($reqVal != ''){ #debug("found reqVal:$reqVal not in optionList."); } } } else{ debug("Unknown oppnsk:$oppnsk. 1809210905. \n"); } $newurl .= "&act=list"; #debug("fillPickUpUrl result: newurl:$newurl tagprefix:$tagPrefix\n"); return array($newurl, $tagPrefix, $stylestr); } ?> <file_sep>/extra/xdirectory.php <?php # directory management module # <EMAIL> on Sun Jan 31 10:22:15 CST 2016 # updts by <EMAIL>, Tue Apr 23 13:35:30 HKT 2019 #$isoput = false; $isheader = 0; $_REQUEST['isheader'] = $isheader; #$out_header = $isheader; require("../comm/header.inc.php"); include("../comm/tblconf.php"); include_once($appdir."/class/xdirectory.class.php"); if(!isset($xdirectory)){ $xdirectory = new XDirectory($tbl); } $inframe = $_REQUEST['inframe']; if($inframe == ''){ # re open in an iframe window $myurl = $rtvdir."/extra/xdirectory.php?inframe=1&".$_SERVER['QUERY_STRING'].'&'.SID.'='.$sid; $out .= "<iframe id=\"linktblframe\" name=\"linktblframe\" width=\"100%\" height=\"100%\" src=\"" .$myurl."&isheader=0\" frameborder=\"0\"></iframe>"; } else{ $dirLevelLength = 2; # main actions $out .= ' <script type="text/javascript" src="'.$rtvdir.'/comm/jquery-3.6.1.min.js" charset="utf-8"></script> <style type="text/css"> .node ul{ margin-left:-25px; } .node ul li{ list-style-type:none; } .node .node{ display:none; } .node .tree{ height:24px; line-height:24px; } .ce_ceng_close{ background:url(../img/cd_zd1.png) left center no-repeat; padding-left: 15px; } .ce_ceng_open{ background:url(../img/cd_zd.png) left center no-repeat; } </style> '; $out .= ""; $icode = $_REQUEST['icode']; $iname = $_REQUEST['iname']; $rootId = '00'; $parentCode = Wht::get($_REQUEST, 'parentcode'); if(inString('-', $parentCode)){ //- 0100-止疼药2级 $tmpArr = explode('-', $parentCode); $parentCode = $tmpArr[0]; } else if(inString('THIS_', $parentCode)){ //- THIS_belongto $parentCode = $rootId; } $xdirectory->set('parentCode', $parentCode); $expandList = array(); if(strlen($parentCode) > $dirLevelLength){ $codeV = ''; $codeArr = str_split(substr($parentCode,0,strlen($parentCode)-$dirLevelLength), $dirLevelLength); foreach($codeArr as $k=>$v){ $codeV .= $v; $expandList[$codeV] = $codeV; } } #debug("extra/xdir: parentcode:$parentCode expandList:".serialize($expandList)); $list = array(); $sqlCondi = "1=1 order by $icode asc"; $hm = $xdirectory->getBy("$icode, $iname", "$sqlCondi", $withCache=array("key"=>"xdir-$tbl-$sqlCondi")); if($hm[0]){ $hm = $hm[1]; } else{ $hm = array(0=>array("$icode"=>$rootId, "$iname"=>'所有/All')); } #debug($hm); # added by <EMAIL>, Sat May 22 21:29:53 CST 2021 $sortArr = $xdirectory->sortDir($hm, $icode, $iname); #debug("sortArr:"); debug($sortArr); $hm = $sortArr; if(1){ foreach($hm as $k=>$v){ if($v[$icode] == ''){ $v[$icode] = '00'; # init hierarchy } $list[$v[$icode]] = $v[$iname]; } $out .= '<style type="text/css">'; foreach($list as $k=>$v){ $out .= '#nodelink'.$k.'{ width:168px; height:20px; display:none; }'; } $out .= '</style>'; $str = $xdirectory->getList($list, $dirLevelLength); $out .= $str; } $targetField = Wht::get($_REQUEST, 'targetfield'); $imode = Wht::get($_REQUEST, "imode"); if($imode == 'read' && $targetField != $icode){ $icode = $targetField; } $out .= " <script type=\"text/javascript\"> var current_link_field='".$icode ."'; var tmpTimer0859=window.setTimeout(function(){parent.sendLinkInfo('".$parentCode."','w', current_link_field);}, 1*1000);</script> "; $out .= ' <script type="text/javascript"> $(".tree").each(function(index, element) { if($(this).next(".node").length>0){ $(this).addClass("ce_ceng_close"); } else{ $(this).css("padding-left","15px"); } }); '; foreach($expandList as $k=>$v){ $out .= ' var ull = $("#'.$v.'").next(".node"); ull.slideDown(); $("#'.$v.'").addClass("ce_ceng_open"); ull.find(".ce_ceng_close").removeClass("ce_ceng_open"); '; } $out .= ' $(".tree").click(function(e){ var ul = $(this).next(".node"); if(ul.css("display")=="none"){ ul.slideDown(); $(this).addClass("ce_ceng_open"); ul.find(".ce_ceng_close").removeClass("ce_ceng_open"); }else{ ul.slideUp(); $(this).removeClass("ce_ceng_open"); ul.find(".node").slideUp(); ul.find(".ce_ceng_close").removeClass("ce_ceng_open"); } }); '; $out .= ' //- disp menu options function xianShi(nodeId) { document.getElementById("nodelink"+nodeId).style.display="inline"; } //- hide options function yinCang(nodeId) { document.getElementById("nodelink"+nodeId).style.display="none"; } //- highlights selected var lastSelectedK = \'\'; function changeBgc(nodeId){ var myObj = document.getElementById(nodeId); if(myObj){ myObj.style.backgroundColor=\'silver\'; } if(lastSelectedK != \'\' && lastSelectedK != nodeId){ myObj = document.getElementById(lastSelectedK); if(myObj){ myObj.style.backgroundColor=\'\'; } } lastSelectedK = nodeId; } '; # positioning to selected, 17:42 6/11/2020 if($parentCode != ''){ $out .= 'if(true){ var tmpReloadTimer=window.setTimeout(function(){ var tmpObj=document.getElementById("'.$parentCode.'"); if(tmpObj){tmpObj.scrollIntoView(); parent.scrollTo(0,10);}}, 1*1000);};'; } $out .='</script>'; } require("../comm/footer.inc.php"); ?><file_sep>/extra/insitesearch.php <?php # In-site searching # Xenxin<EMAIL> # Wed May 30 15:40:33 CST 2018 require("../comm/header.inc.php"); include("../comm/tblconf.php"); include_once($appdir."/class/base62x.class.php"); include_once($appdir."/class/insitesearch.class.php"); # variables $MAX_SUCC_COUNT = 5; $MAX_FIELD_COUNT = 99999; $isep = "::"; $time_bgn = time(); $gtbl2 = $gtbl; if($testDb != ''){ $args = array('db'=>$_CONFIG['maindb']); $gtbl2 = new GTbl($tbl, $args, $sep); debug($gtbl2); } $iss = new InSiteSearch(); $issubmit = Wht::get($_REQUEST, 'issubmit'); $issout .= serialize($_REQUEST); $isskw = Wht::get($_REQUEST, 'isskw'); $issLastId = Wht::get($_REQUEST, 'isslastid'); if($issLastId == ''){ $issLastId = 0; } # max fields return # module path $module_path = ''; include_once($appdir."/comm/modulepath.inc.php"); # actions if($issubmit == 1 && $isskw != ''){ if($act == 'init'){ # init a searcho } else{ $resultList = array(); $succCount = 0; $succTblList = array(); $tbl_all_count = 0; $fieldi = 0; $skipFieldI = $issLastId; $hm = $iss->execBy($sql="select id, idb, itbl, ifield from ".$iss->getTbl() ." where 1=1 order by icount desc, id desc limit 0, ".$MAX_FIELD_COUNT, null, $withCache=array('key'=>'iss-fields-'.$issLastId)); if($hm[0]){ $hm = $hm[1]; foreach($hm as $k=>$v){ if($fieldi++ < $skipFieldI){ #debug("fieldi:$fieldi less than $issLastId, skip next..."); continue; } $issLastId++; # $v['id']; $idb = $v['idb']; $itbl = $v['itbl']; $ifield = $v['ifield']; $hm2 = $iss->execBy($sql2="select $ifield from $itbl where $ifield like '%$isskw%' limit 3", null, $withCache=array('key'=>"iss-search-$tbl-$ifield-$isskw")); if($hm2[0]){ $hm2 = $hm2[1]; foreach($hm2 as $k2=>$v2){ $resultList[$idb.$isep.$itbl.$isep.$ifield] = $v2; } $succTblList[] = $itbl; $succCount++; #debug("read succ from $itbl-$ifield, $succCount / $issLastId / $sql2 / hm2:".serialize($hm2)); } else{ #debug("read failed from $itbl-$ifield, skip...$issLastId "); } if($succCount > $MAX_SUCC_COUNT){ debug("insitesearch succCount reached, exit now..."); break; } $tbl_all_count++; } } else{ debug("read iss fields failed. 201805310746."); } $data['result_list'] = $resultList; $data['isslastid'] = $issLastId; $moduleNameList = array(); if(count($succTblList) > 0){ $moduleList = implode("','", $succTblList); $hm = $iss->execBy($sql3="select * from ".$_CONFIG['tblpre']."info_menulist " ." where modulename in ('$moduleList') order by id", null, $withCache=array('key'=>'iss-read-module-path-'.$moduleList)); if($hm[0]){ $hm = $hm[1]; foreach($hm as $k=>$v){ $moduleNameList[$v['thedb'].$isep.$v['modulename']] = $v; } #debug($moduleNameList); } else{ debug("read modulename failed. 201805311254."); } } $data['module_list'] = $moduleNameList; } } else if($act == 'clickreport'){ $objId = Wht::get($_REQUEST, 'objid'); $fieldArr = explode($isep, $objId); debug("objId:[$objId] fieldArr:".serialize($fieldArr)); $imd5 = md5( implode("\t\t", $fieldArr) ); $hm = $iss->execBy($sql="update ".$iss->getTbl() ." set icount=icount+1 where imd5='$imd5' limit 1", null, null); if($hm[0]){ debug("icount++ succ with sql:$sql\n"); } else{ debug("icount++ failed with sql:$sql\n"); } $fmt = 'json'; $_REQUEST['fmt'] = $fmt; $smttpl = ''; } else{ # prepare form data } $time_all_cost = time() - $time_bgn; # output $smt->assign('welcomemsg',$welcomemsg); $smt->assign('isheader', $isheader); $smt->assign('out_header', $out_header); $smt->assign('out_footer', $out_footer); $smt->assign('rtvdir', $rtvdir); $smt->assign('ido', $ido); $smt->assign('jdo', $jdo); $smt->assign('url', $url); $smt->assign('sid', $sid); $smt->assign('rtvdir', $rtvdir); $smt->assign('output', $out); $smt->assign('issout',$issout); $smt->assign('issubmit', $issubmit); $smt->assign('levelcode', $levelcode); $smt->assign('modulepath', $module_path); $smt->assign('isskw', $isskw); $smt->assign('isep', $isep); $smt->assign('max_last_id', 0); # starting point next $smt->assign('tbl_all_count', $tbl_all_count+1); $smt->assign('time_all_cost', $time_all_cost); $smt->assign('act', $act); #tpl if($fmt == ''){ $smttpl = getSmtTpl(__FILE__,$act=''); $smttpl = 'insitesearch.html'; } else{ #debug("output $fmt format only...."); } require("../comm/footer.inc.php"); ?> <file_sep>/class/pickup.class.php <?php /* PickUp class * v0.1, * <EMAIL>, hotmail, gmail}.com * Wed Sep 19 CST 2018 */ if(!defined('__ROOT__')){ define('__ROOT__', dirname(dirname(__FILE__))); } require_once(__ROOT__.'/inc/webapp.class.php'); class PickUp extends WebApp{ const SID = 'sid'; const PICK_TOP_N = 12; const PICK_MAX_FIELD_LENGTH = 12; var $ver = 0.01; var $fieldList = array(); # public function __construct($args=null){ #$this->setTbl(GConf::get('tblpre').'mytbl'); //- init parent parent::__construct($args); $this->currTime = date("Y-m-d H:i:s", time()); } # public function __destruct(){ # @todo } # public methods # get option list by field public function getOptionList($field, $fieldinputtype, $pageCondi, $pageCondiVal){ $options = array(); $hmfield = $this->fieldList; if(count($hmfield) < 1){ $this->fieldList = $this->get('fieldlist'); } $fieldtype = $hmfield[$field]; $tbl = $this->getTbl(); $myId = $this->get('myid'); $prtFieldType = 'string'; $isTimeField = false; if(inString('time', $fieldtype) || inString("date", $fieldtype)){ $isTimeField = true; } if($pageCondi == null || $pageCondi == ''){ $pageCondi = '1=1'; } #debug("class/pickup: pageCondi:$pageCondi"); $fieldDefineLength = $this->_getFieldDefineLength($field, $fieldtype); if($fieldDefineLength > self::PICK_MAX_FIELD_LENGTH * 20){ # why 20? <255? #debug("\tfield:$field has too long:$fieldDefineLength skip....\n"); } else if(inString("char", $fieldtype) || $fieldinputtype == 'select'){ $fieldUniq = $field.'_uniq_all'; $hm = $this->execBy("select substr($field, 1, ".self::PICK_MAX_FIELD_LENGTH .") as $fieldUniq, count($myId) as icount from $tbl " ." where $pageCondi group by $fieldUniq order by icount desc limit ".self::PICK_TOP_N, null, $withCache=array('key'=>"read-pickup-$tbl-$field-$pageCondiVal")); if($hm[0]){ $options = $hm[1]; } #debug("\t read tbl:$tbl field:$field type:$fieldtype hm:[".serialize($hm)."]"); $prtFieldType = 'string'; } else if($field == $myId || $isTimeField|| inString('int', $fieldtype) || inString('decimal', $fieldtype) || inString('float', $fieldtype) || inString('double', $fieldtype)){ $imax = 1; $imin = 0; $hm = $this->execBy("select max($field) as imax, min($field) as imin from $tbl " ." where $pageCondi", null, $withCache=array('key'=>"read-pickup-$tbl-$field-$pageCondiVal")); if($hm[0]){ $hm = $hm[1][0]; if($isTimeField){ $imax = strtotime($hm['imax']); }else{ $imax = $hm['imax']; } if($isTimeField){ $imin = strtotime($hm['imin']); }else{ $imin = $hm['imin']; } } $istep = ($imax - $imin) / self::PICK_TOP_N; $valueUniq = array(); for($i=$imin; $i<$imax; $i+=$istep){ if($imin > 1 || $field == $myId || inString('int', $fieldtype)){ $val = ceil($i); if($isTimeField){ $val = date("Y-m-d", $val); } if(isset($valueUniq[$val])){ # @todo } else{ $options[] = array($field=>$val); $valueUniq[$val] = 1; } } else{ $val = $i; if($isTimeField){ $val = date("Y-m-d", $val); } else{ $val = sprintf("%0.1f", $val); } $options[] = array($field=>$val); } } #debug("\t read tbl:$tbl field:$field type:$fieldtype imax:$imax imin:$imin istep:$istep hm:[".serialize($options)."]"); $prtFieldType = 'number'; } else{ debug("unsupported tbl:$tbl field:$field fieldtype:$fieldtype. 1809191556."); } $options = array($options, $prtFieldType); return $options; } # private methods # private function _getFieldDefineLength($field, $fieldtype){ $len = 0; if(preg_match("/char\(([0-9]+)\)/", $fieldtype, $matchArr)){ $len = $matchArr[1]; #debug("found char f:$field length:$len with fieldtype:[$fieldtype]\n"); } return $len; } # private function _sayHi(){ $rtn = ''; return $rtn; } } ?> <file_sep>/gmis.tables.sql ---- gmis tables, 201908; to sep in install script; drop table if exists gmis_filedirtbl; CREATE TABLE `gmis_filedirtbl` ( `id` int(12) NOT NULL AUTO_INCREMENT, `filename` char(128) NOT NULL DEFAULT '' COMMENT 'file or dir name', `parentname` char(254) NOT NULL DEFAULT '' COMMENT 'file or dir path', `pparentname` varchar(768) NOT NULL DEFAULT '' COMMENT 'file or dir path uplevel', `idesc` char(255) NOT NULL DEFAULT '', `itype` tinyint(1) NOT NULL DEFAULT '0' COMMENT '0:file, 1:dir', `filetype` char(64) NOT NULL DEFAULT '' COMMENT 'mime type', `filesize` int(12) NOT NULL DEFAULT '0' COMMENT 'KB', `filepath` char(255) NOT NULL DEFAULT '' COMMENT 'file system dir', `ioperator` tinyint(1) NOT NULL DEFAULT '0', `inserttime` datetime NOT NULL DEFAULT '1001-01-01 00:00:01', `updatetime` datetime NOT NULL DEFAULT '1001-01-01 00:00:01', `parentid` int(12) NOT NULL DEFAULT '0', PRIMARY KEY (`id`), UNIQUE KEY `key2` (`parentname`,`filename`), KEY `key3` (`filename`), KEY `key4` (`filetype`) ); drop table if exists `gmis_fin_operatelogtbl`; CREATE TABLE `gmis_fin_operatelogtbl` ( `id` int(11) NOT NULL AUTO_INCREMENT, `parentid` int(11) NOT NULL DEFAULT '0', `parenttype` char(32) NOT NULL DEFAULT '', `userid` int(11) NOT NULL DEFAULT '0', `actionstr` char(255) NOT NULL DEFAULT '', `inserttime` datetime NOT NULL DEFAULT '1001-01-01 00:00:00', PRIMARY KEY (`id`) ); drop table if exists `gmis_fin_todotbl`; CREATE TABLE `gmis_fin_todotbl` ( `id` int(11) NOT NULL AUTO_INCREMENT, `pid` int(12) NOT NULL DEFAULT '0', `taskname` char(128) NOT NULL DEFAULT '', `tasktype` tinyint(1) NOT NULL DEFAULT '0', `triggerbyparent` char(64) NOT NULL DEFAULT '', `triggerbyparentid` int(11) NOT NULL DEFAULT '0', `togroup` mediumint(4) NOT NULL DEFAULT '0', `touser` mediumint(4) NOT NULL DEFAULT '0', `inserttime` datetime NOT NULL DEFAULT '1001-01-01 00:00:00', `operator` char(32) NOT NULL DEFAULT '', `istate` tinyint(1) NOT NULL DEFAULT '1', `taskmemo` varchar(2048) NOT NULL DEFAULT '', `taskreply` varchar(1024) NOT NULL DEFAULT '', `taskfile` char(255) NOT NULL DEFAULT '', `updatetime` datetime NOT NULL DEFAULT '1001-01-01 00:00:00', PRIMARY KEY (`id`), KEY `k2` (`pid`), KEY `k3` (`touser`), KEY `k4` (`triggerbyparentid`) ); drop table if exists `gmis_info_attachefiletbl`; CREATE TABLE `gmis_info_attachefiletbl` ( `id` int(11) NOT NULL AUTO_INCREMENT, `userid` int(11) NOT NULL DEFAULT '0', `parentid` int(11) NOT NULL DEFAULT '0', `parenttype` char(32) NOT NULL DEFAULT '', `filename` char(64) NOT NULL DEFAULT '', `filetype` char(16) NOT NULL DEFAULT '', `filesize` int(11) NOT NULL DEFAULT '0', `filepath` char(64) NOT NULL DEFAULT '', `istate` tinyint(4) NOT NULL DEFAULT '1', `updatetime` datetime NOT NULL DEFAULT '1001-01-01 00:00:00', `operator` char(32) NOT NULL DEFAULT '', PRIMARY KEY (`id`), UNIQUE KEY `id` (`id`) ); drop table if exists `gmis_info_grouptbl`; CREATE TABLE `gmis_info_grouptbl` ( `id` int(11) NOT NULL AUTO_INCREMENT, `groupname` char(32) NOT NULL DEFAULT '', `grouplevel` tinyint(1) NOT NULL DEFAULT '0', `inserttime` datetime NOT NULL DEFAULT '1001-01-01 00:00:00', `operator` char(32) NOT NULL DEFAULT '', `istate` tinyint(1) NOT NULL DEFAULT '1', PRIMARY KEY (`id`), UNIQUE KEY `key2` (`groupname`), UNIQUE KEY `key3` (`grouplevel`) ); drop table if exists `gmis_info_helptbl`; CREATE TABLE `gmis_info_helptbl` ( `id` int(11) NOT NULL AUTO_INCREMENT, `title` char(255) NOT NULL DEFAULT '', `content` text NOT NULL, `inserttime` datetime NOT NULL DEFAULT '1001-01-01 00:00:00', `operator` char(32) NOT NULL DEFAULT '', `orderno` tinyint(1) NOT NULL DEFAULT '0', `click` mediumint(4) NOT NULL DEFAULT '0', `reply` mediumint(4) NOT NULL DEFAULT '0', `isfaq` tinyint(1) NOT NULL DEFAULT '0', PRIMARY KEY (`id`), UNIQUE KEY `key2` (`title`) ); drop table if exists `gmis_info_menulist`; CREATE TABLE `gmis_info_menulist` ( `id` int(11) NOT NULL AUTO_INCREMENT, `linkname` char(24) NOT NULL DEFAULT '', `levelcode` char(48) NOT NULL DEFAULT '', `modulename` char(48) NOT NULL DEFAULT '', `dynamicpara` char(128) NOT NULL DEFAULT '', `istate` tinyint(1) NOT NULL DEFAULT '1', `operator` char(24) NOT NULL DEFAULT '', `updatetime` datetime NOT NULL DEFAULT '1001-01-01 00:00:00', `disptitle` char(24) NOT NULL DEFAULT '', `thedb` char(24) NOT NULL DEFAULT '', PRIMARY KEY (`id`), UNIQUE KEY `singlecode` (`levelcode`) ); drop table if exists `gmis_info_objectfieldtbl`; CREATE TABLE `gmis_info_objectfieldtbl` ( `id` int(11) NOT NULL AUTO_INCREMENT, `parentid` int(11) NOT NULL DEFAULT '0', `fieldname` char(32) NOT NULL DEFAULT '', `fieldtype` char(16) NOT NULL DEFAULT '0', `fieldlength` mediumint(4) NOT NULL DEFAULT '32', `defaultvalue` char(32) NOT NULL DEFAULT '', `otherset` char(32) NOT NULL DEFAULT '', `fieldmemo` char(255) NOT NULL DEFAULT '', `updatetime` datetime NOT NULL DEFAULT '1001-01-01 00:00:00', `operator` char(32) NOT NULL DEFAULT '', `chnname` char(64) NOT NULL DEFAULT '', PRIMARY KEY (`id`), UNIQUE KEY `key2` (`parentid`,`fieldname`) ); drop table if exists `gmis_info_objectgrouptbl`; CREATE TABLE `gmis_info_objectgrouptbl` ( `id` int(11) NOT NULL AUTO_INCREMENT, `groupname` char(32) NOT NULL DEFAULT '', `grouplevel` tinyint(1) NOT NULL DEFAULT '0', `inserttime` datetime NOT NULL DEFAULT '1001-01-01 00:00:00', `operator` char(32) NOT NULL DEFAULT '', `istate` tinyint(4) NOT NULL DEFAULT '0', PRIMARY KEY (`id`), UNIQUE KEY `key2` (`groupname`), UNIQUE KEY `key3` (`grouplevel`) ); drop table if exists `gmis_info_objectindexkeytbl`; CREATE TABLE `gmis_info_objectindexkeytbl` ( `id` int(11) NOT NULL AUTO_INCREMENT, `parentid` int(11) NOT NULL DEFAULT '0', `indexname` char(32) NOT NULL DEFAULT '', `indextype` char(32) NOT NULL DEFAULT '', `onfield` char(64) NOT NULL DEFAULT '', PRIMARY KEY (`id`), UNIQUE KEY `key2` (`parentid`,`indexname`) ); drop table if exists `gmis_info_objecttbl`; CREATE TABLE `gmis_info_objecttbl` ( `id` mediumint(6) NOT NULL AUTO_INCREMENT, `objname` char(32) NOT NULL DEFAULT '', `tblname` char(32) NOT NULL DEFAULT '', `objgroup` tinyint(1) NOT NULL DEFAULT '0', `tblfield` char(254) NOT NULL, `tblindex` char(254) NOT NULL DEFAULT '', `istate` tinyint(1) NOT NULL DEFAULT '1', `addtodesktop` tinyint(1) NOT NULL DEFAULT '0', `operator` char(32) NOT NULL DEFAULT '', `updatetime` datetime NOT NULL, `inserttime` datetime NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `key2` (`tblname`) ); drop table if exists `gmis_info_operateareatbl`; CREATE TABLE `gmis_info_operateareatbl` ( `id` int(11) NOT NULL AUTO_INCREMENT, `areacode` char(16) NOT NULL DEFAULT '', `areaname` char(32) NOT NULL DEFAULT '', `inserttime` datetime NOT NULL DEFAULT '1000-01-01 00:00:00', `operator` char(32) NOT NULL DEFAULT '', `istate` tinyint(1) NOT NULL DEFAULT '1', PRIMARY KEY (`id`), UNIQUE KEY `key2` (`areacode`) ); drop table if exists `gmis_info_siteusertbl`; CREATE TABLE `gmis_info_siteusertbl` ( `id` int(11) NOT NULL AUTO_INCREMENT, `email` char(32) NOT NULL DEFAULT '', `username` char(24) NOT NULL DEFAULT '', `realname` char(8) NOT NULL, `password` char(64) NOT NULL DEFAULT '', `avatar` char(8) NOT NULL, `company` char(200) NOT NULL, `gender` int(2) NOT NULL, `mobile` char(12) NOT NULL, `qq` int(12) NOT NULL, `money` char(8) NOT NULL, `score` char(8) NOT NULL, `zipcode` char(6) NOT NULL, `address` char(200) NOT NULL, `city_id` char(4) NOT NULL, `enable` int(2) NOT NULL, `manager` int(2) NOT NULL, `secret` char(16) NOT NULL, `recode` char(16) NOT NULL, `ip` char(64) NOT NULL DEFAULT '', `updatetime` datetime NOT NULL DEFAULT '1001-01-01 00:00:00', `inserttime` datetime NOT NULL DEFAULT '1001-01-01 00:00:00', `istate` int(2) NOT NULL, UNIQUE KEY `email` (`email`), KEY `id` (`id`) ); drop table if exists `gmis_info_toolsettbl`; CREATE TABLE `gmis_info_toolsettbl` ( `id` int(11) NOT NULL AUTO_INCREMENT, `iname` char(64) NOT NULL DEFAULT '', `iurl` char(255) NOT NULL DEFAULT '', `istate` tinyint(1) NOT NULL DEFAULT '1', `inserttime` datetime NOT NULL DEFAULT '0001-01-01 00:00:01', `updatetime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `ioperator` char(32) NOT NULL DEFAULT '', PRIMARY KEY (`id`), UNIQUE KEY `uk1` (`iname`), KEY `ik1` (`istate`) ); drop table if exists `gmis_info_usertbl`; CREATE TABLE `gmis_info_usertbl` ( `id` int(11) NOT NULL AUTO_INCREMENT, `password` char(64) NOT NULL DEFAULT '', `realname` char(32) NOT NULL DEFAULT '', `email` char(32) NOT NULL DEFAULT '', `usergroup` tinyint(1) NOT NULL DEFAULT '0', `branchoffice` char(16) NOT NULL DEFAULT '', `operatearea` char(255) NOT NULL DEFAULT '', `inserttime` datetime NOT NULL DEFAULT '1001-01-01 00:00:00', `updatetime` datetime NOT NULL DEFAULT '1001-01-01 00:00:00', `istate` tinyint(1) NOT NULL DEFAULT '1', `operator` char(32) NOT NULL DEFAULT '', PRIMARY KEY (`id`), UNIQUE KEY `uniemail` (`email`) ); drop table if exists `gmis_insitesearchtbl`; CREATE TABLE `gmis_insitesearchtbl` ( `id` int(12) NOT NULL AUTO_INCREMENT, `idb` char(24) NOT NULL DEFAULT '', `itbl` char(64) NOT NULL DEFAULT '', `ifield` char(64) NOT NULL DEFAULT '', `ivalue` varchar(255) NOT NULL DEFAULT '', `imd5` char(32) NOT NULL DEFAULT '' COMMENT 'md5(idb, itbl, ifield, ivalue)', `icount` mediumint(8) NOT NULL DEFAULT '1', `updatetime` datetime NOT NULL DEFAULT '1001-01-01 00:00:01', PRIMARY KEY (`id`), UNIQUE KEY `key2` (`imd5`), KEY `k3` (`ivalue`) ); drop table if exists `gmis_issblackwhitetbl`; CREATE TABLE `gmis_issblackwhitetbl` ( `id` int(12) NOT NULL AUTO_INCREMENT, `idb` char(24) NOT NULL DEFAULT '', `itbl` char(64) NOT NULL DEFAULT '', `ifield` char(64) NOT NULL DEFAULT '', `isblack` tinyint(1) NOT NULL DEFAULT '0', `iswhite` tinyint(1) NOT NULL DEFAULT '0', `istate` tinyint(1) NOT NULL DEFAULT '1', `updatetime` datetime NOT NULL DEFAULT '1001-01-01 00:00:01', PRIMARY KEY (`id`), UNIQUE KEY `key2` (`idb`,`itbl`,`ifield`) ); drop table if exists `gmis_mydesktoptbl`; CREATE TABLE `gmis_mydesktoptbl` ( `id` int(11) NOT NULL AUTO_INCREMENT, `userid` int(11) NOT NULL DEFAULT '0', `useremail` char(32) NOT NULL DEFAULT '', PRIMARY KEY (`id`) ); drop table if exists `gmis_mynotetbl`; CREATE TABLE `gmis_mynotetbl` ( `id` int(11) NOT NULL AUTO_INCREMENT, `content` text COLLATE utf8mb4_general_ci NOT NULL, `notecode` char(24) COLLATE utf8mb4_general_ci NOT NULL DEFAULT '', `inserttime` datetime NOT NULL DEFAULT '1001-01-01 00:00:00', `updatetime` datetime NOT NULL DEFAULT '1001-01-01 00:00:00', `istate` char(10) COLLATE utf8mb4_general_ci NOT NULL, `operator` varchar(10) COLLATE utf8mb4_general_ci NOT NULL, PRIMARY KEY (`id`), KEY `k3` (`inserttime`) ); drop table if exists `gmis_useraccesstbl`; CREATE TABLE `gmis_useraccesstbl` ( `id` int(11) NOT NULL AUTO_INCREMENT, `userid` int(11) NOT NULL DEFAULT '0', `usergroup` int(11) NOT NULL DEFAULT '0', `objectid` mediumint(6) NOT NULL DEFAULT '0', `objectfield` char(255) NOT NULL DEFAULT '', `objectgroup` tinyint(1) NOT NULL DEFAULT '0', `accesstype` tinyint(1) NOT NULL DEFAULT '0', `operatelog` char(64) NOT NULL, `istate` tinyint(1) NOT NULL DEFAULT '1', `inserttime` datetime NOT NULL DEFAULT '1001-01-01 00:00:00', `memo` char(15) NOT NULL, `operator` char(6) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `key2` (`userid`,`usergroup`,`objectid`,`objectgroup`,`objectfield`) ); drop table if exists `gmis_dict_infotbl`; CREATE TABLE `gmis_dict_infotbl` ( `id` int(12) NOT NULL AUTO_INCREMENT COMMENT 'primary key', `ikey` char(24) COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT 'dict key', `ivalue` char(64) COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT 'dict value', PRIMARY KEY (`id`) ); drop table if exists `gmis_dict_detailtbl`; CREATE TABLE `dict_detailtbl` ( `id` int NOT NULL AUTO_INCREMENT, `itype` char(24) NOT NULL DEFAULT '' COMMENT 'dict key code', `ikey` char(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT 'item name', `ivalue` char(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT 'item value', `iorder` int NOT NULL DEFAULT '0' COMMENT 'order num', `imemo` char(254) NOT NULL DEFAULT '' COMMENT 'desc for the ikey/ivalue.', PRIMARY KEY (`id`), UNIQUE KEY `k3` (`itype`,`ikey`,`ivalue`), KEY `k2` (`itype`) ); <file_sep>/extra/xianjinquan.php <?php # batchly generate xianjinquan # <EMAIL> on Sun Jan 31 10:22:15 CST 2016 # Mon May 13 13:07:32 HKT 2019 # require("../comm/header.inc.php"); $gtbl = new GTbl($tbl, array(), $elementsep); include("../comm/tblconf.php"); # main actions $out = ""; if($act == 'dobatch1'){ #$out .= "act:[$act] reqt:".serialize($_REQUEST); $out .= "<fieldset><legend> 批量生成促销现金券: 步骤2 </legend> <form id='addstepform' name='addstepform' action='extra/xianjinquan.php?sid=$sid&act=dobatch2&tbl=$tbl&db=$db' method='post'>"; $out .= "<p> 主题:".($sname=Wht::get($_REQUEST, 'sname'))." <input name='sname' type='hidden' value='".$sname."'/> </p>"; $out .= "<p> 面值:".($facevalue=intval(Wht::get($_REQUEST, 'facevalue')))." 元 <input name='facevalue' type='hidden' value='".$facevalue."'/> </p>"; $out .= "<p> 数量:".($icount=intval(Wht::get($_REQUEST, 'icount')))." 张 <input name='icount' type='hidden' value='".$icount."'/> </p>"; $out .= "<p> 绑定到商品Id:".($bind2productid=intval(Wht::get($_REQUEST, 'bind2productid')))." <input name='bind2productid' type='hidden' value='".$bind2productid."'/> </p>"; $out .= "<p> 绑定到商户Id:".($bind2storeid=intval(Wht::get($_REQUEST, 'bind2storeid')))." <input name='bind2storeid' type='hidden' value='".$bind2storeid."'/> </p>"; $out .= "<p> 有效截止日期:".($dendtime=Wht::get($_REQUEST, 'dendtime'))." <input name='dendtime' type='hidden' value='".$dendtime."'/> </p>"; $out .= " <p> <input type='button' name='rtnbtn' value='返回修改' onclick=\"javascript:GTAj.backGTAjax('contentarea','1');\"/> <input type='submit' value='确认无误, 批量生成' id='addmultistepsubmit' onclick=\"javascript:doActionEx(this.form.name,'contentarea');\"/></p> </form> </fieldset>"; } else if($act == 'dobatch2'){ $sname=Wht::get($_REQUEST, 'sname'); $facevalue=intval(Wht::get($_REQUEST, 'facevalue')); $icount=intval(Wht::get($_REQUEST, 'icount')); $bind2productid=intval(Wht::get($_REQUEST, 'bind2productid')); $bind2storeid=intval(Wht::get($_REQUEST, 'bind2storeid')); $dendtime=Wht::get($_REQUEST, 'dendtime'); $succi = 0; for($i=0; $i<$icount; $i++){ $scode = date('mdHis', time()).$i; $tmpsql = "insert into ".$tbl." set sname='$sname', scode='$scode', facevalue=$facevalue, dendtime='$dendtime', dinserttime=NOW(),bind2productid='".$bind2productid."',bind2storeid='".$bind2storeid."'"; $result = $gtbl->execBy($tmpsql); if($result[0]){ $succi++; } debug("extra/xinjinquan: ".$tmpsql." result:".serialize($result)); } $out .= "成功批量生成 $succi 张 $facevalue 元现金券! 请 <a href='javascript:window.location.reload();'>刷新浏览</a>."; } else{ $out .= "<fieldset><legend> 批量生成促销现金券: 步骤1 </legend> <form id='addstepform' name='addstepform' action='extra/xianjinquan.php?sid=$sid&act=dobatch1&tbl=$tbl&db=$db' method='post'>"; $out .= "<p> 主题:<input name='sname' style=\"width:260px\"/> </p>"; $out .= "<p> 面值:<input name='facevalue'/> <br/> 单位为元, 填写整数 如, 100, 50, 20, 10等 </p>"; $out .= "<p> 数量:<input name='icount'/> <br/> 共 ? 张, 填写整数 如, 100, 50, 20, 10等 </p>"; $out .= "<p> 绑定到商品Id:<input name='bind2productid'/> <br/> 只在浏览该商品时可领用,不填为所有 </p>"; $out .= "<p> 绑定到商户Id:<input name='bind2storeid'/> <br/> 只在浏览该商户的商品时可领用,不填为所有 </p>"; $out .= "<p> 有效截止日期:<input name='dendtime'/><br/>日期格式: YYYY-mm-dd , 如 2019-12-31 </p>"; $out .= " <p><input type='submit' value='确认, 下一步' id='addmultistepsubmit' onclick=\"javascript:doActionEx(this.form.name,'contentarea');\"/></p> </form> </fieldset>"; } # or $data['respobj'] = array('output'=>'content'); # module path $module_path = ''; include_once($appdir."/comm/modulepath.inc.php"); # without html header and/or html footer $isoput = false; require("../comm/footer.inc.php"); ?><file_sep>/act/insitesearchsort.v1.php <?php include_once($appdir.'/class/insitesearch.class.php'); $MIN_CHAR_LENGTH = 4; $MAX_CHAR_LENGTH = 255; $tblpre = $_CONFIG['tblpre']; $fieldBlackList = array( 'un_promotion_p2p_ios'=>array('activaterate'=>1), 'un_promotion'=>array('activaterate'=>1), 'un_promotion_p2p'=>array('activaterate'=>1), 'un_promotion_nopb'=>array('activaterate'=>1), 'un_promotion_cpcm'=>array('activaterate'=>1), 'un_promotion_sub'=>array('activaterate'=>1), 'un_promotion_ios'=>array('activaterate'=>1) ); $tblBlackList = array($tblpre.'insitesearchtbl'=>1, $tblpre.'info_objecttbl'=>1); #print_r($tblBlackList); $iss = new InSiteSearch(); # in-site search sorting if(true){ $issTblList = array(); $sql = "show tables"; $hm = $gtbl->execBy($sql, null, $withCache=array('key'=>$db.'-show-tables')); if($hm[0]){ $hm = $hm[1]; $issTblList = $hm; } else{ debug("read tables failed. 201805291213."); } # tables foreach($issTblList as $k=>$tmpTblArr){ $tmpTbl = $tmpTblArr['Tables_in_adSystem']; #debug("tbl:$tmpTbl seri:".serialize($tmpTblArr)); if(isset($tblBlackList[$tmpTbl])){ continue; } else if(inString('_temp', $tmpTbl) || inString('temp_', $tmpTbl)){ #debug($tmpMsg="found temp tmptbl:$tmpTbl, skip...\n"); #$out .= $tmpMsg; continue; } else if(inString('_old', $tmpTbl) || inString('old_', $tmpTbl)){ #debug($tmpMsg="found old tmptbl:$tmpTbl, skip...\n"); #$out .= $tmpMsg; continue; } else if(preg_match("/_[0-9]+$/", $tmpTbl)){ #debug($tmpMsg="found rotating tmptbl:$tmpTbl, skip...\n"); #$out .= $tmpMsg; continue; } $issFieldList = array(); $sql = "desc $tmpTbl"; $hm = $gtbl->execBy($sql, null, $withCache=array('key'=>$db.'-'.$tmpTbl.'-desc')); if($hm[0]){ $hm = $hm[1]; $issFieldList = $hm; } else{ debug("desc table:$tmpTbl failed. 201805291217."); } # fields $issTargetField = array(); foreach($issFieldList as $fk=>$tmpField){ $tmpFieldName = $tmpField['Field']; $tmpFieldType = $tmpField['Type']; $tmpName = strtolower($tmpFieldName); if(startsWith($tmpFieldType, 'char') || startsWith($tmpFieldType, 'varchar')){ if(isset($fieldBlackList[$tmpTbl][$tmpFieldName])){ #debug($tmpMsg="found field:$tmpFieldName for blacklist, skip...\n"); $out .= $tmpMsg; continue; } else if(checkSqlKeyword($tmpFieldName)){ #debug($tmpMsg="found field:$tmpFieldName for sql keyword, skip...\n"); #$out .= $tmpMsg; continue; } else if(inString('md5', $tmpName) || inString('url', $tmpName) || inString('size', $tmpName)){ #debug($tmpMsg="found field:$tmpFieldName for sql potential md5/url, skip...\n"); #$out .= $tmpMsg; continue; } else if(inString('password', $tmpName) || inString('pwd', $tmpName)){ continue; } else{ $tmpLen = 0; if(preg_match("/char\(([0-9]+)\)/", $tmpFieldType, $matchArr)){ $tmpLen = $matchArr[1]; if($tmpLen < $MIN_CHAR_LENGTH || $tmpLen > $MAX_CHAR_LENGTH){ #debug($tmpMsg="matchArr:".serialize($matchArr)." length:".$matchArr[1] # ." for $tmpFieldName, skip for out of range\n"); #$out .= $tmpMsg; } else{ $issTargetField[] = $tmpFieldName; #debug("$tmpTbl found field:$tmpFieldName for type:$tmpFieldType." # ." targetfield:".serialize($issTargetField)); } } else{ debug("char field:$tmpFieldName length failed."); } } } else{ #debug("$tmpTbl skip field:$tmpFieldName for type:$tmpFieldType."); } } # data if(count($issTargetField) > 0){ $sql = "select ".implode(',', $issTargetField)." from $tmpTbl limit 40, 20"; #debug($tmpMsg=" run sql:$sql\n"); $out .= $tmpMsg; $hm = $gtbl->execBy($sql, null, $withCache=array('key'=>$db.'-'.$tmpTbl.'-content-page-size=40??')); if($hm[0]){ $hm = $hm[1]; debug($tmpMsg="tbl-".($tbli++).":$tmpTl read val:".count($hm)." try to save...\n"); $out .= $tmpMsg; $result = $iss->saveInfo($hm, $itbl=$tmpTbl, $idb); $out .= $result; } } else{ debug($tmpMsg="no field left for tbl:$tmpTbl. 201805291224.\n"); $out .= $tmpMsg; } } } ?> <file_sep>/inc/sessiona.class.php <?php /* Session admin, handling users sessions in all apps * v0.1 * <EMAIL> * Sat Jul 23 09:50:58 UTC 2011 * Mon, 6 Mar 2017 21:59:03 +0800, implementing */ if(!defined('__ROOT__')){ define('__ROOT__', dirname(dirname(__FILE__))); } require_once(__ROOT__."/inc/config.class.php"); require_once(__ROOT__."/inc/socket.class.php"); require_once(__ROOT__."/inc/session.class.php"); #require_once(__ROOT__."/inc/class.connectionpool.php"); class SessionA { var $conf = null; var $sessionconn = null; //- construct function __construct($sessionConf = null){ $sessionConf = ($sessionConf==null ? 'Session_Master' : $sessionConf); $this->conf = new $sessionConf; $sessionDriver = GConf::get('sessiondriver'); $this->sessionconn = new $sessionDriver($this->conf); } //- function __destruct(){ $this->close(); } # get public function get($k){ # @todo $k = $this->_md5k($k); return $this->sessionconn->get($k); } # set public function set($k, $v){ # @todo $k = $this->_md5k($k); $rtn = $this->sessionconn->set($k, $v); return $rtn; } # delete public function rm($k){ $k = $this->_md5k($k); $rtn = $this->sessionconn->del($k); return $rtn; } # shorten key private function _md5k($k){ return strlen($k)>32 ? md5($k) : $k; } //- function close(){ # @todo, long conn? # need sub class to override with actual close handler $this->sessionconn->close(); return true; } } ?> <file_sep>/act/preset-vars.inc.php <?php # collect preset vars from request and foward to class/gtbl # <EMAIL>, Thu May 6 11:11:48 CST 2021 if(true){ $hmorig = array(); foreach($_REQUEST as $k=>$v){ if(startsWith($k,"pnsk")){ $hmorig[substr($k,4)] = $v; } else if(startsWith($k, 'parent')){ $k2 = $v; $hmorig[$k2] = $_REQUEST[$k2]; } } # sync pre-set params $gtbl->set(GTbl::RESULTSET, $hmorig); } ?> <file_sep>/README.md # gMIS 吉密斯 ![gmis](http://ufqi.com/blog/wp-content/uploads/2016/08/gmis-logo-201606.jpg) genral Management Information System (通用管理信息系统) It is a general Management Information System based on -GWA2 with powerful and configurable I/O. “In a demand-driven opinion, we faced increasing requests of creating enormous table-based management tools for operation teams in years of 2005-2010 at ChinaM, an affiliate of Telstra in Beijing. Those shared some common functions and most of them just needed to achieve basic goals (CURDLS) for a table. So we conducted many practices to find one to meet this kind of demand, for all, forever.” -NatureDNS: -gMIS , -吉密斯 (jí mì sī in Chinese pinyin), -鸡觅食 ![gMIS Architecture](http://ufqi.com/dev/gmis/page-relation.201303.v1.png) ### 站点/Official Page [gMIS 吉米斯](https://ufqi.com/dev/gmis/) @ufqi.com ### History This project has been started and pondered during the study in [Univ. of Derby](http://www.derby.ac.uk), 2011, and it is based on some observations and demands from [ChinaM](http://chinam.com), prior to 2010. In the short time in [Sina](http://weibo.com) Corp., and it has been created from top to down and the polishing work are continuing and lasting till now. ### Documents & References [gMIS Documents & Reference online](https://wadelau.github.io/gmis/index) [吉米斯在线参考文档](https://wadelau.github.io/gmis/index) ### Updates [-gMIS Updates](http://ufqi.com/blog/category/computer-tech/%E9%80%9A%E7%94%A8%E4%BF%A1%E6%81%AF%E7%AE%A1%E7%90%86%E7%B3%BB%E7%BB%9F/) [-gMIS更新官方Blog](http://ufqi.com/blog/category/computer-tech/%E9%80%9A%E7%94%A8%E4%BF%A1%E6%81%AF%E7%AE%A1%E7%90%86%E7%B3%BB%E7%BB%9F/) gMIS +自动层级目录 gMNIS +删除确认、删除异步及删除延时,delete confirm,aysnc and delay -gMIS更新:增加input2Select功能(3) -gmis更新201505,增加linkfieldcopy -gMIS 更新:字符串处理,op字段及github -gMIS更新:getSelectOption, getTblRotateName, 附件管理, toExecl等 -gMIS更新:增加默认主页和多层全路径 -gMIS更新兼容Strict SQL Mode .... ### 安装/Installation #### 自动安装脚本/Automatic installation script Please put all files under a sub directory and init from the script ./install.php #### 手工安装/Manual installation Download all its contents and put them under a single folder, then edit inc/config.inc to customize it. <file_sep>/act/trigger.php <?php #embedded in act/doaddmodi.php or act/dodelete.php #error_log(__FILE__.": act:[$act] id:[$id] triggers:[".$triggers=$gtbl->getTrigger($id)."]"); $IDTAG = 'id'; if(!isset($fieldlist)){ $fieldlist = array(); } #if($act == 'list-dodelete'){ if(true){ if($id != ''){ $tblTrigger = $gtbl->getTrigger(''); #error_log(__FILE__.": act:[$act] id:[$id] tbl triggers:[".$triggers=$gtbl->getTrigger()."]"); if($tblTrigger != ''){ $gtbl->setTrigger($IDTAG, $tblTrigger); debug("id triggers:[".$triggers=$gtbl->getTrigger($IDTAG)."]"); $fieldlist[] = $IDTAG; } if(is_array($hmorig) && count($hmorig) > 0){ foreach($hmorig as $k=>$v){ if(!defined($_REQUEST[$K]) || $_REQUEST[$k] == ''){ $_REQUEST[$k] = $v; } } } } } # some triggers bgn, added on Fri Mar 23 21:51:12 CST 2012 # see xml/fin_todotbl.xml foreach($fieldlist as $i=>$field){ # e.g. <trigger>1::copyto::dijietbl::tuanid=id::tuanid=id</trigger> # 0:currentFieldValue, 1:action, 2:targetTbl, 3:targetField, 4:where, 5:extra $triggers = $gtbl->getTrigger($field); if($triggers != ''){ debug("field:$field triggers:[".$triggers."]"); $fstArr = explode("|",$triggers); $tmpGtbl = new GTbl('', array(), ''); foreach($fstArr as $k=>$trigger){ $tArr = explode("::", $trigger); if($tArr[0] == 'ALL' || $tArr[0] == $gtbl->get($field)){ $tmptbl = $tArr[2]; $tmptbl = $tmpGtbl->setTbl($tmptbl); if($tArr[1] == 'copyto'){ $sqlchk = "select id from $tmptbl where "; $chkFArr = explode(",", $tArr[4]); foreach($chkFArr as $k=>$v){ if($v != ''){ $chkField = explode("=", $v); $sqlchk .= $chkField[0]."='".$gtbl->get($chkField[1])."' and "; } } $sqlchk = substr($sqlchk, 0, strlen($sqlchk)-4); $sqlchk .= " limit 1"; $sql = "insert into ".$tmptbl." set "; $sqlupd = "update ".$tmptbl." set "; $fieldArr = explode(",",$tArr[3]); foreach($fieldArr as $k=>$v){ if($v != ''){ $vArr = explode("=",$v); if(strpos($vArr[1],"'") === 0 ||strpos($vArr[1],'"') === 0){ # hss_fin_applylogtbl.xml $gtbl->set($vArr[1], substr($vArr[1],1,strlen($vArr[1])-2)); } else if($vArr[1] == 'THIS'){ $vArr[1] = $field; } $tmpfieldv = $gtbl->get($vArr[1]); if($vArr[1] == 'THIS_TABLE' || $vArr[1] == 'THIS_TBL'){ $tmpfieldv = $tbl; } else if($vArr[1] == 'THIS_ID'){ $tmpfieldv = $id; } else if(in_array($vArr[0], $timefield)){ $tmpfieldv = date("Y-m-d H:i:s", time()); # 'NOW()'; } $sql .= " ".$vArr[0]."='".$tmpfieldv."',"; $sqlupd .= " ".$vArr[0]."='".$tmpfieldv."',"; } } $sql = substr($sql, 0, strlen($sql)-1); $sqlupd = substr($sqlupd, 0, strlen($sqlupd)-1); debug(" trigger: sqlchk:[".$sqlchk."]"); $tmpExtraArr = explode(',', $tArr[5]); # extra $allowInsert = true; if(in_array('NO_INSERT', $tmpExtraArr)){ $allowInsert = false; } $tmphm = $gtbl->execBy($sqlchk, null); if(!$tmphm[0]){ if($allowInsert){ $tmphm = $gtbl->execBy($sql,null); } else{ debug('trigger skip for not allow insert. sql:['.$sql.']'); } debug(" trigger insert sql:[".$sql."] extraArr:[".serialize($tmpExtraArr)."]"); } else{ $newtmphm = $tmphm[1]; $sqlupd = $sqlupd." where "; #id='".$newtmphm[0]['id']."' limit 1"; $chkFArr = explode(",", $tArr[4]); foreach($chkFArr as $k=>$v){ if($v != ''){ $chkField = explode("=", $v); $sqlupd .= $chkField[0]."='".$gtbl->get($chkField[1])."' and "; } } $sqlupd = substr($sqlupd, 0, strlen($sqlupd)-4); # no limit 1? $tmphm = $gtbl->execBy($sqlupd, null); debug(" trigger upd sql:[".$sqlupd."]"); } #print_r($tmphm); } else if($tArr[1] == 'lockto'){ $sql = "replace into ".$tmptbl." set inserttime=NOW(), operator='".$userid."', "; $sqlchk = "select id from $tmptbl where "; $fieldArr = explode(",",$tArr[3]); foreach($fieldArr as $k=>$v){ if($v != ''){ $vArr = explode("=",$v); if(strpos($vArr[1],"'") === 0 ||strpos($vArr[1],'"') === 0) { $gtbl->set($vArr[1], substr($vArr[1],1,strlen($vArr[1])-1)); }else if($vArr[1] == 'THIS'){ $vArr[1] = $field; } $tmpfieldv = $gtbl->get($vArr[1]); if($vArr[1] == 'THIS_TABLE' || $vArr[1] == 'THIS_TBL'){ $tmpfieldv = $tbl; }else if($vArr[1] == 'THIS_ID'){ $tmpfieldv = $id; } $sql .= " ".$vArr[0]."='".$tmpfieldv."',"; $sqlchk .= " ".$vArr[0]."='".$tmpfieldv."' and"; } } $sql .= " mode='r' "; $sqlchk = substr($sqlchk, 0, strlen($sqlchk)-3); $tmphm = $gtbl->execBy($sql,null); #print_r($tmphm); } else if($tArr[1] == 'extraact'){ # see xml/hss_tuandui_shouzhitbl.xml # e.g. <trigger>ALL::extraact::extra/sendmail.php::Offer入口调整修改id=THIS_ID</trigger> $extraact = $tArr[2]; $args = $tArr[3]; include($appdir."/".$extraact); } } } } } # some triggers end, added on Fri Mar 23 21:51:12 CST 2012 ?><file_sep>/act/updatefield.php <?php $field = Wht::get($_REQUEST, 'field'); # remedy by wadelau Tue Jun 30 16:17:53 CST 2015 # updt by xenxin, Sat May 22 12:08:50 CST 2021 # same as act/doaddmodi.php $fieldv = Wht::get($_REQUEST, $field); $fieldv = urldecode($fieldv); if($fieldv == ''){ if($gtbl->isNumeric($hmfield[$field]) == 1){ $fieldv = $hmfield[$field."_default"]; #print __FILE__.": field:[".$field."] type:[".$hmfield[$field]."] is int."; $fieldv = $fieldv=='' ? 0 : $fieldv; } } if(1){ if(strpos($fieldv,"<") !== false){ # added by wadelau on Sun Apr 22 22:09:46 CST 2012 if($fieldInputType == 'textarea'){ # allow all html tags except these below $fieldv = str_replace("<script","&lt;script", $fieldv); $fieldv = str_replace("<iframe","&lt;iframe", $fieldv); $fieldv = str_replace("<embed","&lt;embed", $fieldv); } else{ $fieldv = str_replace("<","&lt;", $fieldv); } } else if(strpos($fieldv,"&lt;") !== false){ #error_log(__FILE__.": 0 $fieldv"); $fieldv = preg_replace("/&lt;[^>]+?>/", "", $fieldv); # remedy on Fri, 26 Aug 2016 16:32:13 +0800 $fieldv = str_replace("&nbsp;", "", $fieldv); #error_log(__FILE__.": 1 $fieldv"); } if(strpos($fieldv, "\n") !== false){ $fieldv = str_replace("\n", "<br/>", $fieldv); } } $gtbl->set($field, $fieldv); $gtbl->setId($id); $hm = $gtbl->setBy("$field", ""); if($hm[0]){ $hm = $hm[1]; $out .= "--SUCC--"; } # read newly-written data, Tue Sep 27 13:28:06 CST 2016 $hmNew = $gtbl->getBy('*', $gtbl->myId.'="'.$id.'"'); if($hmNew[0]){ $hmNew = $hmNew[1][0]; #debug(__FILE__.": resultset-tag:[".$gtbl->resultset."]"); $gtbl->set($gtbl->resultset, $hmNew); #debug($gtbl->get($gtbl->resultset)); } # some triggers bgn, added on Fri Mar 23 21:51:12 CST 2012 include("./act/trigger.php"); # some triggers end, added on Fri Mar 23 21:51:12 CST 2012 $gtbl->setId(''); # clear targetId ?> <file_sep>/act/tblcheck.php <?php # do some action defined in table::check tag in xxxx.xml $checkactions = $gtbl->getTblCHK(); if(count($checkactions) > 0){ foreach($checkactions as $chkact=>$do){ if($chkact == $act){ #$out .= __FILE__.": found preset checkaction:[".$do."]\n"; include($appdir."/".$do); } } } # manage mode check $mode = $gtbl->getMode(); $accMode = $mode; if($mode != ''){ $act2mode = array('add'=>'w', 'addbycopy' => 'w', 'list-addform'=>'w', 'modify'=>'w', 'import'=>'w', 'updatefield'=>'w', 'list'=>'r', 'list-toexcel'=>'r', 'view'=>'r', 'list-dodelete'=>'d', 'print' => 'r', 'deepsearch' => 'r', 'dodeepsearch' => 'r', 'pivot' => 'r', 'pivot-do' => 'r', 'pickup' => 'r', ); $modechar = $act2mode[$act]; if(!isset($modechar)){ error_log(__FILE__.": unknown act:[$act] in act2mode.201202282117"); } else{ if($mode == 'o-w'){ # @todo } else if(strpos($mode, $modechar) === false){ $out = "<p>访问被拒绝. <br/>act:[$act] is not allowed in mode:[$mode]. 201202282143\n"; $out .= "<br/><br/> 联系上级或技术支持<a href='mailto:".$_CONFIG['adminmail']."?subject=" .$_CONFIG['agentname']."权限申请访问$tbl@$db'> 申请变更 </a> <br/><br/></p>"; if($fmt == ''){ # } else if($fmt == 'json'){ $data = array(); $data['out'] = $out; $data['targetid'] = $id; $out = json_encode($data); } else{ debug($fmt, "unknown fmt:$fmt"); } #debug("act/tblcheck: out:$out"); print $out; exit(0); } else{ #$out .= "act:[$act] is ready.\n"; } } } ?> <file_sep>/act/synctblindexkey.php <?php # embeded in xml/hss_info_objectindexkeytbl, write stat data when modifying # <EMAIL>, Tue Jul 3 21:53:25 CST 2012 if(1){ $targettbl = ''; $sql = "select tblname from ".$_CONFIG['tblpre']."info_objecttbl where id='".$_REQUEST['parentid']."' limit 1"; $hm = $gtbl->execBy($sql, null); if($hm[0]){ $targettbl = $hm[1][0]['tblname']; } $myindexname = trim($_REQUEST['indexname']); $myindexname = str_replace("`","", $myindexname); $myonfield = trim($_REQUEST['onfield']); $myonfield = str_replace("`","", $myonfield); if($act == 'list-dodelete'){ $sql = "alter table $targettbl drop index ".$hmorig['fieldname']; }else if($_REQUEST['id'] == ''){ $sql = "alter table $targettbl add ".$_REQUEST['indextype']." index ".$myindexname; $sql .= "(".$myonfield.")"; }else if(1){ $sql = "alter table $targettbl drop index ".$hmorig['fieldname']; $gtbl->execBy($sql, null); $sql = "alter table $targettbl add ".$_REQUEST['indextype']." index ".$myindexname; $sql .= "(".$myonfield.")"; } $gtbl->execBy($sql, null); error_log(__FILE__.": act:$act, req_id:".$_REQUEST['id']." sql:[".$sql."]"); } ?>
4642f530bbd1e677242bd4f85a0cd65538f6e9ab
[ "SQL", "JavaScript", "Markdown", "PHP", "Shell" ]
36
PHP
wadelau/gMIS
44574030ea18e7717bf0c9097480860fe61ab759
18cd206173b25592b8a7b863455227c3ed70a536
refs/heads/master
<file_sep>package by.belhard.j2.homework4; import java.util.Map; import java.util.Scanner; public class ATM { public static void startWork() { Scanner sc = new Scanner(System.in); Banking b = new Banking(); // b.addAcc(1, 7777, 300); // b.addAcc(2, 7787, 300); // b.addAcc(4, 7778, 300); // b.addAcc(3, 7877, 300); System.out.println("1.Данные о счёте" + '\n' + "2.Пополнить счёт" + '\n' + "3.Снять деньги со счёта" + '\n' + "4.Перевод"); int x = sc.nextInt(); switch (x) { case 1: System.out.println("Введите номер счёта"); int s = sc.nextInt(); System.out.println("Введите пинкод:"); int p = sc.nextInt(); int ps = b.checkPass(s); if (p == ps) b.checkAcc(s); else System.out.println("Неправильный пинкод"); break; case 2: System.out.println("Введите номер счёта"); int s1 = sc.nextInt(); System.out.println("Введите пинкод:"); int p1 = sc.nextInt(); int ps1 = b.checkPass(s1); if (p1 == ps1) { b.checkAcc(s1); System.out.println("Введите сумму пополнения"); double ss = sc.nextDouble(); System.out.println("Итого"); b.addBalance(s1, ss); } else System.out.println("Неправильный пинкод"); break; case 3: System.out.println("Введите номер счёта"); int s2 = sc.nextInt(); System.out.println("Введите пинкод:"); int p2 = sc.nextInt(); int ps2 = b.checkPass(s2); if (p2 == ps2) { b.checkAcc(s2); System.out.println("Введите желаемую сумму"); double ss = sc.nextDouble(); System.out.println("Итого"); b.addBalance(s2, -ss); } else System.out.println("Неправильный пинкод"); break; case 4: System.out.println("Введите номер счёта с которого будут забирать деньги"); int s3 = sc.nextInt(); System.out.println("Введите номер счёта на который зачисляют деньги"); int s03 = sc.nextInt(); System.out.println("Введите пинкод счета 1"); int p3 = sc.nextInt(); int ps3 = b.checkPass(s3); if (p3 == ps3) { b.checkAcc(s3); System.out.println("Введите желаемую сумму"); double ss = sc.nextDouble(); System.out.println("Итого"); b.transfer(s3,s03,ss); } else System.out.println("Неверные данные"); break; default: System.out.println("Неправильная команда"); break; } } } <file_sep>package by.belhard.j2.lesson4; import by.belhard.j2.lesson4.in.Country; import by.belhard.j2.lesson4.in.Person; import by.belhard.j2.lesson4.in.Sex; import by.belhard.j2.lesson4.in.Worker; public class Main { public static void main(String[] args) { Person person1 = new Person("Pablo", 23, Sex.MALE); Person person2 = new Person("Anna", 20, Sex.FEMALE); person1.setCountry(new Country("Brazil", 123456)); person2.setCountry(person1.getCountry()); System.out.println(person1); System.out.println(person2); Worker worker1 =new Worker("Mustafa",45,Sex.MALE); System.out.println(worker1); worker1.toWork(); } } <file_sep>package by.belhard.j2.lesson5; public class KItchenWorker extends Worker { } <file_sep>package by.belhard.j2.homework3; public class Prod extends Product { public Prod(String name, double price) { super(name, price); } } <file_sep>package by.belhard.j2.homework3; import java.util.HashMap; import java.util.Map; public class Main { public static void main(String[] args) { Market x = new Market(); Map<String,Product > product =x.getProduct(); product.put("prod1", new Prod("prod1", 10)); product.put("prom1", new Prom("prom1", 20)); product.put("forA1", new ForAnimals("forA1", 15)); product.put("prod2", new Prod("prod2", 30)); Map<String, Product> cart = x.getCart(); cart.put("cart1", product.get("prom1")); cart.put("cart2", product.get("prom1")); cart.put("cart3", product.get("prod1")); System.out.println(cart.values()); double sum = 0; for (Map.Entry<String, Product> entry : cart.entrySet()) sum += entry.getValue().getPrice(); System.out.println("Full Price=" + sum); // product.put("prod1", new Prod("prod1", 10)); // product.put("prom1", new Prom("prom1", 20)); // product.put("forA1", new ForAnimals("forA1", 15)); // product.put("prod2", new Prod("prod2", 30)); } // Market x = new Market(); // public void addTo(){ // HashMap<String,Product> product =x.getProduct(); // product.put("prod1", new Prod("prod1", 10)); // product.put("prom1", new Prom("prom1", 20)); // product.put("forA1", new ForAnimals("forA1", 15)); // product.put("prod2", new Prod("prod2", 30)); // // HashMap<String, Product> cart = x.getCart(); // // cart.put("cart1", product.get("prom1")); // cart.put("cart2", product.get("prom1")); // cart.put("cart3", product.get("prod1")); // System.out.println(cart.values()); //} } <file_sep>package by.belhard.j2.lesson5; public class Main { public static void main(String[] args) { /*Worker worker = new Worker(); worker.exampleMethod(); Person person1 = new Person(); person1.doWork(); worker.doWork();*/ Person person2 = new FactoryWorker(); person2.doWork(); Person person1 = new Teacher(); System.out.println(person1.getA()); person1.doWork(); System.out.println(person1 instanceof Person); System.out.println(person2 instanceof Teacher); System.out.println(new FactoryWorker() instanceof Object); System.out.println(); Workable monkey =new Monkey(); Workable worker = new Worker(); monkey.doWork(); worker.doWork(); } } <file_sep>package by.belhard.j2.lesson5; public interface Workable { double PI = 3.1415; void doWork(); default void exapleDefaultM(){ } static void examplePrivate(){ } } <file_sep>package by.belhard.j2.lesson9.try2; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; public class Main { public static void main(String[] args) { List<Car> list = new ArrayList<>(); list.add(new Car("opel", 3000)); list.add(new Car("opel", 1500)); list.add(new Car("opel", 2000)); list.add(new Car("audi", 6000)); list.add(new Car("audi", 1500)); list.add(new Car("opel", 6000)); Comparator<Car> comparatorCar = ((o1, o2) -> { int dDistance = o1.getDistance() - o2.getDistance(); if (dDistance == 0) return o1.getName().compareTo(o2.getName()); return dDistance; }); list.forEach(System.out::println); List<Car> collect = list.stream().filter(a -> a.getDistance() < 5000).sorted(comparatorCar) .collect(Collectors.toList()); System.out.println(); collect.forEach(System.out::println); } } <file_sep>package by.belhard.j2.lesson11; import java.sql.*; public class Main { private static final String DRIVER_NAME = "com.mysql.cj.jdbc.Driver"; private static final String USER ="root"; private static final String PASSWORD ="<PASSWORD>"; private static final String URL = "jdbc:mysql://localhost:3306/company?serverTimezone=UTC"; public static void main(String[] args) { try { Class.forName(DRIVER_NAME); }catch (ClassNotFoundException e){ System.out.println(DRIVER_NAME + " loading failure"); return; } Connection connection; try { connection = DriverManager.getConnection(URL, USER, PASSWORD); Statement statement = connection.createStatement(); //statement.execute("insert into employees values (null,'Bruce',null,150,current_date )"); // int result = statement.executeUpdate("delete from employees where name = 'Bruce'"); // System.out.println(result + "rows"); String query = "select * from employees e join specialties s on (e.specialty_id = s.id);"; statement.executeQuery(query); ResultSet resultSet = statement.executeQuery(query); while (resultSet.next()){ int id = resultSet.getInt("e.id"); String name = resultSet.getString("name"); String specialty =resultSet.getString("specialty"); int salary = resultSet.getInt("salary"); java.util.Date date = resultSet.getDate("date_of_employment"); System.out.printf("%-2d) %-10s %-10s %5d %5$td/%5$tm/%5$tY\n", id, name, specialty, salary, date); } // query= "update employees set (salary =salary + ?) where salary < ?;"; PreparedStatement preparedStatement = connection.prepareStatement("update employees set (salary =salary + ?) where salary < ?;"); preparedStatement.setInt(1,100); preparedStatement.setInt(2,1000); }catch(SQLException e){ e.printStackTrace(); } } } <file_sep>package by.belhard.j2.homework1; public class Home2 { public static void main(String[] args) { /*int x = 1; do { System.out.println("Это" + " " + x + "-я строка"); x++; } while (x <= 15);*/ for (int i =1; i <= 15; i++){ System.out.printf("%d) Это %d-я строка\n",i,i);} } }<file_sep>package by.belhard.j2.homework2; public class Car { private String name; private Coordinate coordinate; private double km; public Car(String name, Coordinate coordinate) { this(name, coordinate, 20); } public Car(String name,double x, double y){ this(name, new Coordinate(x,y)); } public Car(String name,Coordinate coordinate, double km) { this.name = name; this.coordinate=coordinate; this.km = km; } public double move(Coordinate point) { double km = this.coordinate.Distance(point); this.km += km; this.coordinate = point; return km; } public double move(double x,double y){ return move(new Coordinate (x,y)); } public String getName() { return name; } public void setName(String name) { this.name = name; } public Coordinate getCoordinate() { return coordinate; } public void setCoordinate(Coordinate coordinate) { this.coordinate = coordinate; } public double getKm() { return km; } public void setKm(double km) { this.km = km; } @Override public String toString() { return "Car{" + "name='" + name + '\'' + ", coordinate=" + coordinate + ", distance=" + km + '}'; } /*public void toMove(double x ,double y) { double a; double b; a = x - this.x; b = y - this.y; km = this.km + Math.sqrt((a*a) + (b*b)) ; this.x = x; this.y = y; // x=(55.75222); // y=(37.61556); }*/ /*public String getName() { return name; } public void setName(String name) { this.name = name; } public double getX() { return x; } public void setX(double x) { this.x = x; } public double getY() { return y; } public void setY(double y) { this.y = y; } public double getKm() { return km; } public void setKm(double km) { this.km = km; } @Override public String toString() { return "Car{" + "name='" + name + '\'' + ", x=" + x + ", y=" + y + ", distance=" + km + '}'; }*/ }<file_sep>package by.belhard.j2.solo; import jdk.nashorn.internal.scripts.JO; import javax.swing.JOptionPane; public class Main { public static void main(String[] args) { int yearNow,yearBorn,userAge,bDay; String userData; userData = JOptionPane.showInputDialog("Romeli welia?"); yearNow = Integer.parseInt(userData); userData = JOptionPane.showInputDialog("Romel wels daibade?"); yearBorn = Integer.parseInt(userData); userData = JOptionPane.showInputDialog("Gqondat wels dabadebis dge? ki-0, ara-1"); bDay = Integer.parseInt(userData); userAge = yearNow - yearBorn - bDay; JOptionPane.showMessageDialog(null,"Tqveni asaki: " + userAge); } } <file_sep>package by.belhard.j2.lesson5; public class Worker extends Person{ public void exampleMethod(){ System.out.println("this.a="+ this.a + "super.a = " +super.a);} @Override public void doWork(){ System.out.println("umeiu"); } } <file_sep>package by.belhard.j2.homework1; public class Home { public static void main(String[] args) { int x=19; /* if ((x*2) > 20) { System.out.println(x); }else if ((x*2) <20) { System.out.println(-x); }else System.out.println("0");*/ int result =0; if (x*2>20){ result = x; } } } <file_sep>package by.belhard.j2.homework4; import java.util.HashMap; import java.util.Map; public class BankingOld { public Map<Integer, Account> accs = new HashMap<>(); public void checkAcc(int x) { Account a = accs.get(x); System.out.println(a); } public Integer checkPass(int x) { int a = accs.get(x).getPass(); return a; } public void addAcc(Account account) { accs.put(account.getName(), account); }public void addAcc(int name, int pass, double money) { this.addAcc(new Account(name, pass, money)); } // // public void minusBalance(int x, double y){ // int name1 = accs.get(x).getName(); // int pass1 = accs.get(x).getPass(); // double a = accs.get(x).getMoney(); // double sum = a - y; // addAcc(name1,pass1,sum); // Account i = accs.get(x); // System.out.println(i); // } public void transfer (int a, int b, double y){ int name1 = accs.get(a).getName(); int pass1 = accs.get(a).getPass(); double s = accs.get(a).getMoney(); int name2 = accs.get(b).getName(); int pass2 = accs.get(b).getName(); double s2 = accs.get(b).getMoney(); double sum = s - y; double sum2 = s2 +y; addAcc(name1,pass1,sum); addAcc(name2,pass2,sum2); Account i = accs.get(a); System.out.println(i); // Account i2 = accs.get(b); // System.out.println(i+"\n"+ i2); } public void addBalance(int x, double y){ int name1 = accs.get(x).getName(); int pass1 = accs.get(x).getPass(); double a = accs.get(x).getMoney(); double sum = a + y; addAcc(name1,pass1,sum); Account i = accs.get(x); System.out.println(i); } } <file_sep>package by.belhard.j2.lesson8.l4; import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Main { public static void main(String[] args) throws FileNotFoundException { Scanner scanner = new Scanner(new File("example.data")); int sum1 =0; int sum2 =0; int sum3 =0; int sum4 =0; double sum5 =0; String[] line; while (scanner.hasNextLine()) { line = scanner.nextLine().split(" "); sum1 +=Integer.parseInt(line[0]); sum2 +=Integer.parseInt(line[1]); sum3 +=Integer.parseInt(line[2]); sum4 +=Integer.parseInt(line[3]); sum5 +=Double.parseDouble(line[4]); } } } <file_sep>package by.belhard.j2.homework2; public class Coordinate { private double x; private double y; public Coordinate(double x, double y) { this.x = x; this.y = y; } public double Distance(Coordinate other){ return Math.sqrt((this.x - other.x)*(this.x - other.x)+(this.y - other.y)* (this.y-other.y)); } public double getX() { return x; } public void setX(double x) { this.x = x; } public double getY() { return y; } public void setY(double y) { this.y = y; } @Override public String toString() { return "Coordinate{" + "x=" + x + ", y=" + y + '}'; } } <file_sep>package by.belhard.j2.lesson5; public abstract class Person implements Workable { public int a=10; public abstract void doWork(); public void sayHello(){ System.out.println("Hello!"); } public int getA() { return a; } } <file_sep>package by.belhard.j2.homework2; public class Main { public static void main(String[] args) { Car car1 = new Car("BMW", 53.8722515,27.616536); System.out.println(car1); car1.move(55.75222,37.61556); System.out.println(car1); } //x=53.8722515 y=27.616536 }
4a7be22effc9bde9fd686f2b91433d0daf845d38
[ "Java" ]
19
Java
Galdava/homework
ef9e17a235184288bb890931a9dcf45fbec2740c
7f5ca5ce593d19ef7d9e020d7fa4d5f130ed3a70
refs/heads/master
<repo_name>CaroseKYS/fis3-parser-get-conf<file_sep>/README.md # fis3-parser-get-conf 该模块用于在fis3发布项目时为前端js、html以及css代码提供获取服务器端配置信息的能力。 ## 使用方法 ### 安装模块 npm install -g fis3-parser-get-conf ### 使用基础功能 fis.match('*', function(){ parser: fis.plugin('get-conf') }); ### 配置项 fis.match('*', { parser: fis.plugin('get-conf', { confFile: "./conf.json", /*配置文件名称*/ contextPath: "/app", /*上下文路径*/ ifExcluded: function(propStr){ return propStr in {'redis.pass': 1}; } }) }); + `confFile` : 服务器端配置文件的路径(相对于当前工作目录)。如果该参数未配置, 则优先使用 **./fdp-config.js** 文件, 如果 **./fdp-config.js** 文件不存在, 则使用 **./fdp-conf.js** 文件。`__getConf` 方法获取的正是该文件中的属性。 + `ifExcluded`: 是否排除某些属性的判别方法,每次 `__getConf` 方法被调用之前 `ifExcluded` 方法都会被调用,用以判断是否忽略该属性。该方法接受到的参数为 `__getConf` 的参数,如果该方法返回 `true`,则忽略该属性, `__getConf` 方法将得到一个空字符串的返回值。该方法主要用于防止敏感信息泄露。 ### 在js文件中获取配属性 var url = __getConf('fdp-sso-client.fdp-sso-server-uri'); var path = __context(); /* ==> /app */ var path = __context('/test'); /* ==> /app/test */ ### 在html文件中获取配属性 <a href="__getConf(fdp-sso-client.fdp-sso-server-uri)"></a> <a href="__context(/index.html)"></a> ### 关于__getConf方法的参数 `__getConf` 方法的参数如果是用 `.` 分割,则表示是递归获取对象属性。如 `__getConf(fdp-sso-client.fdp-sso-server-uri)` 表示获取配置文件中 `fdp-sso-client` 对象的 `fdp-sso-server-uri` 属性值。 <file_sep>/test/index.js 'use strict'; const rewire = require('rewire'); const should = require('should'); var index; describe('index.js测试', function(){ it('加载模块', function(){ should.doesNotThrow(function(){ index = rewire('../index.js'); }); }); describe('导出方法测试', function(){ var content; var file; var opts; beforeEach(function (){ content = '<p></p>'; file = {isHtmlLike: true}; opts = {confFile: './package.json'}; }); it('未指定配置文件', function(){ opts = {}; should.throws(function(){ index(content, file, opts).should.equal(content); }); }); it('不获取任何属性', function(){ index(content, file, opts).should.equal(content); }); it('获取作者姓名属性', function(){ opts['contextPath'] = '/app' content = '<p class="__getConf(author.name)" data-target="__context(/test)"></p>'; index(content, file, opts).should.equal('<p class="康永胜" data-target="/app/test"></p>'); delete opts['contextPath']; }); it('css类型文件', function(){ content = '.__getConf(name){z-index: 100;}'; file = {isCssLike: true}; index(content, file, opts).should.equal('.fis3-parser-get-conf{z-index: 100;}'); }); it('js类型文件', function(){ content = '__getConf("name");__context("/app");__context(/app);__context()'; file = {isJsLike: true}; index(content, file, opts).should.equal('"fis3-parser-get-conf";"/app";\'/app\';\'\''); }); it('js类型文件:添加获取模块id的方法测试', function(){ content = '__seajs_mod_id__'; file = {isJsLike: true, subpath: '/subpath'}; index(content, file, opts).should.equal("seajs.data.ids['/subpath']"); }); it('非js html css类型的文件', function(){ content = '<p class="__getConf(author.name)"></p>'; file = {}; index(content, file, opts).should.equal(content); }); it('获取不允许获取的配置', function(){ content = '<p class="__getConf(main)"></p>'; opts.ifExcluded = function(propsStr){ return 'main' === propsStr; }; index.__set__('oConf', null); index(content, file, opts).should.equal('<p class=""></p>'); }); }); describe('私有方法测试', function(){ describe('_ifExcluded', function(){ var _ifExcluded; before(function(){ _ifExcluded = index.__get__('_ifExcluded'); }); it('普通调用应当返回false', function(){ _ifExcluded('dsdfsf').should.equal(false); }); }); describe('_getPropertyTool', function(){ var _getPropertyTool; before(function(){ _getPropertyTool = index.__get__('_getPropertyTool'); }); it('不传入参数,返回空', function(){ _getPropertyTool().should.equal(''); }); it('查找不存在的属性', function(){ should.equal(_getPropertyTool('name.version'), undefined); }); }); }); });<file_sep>/index.js var oConf = null; var contextPath = ''; var ifExcluded; var path = require('path'); var fs = require('fs'); /** * 发布过程中的 __getConf() 与 __context() 方法 * @author 康永胜 * @date 2017-01-12T17:14:31+0800 * @param {[type]} content [description] * @param {[type]} file [description] * @param {[type]} opt [description] * @return {[type]} [description] */ module.exports = function(content, file, opt){ contextPath = opt['contextPath'] || ''; if (!oConf) { try{ oConf = _getConfContent(opt['confFile']); }catch(e){ console.log(e); throw 'fis3-parser-get-conf|获取配置信息失败。'; } ifExcluded = opt.ifExcluded || _ifExcluded; } /*处理html css js文件*/ if (file.isHtmlLike || file.isCssLike || file.isJsLike) { /*__getConf 方法*/ content = content.replace(/__getConf\(\s*(['"]?)([^)]*?)\1\s*\)/ig, function(all, value1, value2){ var prop = _getPropertyTool(value2); if(file.isJsLike){ return value1 + prop + value1; } return prop; }); /*__context 方法*/ content = content.replace(/__context\(\s*(['"]?)([^)]*?)\1\s*\)/ig, function(all, value1, value2){ value2 = value2 || ''; value2 = contextPath + value2; if(file.isJsLike){ value1 = value1 || "'"; value2 = value1 + value2 + value1; } return value2; }); /*__seajs_mod_id__ 方法*/ content = content.replace(/__seajs_mod_id__/ig, function(all){ return 'seajs.data.ids[\'' + file.subpath + '\']'; }); return content; } return content; } /** * 用于根据属性值列表从配置中获取配置信息 * @author 康永胜 * @date 2017-01-22T16:39:12+0800 * @param {String} propertiesStr [以 "." 分割的属性列表] * @return {String} [属性值] */ function _getPropertyTool(propertiesStr){ if(ifExcluded(propertiesStr)){ return ''; } propertiesStr = propertiesStr || ''; propertiesStr = propertiesStr.trim(); if(!propertiesStr || !oConf){ return ''; } var properties = propertiesStr.split('.'); var length = properties.length; var result = ''; var currentDomain = oConf; for (var i = 0; i < length; i++) { currentDomain = result = currentDomain[properties[i]]; if(!result)break; } return result; } /** * 是否将所访问的属性隐藏 * @author 康永胜 * @date 2017-01-22T16:40:30+0800 * @param {String} propertiesStr [以 "." 分割的属性列表] * @return {boolean} [是否隐藏属性] */ function _ifExcluded(propertiesStr){ return false; } /** * 获取配置文件的内容 * @author 康永胜 * @date 2017-02-10T10:37:44+0800 * @param {String} confFile [配置文件名称] * @return {Object} [配置文件内容] */ function _getConfContent(confFile){ var confFile = path.join(process.cwd(), confFile || 'fdp-config.js'); if(!fs.existsSync(confFile)){ confFile = path.join(process.cwd(), 'fdp-conf.js'); } oConf = require(confFile); return oConf; }
e69c31a800da49792bb5c32600528bd5af7c7d9e
[ "Markdown", "JavaScript" ]
3
Markdown
CaroseKYS/fis3-parser-get-conf
ec6bb62867b94639841ecfe706b01f8cc5e8c02e
6f040c2e0b61acd562e1f6e3907bb1d4d702cfcd
refs/heads/master
<repo_name>AkhilRamani/Firebase-Google-Auth-ReactNative<file_sep>/configs/oAuth.config.demo.js import {Platform} from 'react-native'; export const oAuthClientId = Platform.OS === 'android' ? 'android client id' : 'ios client id'<file_sep>/navigation/switch.navigaton.js import { createSwitchNavigator, createAppContainer } from 'react-navigation'; import LoadingScreen from '../screens/loading' import HomeScreen from '../screens/Home' import LoginScreen from '../screens/Login' const AppSwitchNavigator = createSwitchNavigator({ LoadingScreen, LoginScreen, HomeScreen, }) export default createAppContainer(AppSwitchNavigator);
36a78f0b1a4dd5eeca74a35c3532d4a5c690b05a
[ "JavaScript" ]
2
JavaScript
AkhilRamani/Firebase-Google-Auth-ReactNative
10d105343989b9c19bd18a6bde419dd625280c49
d8ea36d88142c8f76fd16b29d1854fd24d824249
refs/heads/master
<file_sep>#Third party imports #Python imports import requests from bs4 import BeautifulSoup #Local imports requests.packages.urllib3.disable_warnings() def has_text(url : str, word : str): """ This function checks if word is in url Use word as lowercase """ flag = False r = requests.get(url, verify=False, allow_redirects=True) if word in r.text: flag = True return flag def get_forms(site : str): """ This function extracts all forms and inputs -- Example -- get_forms('http://wechall.net') [['/login', 'post', {'username': '', 'password': ''}]] """ redirects = [] page = requests.get(site, verify=False, allow_redirects=True) soup = BeautifulSoup(page.content, 'html.parser') for tag in soup.find_all('form'): fields = tag.findAll('input') formdata = dict( (field.get('name'), field.get('value')) for field in fields) redirects.append([tag.get('action'), tag.get('method'), formdata]) return redirects def is_site(domain : str, port : int): """ Function to determine if domain has an http service on determined port -- Example -- is_site('scanme.nmap.org', 22) => False is_site('tls-v1-2.badssl.com', 1012) => True """ has_site = False if port == 443: url = "https://" + domain else: url = "http://" + domain + ":" + str(port) try: r = requests.get(url, verify=False, allow_redirects=True) has_site = True except: pass return has_site def c_or_t(site : str): """ Function to determine if site is content-like or transactional -- Example -- c_or_t('http://wechall.net') => T """ site_type = "C" if get_forms(site): site_type = "T" return site_type def get_urls(site : str): """ Function to parse subdomains from extracted a-href by a given url """ links = [] page = requests.get(site, verify=False, allow_redirects=True) soup = BeautifulSoup(page.content, 'html.parser') for tag in soup.find_all('a', href=True): if "http" in tag['href']: links.append(tag['href'].split("/")[2]) return links <file_sep>sslyze==3.0.1 git+https://github.com/aboul3la/Sublist3r.git python-nmap typing google<file_sep>#Third party imports import nmap #Python imports import random #Local imports import utils import sites top_ports_tcp = '21-25,53,80,88,110-143,389,443,445,995,993,1723,3306,3389,5900,8080' top_ports_udp = '53,67-69,88,161,162,3389,5353' def nmap_scan(site : str, ports=top_ports_tcp, arguments='-Pn -sV -T4'): """ Simple nmap scan to check on common ports No special flags, no scripts, no udp -- Example -- print(nmap_scan("scanme.nmap.org") {22: 'OpenSSH 6.6.1p1 Ubuntu 2ubuntu2.13', 25: ' ', 80: 'Apache httpd 2.4.7'} """ host = utils.is_alive(site) result = {} if host: nm = nmap.PortScanner() nm.scan(host, ports, arguments=arguments) for proto in nm[host].all_protocols(): for port in nm[host][proto].keys(): if nm[host][proto][port]['state'] == "open": product = nm[host][proto][port]['product'] version = nm[host][proto][port]['version'] result[port] = str(product + " " + version) elif nm[host][proto][port]['state'] == "filtered": result[port] = "filtered" else: result[port] = "closed" else: print("[!] Host {} is down!".format(site)) return result def nmap_long_scan(site : str): """ Long nmap scan to check on all ports Noisy, no scripts, no udp """ long_args = '-Pn -p- --max-retries=1 --min-rate=1000 -A' return nmap_scan(site, ports='', arguments=long_args) def nmap_agressive(site : str): """ Long agressive nmap scan to check on all ports Pretty noisy, run all scripts, both TCP and UDP """ agres_args = '-Pn -sUT -p- --version-intensity 9 -A' return nmap_scan(site, ports='', arguments=agres_args) def nmap_re_scan(site : str, scan: dict): """ Simple nmap re-scan on the open ports found Intensive version, run scripts """ mdict = scan.items() opened = dict(filter(lambda elem: elem[1] != 'filtered' and elem[1] != 'closed', mdict)) args = ','.join([str(i) for i in opened]) return nmap_scan(site, arguments='-p' + args + ' --version-intensity 9 -sC -A') def nmap_evasion(site : str): """ Nmap scan for WAS/IDS evasion Packet fragmentation Slow comprehensive Defined source port """ avoid_args = '-f 8 -T0 -g ' + str(random.choice(['80', '443', '53'])) return nmap_scan(site, arguments=avoid_args) <file_sep>#Third party imports from sslyze import server_connectivity from sslyze import synchronous_scanner from sslyze.plugins import openssl_cipher_suites_plugin as cipher #Python imports #Local imports default_port = 443 # DEPRECATED (SSLYZE = 2.1.4) UPGRADE METHODS TO 3.0.1 def syn_scanner(host, port, command_scanner): server_connection = server_connectivity.ServerConnectivityTester( hostname=host, port=port ) connection = server_connection.perform() syn_scanner = synchronous_scanner.SynchronousScanner() scan_result = syn_scanner.run_scan_command(connection, command_scanner) return True if len(scan_result.accepted_cipher_list) > 0 else False def check_ssl2(host : str, port : int = default_port): return syn_scanner(host, port, cipher.Sslv20ScanCommand()) def check_ssl3(host : str, port : int = default_port): return syn_scanner(host, port, cipher.Sslv30ScanCommand()) def check_tls10(host : str, port : int = default_port): return syn_scanner(host, port, cipher.Tlsv10ScanCommand()) def check_tls11(host : str, port : int = default_port): return syn_scanner(host, port, cipher.Tlsv11ScanCommand()) def check_tls12(host : str, port : int = default_port): return syn_scanner(host, port, cipher.Tlsv12ScanCommand()) def check_tls13(host : str, port : int = default_port): return syn_scanner(host, port, cipher.Tlsv13ScanCommand()) def all_scans(host : str, port : int = default_port): dict_checks = {} dict_checks['ssl2'] = check_ssl2(host, port) dict_checks['ssl3'] = check_ssl3(host, port) dict_checks['tls10'] = check_tls10(host, port) dict_checks['tls11'] = check_tls11(host, port) dict_checks['tls12'] = check_tls12(host, port) dict_checks['tls13'] = check_tls13(host, port) return dict_checks def few_scans(host : str, port : int = default_port): dict_checks = {} dict_checks['ssl3'] = check_ssl3(host, port) dict_checks['tls10'] = check_tls10(host, port) dict_checks['tls11'] = check_tls11(host, port) return dict_checks <file_sep>#Third party imports #Python imports import socket #Local imports def is_alive(site : str): """ Function check if site has a public IP address A.K.A.: Public DNS resolution -- Example -- check_if_alive("www.google.com") => "192.168.127.12" check_if_alive("internal.corp") => False """ try: is_alive = socket.gethostbyname(site) except: is_alive = False return is_alive <file_sep>#Third party imports import sublist3r import googlesearch #Python imports import random #Local imports import utils import sites useragent = str(random.choice(['Mozilla/5.0 (Windows NT 6.1; Win64;'\ 'x64; rv:47.0) Gecko/20100101 Firefox/47.0', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 '\ '(KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36', 'Mozilla/5.0 (Linux; Android 7.0; SM-G892A Build/NRD90M; wv) AppleWebKit/537.36 '\ '(KHTML, like Gecko) Version/4.0 Chrome/60.0.3112.107 Mobile Safari/537.36', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.75.14 '\ '(KHTML, like Gecko) Version/7.0.3 Safari/7046A194A'])) def get_subs(domain): """ Uses sublist3r to search for subdomains on several engines -- Example -- get_subs('nequi.com') >> www.nequi.com ; api.nequi.com ; etc... """ subdomains = sublist3r.main(domain, 40, savefile=False, ports=None, silent=True, verbose=False, enable_bruteforce=False, engines='google,bing,yahoo,passivedns') return subdomains def brute_force(domain, wordlist): """ Simple subdomain bruteforcing by DNS reverse lookup working with a prefix wordlist """ brute_list = [] with open(wordlist, 'r') as f1: open_file = f1.read().splitlines() for sub in open_file: if utils.is_alive(sub + "." + domain): brute_list.append(sub + "." + domain) if utils.is_alive(sub + domain): brute_list.append(sub + domain) return brute_list def find_by_name(word : str): """ Search related subdomains on google given a word """ doms = [] for url in googlesearch.search(word, lang='es', pause=3.0, stop=20, user_agent=useragent): doms.append(url.split('/')[2]) return doms <file_sep># -*- coding: utf-8 -*- import requests import random requests.packages.urllib3.disable_warnings() words = list(open('docs\directory-list.txt')) codes = [200,301,302,401,403] common_ext = ['php','aspx','asp','cgi','pl','txt','html'] #Usage found_dir(wordlist, url, [optional] ext) #The function return a dictionary with the directories and files found and their response codes def found_dir(wordlist: list, domain: str, ext = common_ext): results = dict() for word in wordlist: useragent = random.choice(['Mozilla/5.0 (Windows NT 6.1; Win64;'\ 'x64; rv:47.0) Gecko/20100101 Firefox/47.0', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 '\ '(KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36', 'Mozilla/5.0 (Linux; Android 7.0; SM-G892A Build/NRD90M; wv) AppleWebKit/537.36 '\ '(KHTML, like Gecko) Version/4.0 Chrome/60.0.3112.107 Mobile Safari/537.36', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.75.14 '\ '(KHTML, like Gecko) Version/7.0.3 Safari/7046A194A']) headers=[] r = requests.get(domain+"/"+word, verify = False, allow_redirects = False, headers = headers.append(useragent)) if r.status_code in codes: results[word]=r.status_code if ext: for item in ext: if requests.get(domain+"/"+word+"."+item, verify = False, allow_redirects = True).status_code in codes: results[word+"."+ext]=r.status_code return results <file_sep>#Third party imports #Python imports import sys #Local imports import domain import portscan #import sslcheck if len(sys.argv) < 2: print("Usage: python3 {} TARGET".format(sys.argv[0])) sys.exit(0) target = sys.argv[1] # Capture subdomains print("[+] Target: {}".format(target)) print("[+] Getting sub-domains!") print("\n[+][+] Subdomains!") subs = domain.get_subs(target) print(subs) subs_brute = domain.brute_force(target, "docs/small.txt") print(subs_brute) print("\n[+][+] Possible subdomains! (google search)\n") subs_by_name = domain.find_by_name(target.split(".")[0]) print(subs_by_name) subsd = [] for item in subs + subs_brute + subs_by_name: if target.split(".")[0] in item: subsd.append(item) print("\n[+][+] Subdomains found! Remember to check!\n") subsd = list(set(subsd)) print(subsd) f1 = open('resultado.csv', '+w') f1.write('subdominio,port,status\n') print("\n[+] Port-Scanning!") for dom in subsd: print("\n[+] Scanning: {}".format(dom)) res = portscan.nmap_scan(dom) print("[+] " + str(dom) + " : " + str(res)) for key, value in res.items(): f1.write(dom + ',' + str(key) + ',' + str(value) + '\n') f1.close()
c1c97866db14226e1b3893515a56e95dba4514b3
[ "Python", "Text" ]
8
Python
henryval/seek-and-destroy
1e7be45c325c0e534e22724d97d6b39b3485c1e5
55c7160d7a9e2a25d9a27f926913b15b0687d931
refs/heads/master
<file_sep>package com.caocao.shardingjdbc.console.dal.ext; import com.fasterxml.jackson.annotation.JsonIgnore; import java.util.List; /** * <p>文件名称:Page.java</p> * <p>文件描述:</p> * <p>版权所有: 版权所有(C)2016-2099</p> * <p>公 司: 优行科技 </p> * <p>内容摘要:</p> * <p>其他说明: </p> * <p>完成日期:2017年01月17日</p> * * @author <EMAIL> * @version 1.0 */ public class Page<T> { private List<T> rows; private int total; @JsonIgnore private int limit = 10; @JsonIgnore private int offset = 0; public Page(int limit, int offset) { if (offset > 1) { offset = (offset - 1) * 10; } else if (offset == 1) { offset = 0; } this.limit = limit; this.offset = offset; } public List<T> getRows() { return rows; } public Page setRows(List<T> rows) { this.rows = rows; return this; } public int getTotal() { return total; } public Page setTotal(int total) { this.total = total; return this; } public int getLimit() { return limit; } public Page setLimit(int limit) { this.limit = limit; return this; } public int getOffset() { return offset; } public Page setOffset(int offset) { this.offset = offset; return this; } } <file_sep>package com.caocao.shardingjdbc.console.dal.model; import lombok.Data; @Data public class ShMetadata { private Long id; private Byte type; private String dataSourceName; private String createBy; private String updateBy; private String properties; }<file_sep>package com.caocao.shardingjdbc.console.dal.dao; import com.caocao.shardingjdbc.console.dal.model.ShMetadata; import com.caocao.shardingjdbc.console.dto.ShMetadataDto; import org.apache.ibatis.annotations.Param; import java.util.List; public interface ShMetadataMapper { int totalCount(@Param("type") String type, @Param("keywords") String keywords); List<ShMetadata> queryDataSourceList(@Param("begin") Integer begin, @Param("end") Integer end, @Param("type") String type, @Param("keywords") String keywords); int deleteInfo(int i); void insertInfo(ShMetadataDto shMetadataDto); void updateInfo(ShMetadataDto shMetadataDto); List<ShMetadata> queryDataSourceCount(); ShMetadata queryInfoById(Integer materId); String queryMasterPropertiesById(int i); Integer queryNameById(String dataSourceName); List<ShMetadata> queryDataSourceCountNoSharding(); ShMetadataDto queryByName(String name); List<ShMetadata> queryDataSourceCountNoMysql(); String queryPropertiesByDataSourceName(String dataSourceName); }<file_sep>package com.caocao.shardingjdbc.console.dal.service.impl; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.caocao.shardingjdbc.console.common.Constants; import com.caocao.shardingjdbc.console.common.CuratorService; import com.caocao.shardingjdbc.console.common.Utils; import com.caocao.shardingjdbc.console.dal.dao.ShConfigMapper; import com.caocao.shardingjdbc.console.dal.ext.Page; import com.caocao.shardingjdbc.console.dal.model.ShConfig; import com.caocao.shardingjdbc.console.dal.service.ShConfigService; import com.caocao.shardingjdbc.console.dal.service.ShMetadataService; import com.caocao.shardingjdbc.console.dto.ShConfigDto; import com.caocao.shardingjdbc.console.dto.ShMetadataDto; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang.math.NumberUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.HashMap; import java.util.List; import java.util.Map; @Service @Slf4j public class ShConfigServiceImpl implements ShConfigService { @Autowired private ShConfigMapper shConfigMapper; @Resource private ShMetadataService shMetadataService; @Resource private CuratorService curatorService; @Override public void queryConfigList(Page<ShConfigDto> page, String keywords) { int total = shConfigMapper.totalCount(keywords); page.setTotal(total); List<ShConfigDto> list = shConfigMapper.queryConfigList(page.getOffset(), page.getLimit(), keywords); for (ShConfigDto shConfigDto : list) { Boolean isValid = curatorService.init(shConfigDto.getRegServerList()); if (!isValid) { return; } String dataSourceName = shConfigDto.getDataSourceName(); ShMetadataDto shMetadataDto = shMetadataService.queryByName(dataSourceName); Byte datatype = shMetadataDto.getType(); Map<String, Object> map = new HashMap<>(); try { String dataSourcePth = "/" + shConfigDto.getRegNamespace() + "/" + shConfigDto.getDataSourceName() + Constants.CONFIG + Constants.DATASOURCE; String dataSource = curatorService.getData(dataSourcePth); JSONArray object1 = (JSONArray) JSONObject.parse(dataSource); for (int i = 0; i < object1.size(); i++) { JSONObject object = (JSONObject) object1.get(i); String password = Utils.druidEnc(object.getString("password")); object.remove("password"); object.put("password", password); } map.put("dataSource", JSONObject.toJSONString(object1)); if (Constants.MASTER_SLAVE_INTERGER.equals(datatype)) { String masterslaveRulePath = "/" + shConfigDto.getRegNamespace() + "/" + shConfigDto.getDataSourceName() + Constants.CONFIG + Constants.MASTERSLAVE + Constants.RUL; String masterslaveRule = curatorService.getData(masterslaveRulePath); String configmapPath = "/" + shConfigDto.getRegNamespace() + "/" + shConfigDto.getDataSourceName() + Constants.CONFIG + Constants.MASTERSLAVE + Constants.CONFIGMAP; String configmap = curatorService.getData(configmapPath); map.put("masterslaveRule", masterslaveRule); map.put("configmap", configmap); } else if (Constants.SHARDING_INTERGER.equals(datatype)) { String shardingRulePath = "/" + shConfigDto.getRegNamespace() + "/" + shConfigDto.getDataSourceName() + Constants.CONFIG + Constants.SHARDINGS + Constants.RUL; String shardingPropsPath = "/" + shConfigDto.getRegNamespace() + "/" + shConfigDto.getDataSourceName() + Constants.CONFIG + Constants.SHARDINGS + Constants.PROPS; String configmapPath = "/" + shConfigDto.getRegNamespace() + "/" + shConfigDto.getDataSourceName() + Constants.CONFIG + Constants.SHARDINGS + Constants.CONFIGMAP; String shardingRule = curatorService.getData(shardingRulePath); String shardingProps = curatorService.getData(shardingPropsPath); String configmap = curatorService.getData(configmapPath); map.put("configmap", configmap); map.put("shardingProps", shardingProps); map.put("shardingRule", shardingRule); } } catch (Exception e) { log.error("error queryConfigList", e); } shConfigDto.setZkInfo(map); } page.setRows(list); } @Override public void updateInfo(ShConfig shConfig) { shConfigMapper.updateInfo(shConfig); } @Override public void insertInfo(ShConfig shConfig) { shConfigMapper.insertInfo(shConfig); } @Override public Integer queryIdByRegNamespace(String name) { return shConfigMapper.queryIdByRegNamespace(name); } @Override public void deleteInfo(String id) { shConfigMapper.deleteInfo(NumberUtils.toInt(id)); } @Override public String queryDataSourceNameByid(int id) { return shConfigMapper.queryDataSourceNameByid(id); } @Override public void updateStatusById(Long id, byte type) { shConfigMapper.updateStatusById(id, type); } @Override public void updateStatusByDataSourceName(String name, Byte type) { shConfigMapper.updateStatusByDataSourceName(name, type); } @Override public List<ShConfig> queryByDataSourceName(String dataSourceName) { return shConfigMapper.queryByDataSourceName(dataSourceName); } } <file_sep>package com.caocao.shardingjdbc.console.dal.model; import lombok.Data; @Data public class ShConfig { private Long id; private String regNamespace; private String regId; private String regServerList; private String dataSourceName; private Byte status; private String createBy; private String updateBy; }<file_sep>package com.caocao.shardingjdbc.console.dto; import lombok.Data; import java.util.List; @Data public class ShMetadataDto { private Long id; private Byte type; private Byte quote; private String dataSourceName; private String createBy; private String updateBy; private String properties; private String typeValue;//type中文字段 private Integer masterId; //主库id private List<Integer> slaveIds;//从库ids private String loadBalanceAlgorithmType;//分片算法 private List<Integer> dataSourceNamesId;//分开分表使用的数据库id private Integer defaultDataSourceId; private String dataSourceNames; private String tableRuleConfigs; private String bindingTableGroups; private String props; } <file_sep>package com.caocao.shardingjdbc.console.common; import com.alibaba.fastjson.JSON; import lombok.extern.slf4j.Slf4j; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.recipes.cache.NodeCache; import org.apache.curator.framework.recipes.cache.NodeCacheListener; import org.apache.curator.framework.recipes.cache.PathChildrenCache; import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener; import org.apache.curator.retry.ExponentialBackoffRetry; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.data.Stat; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import org.springframework.util.Assert; import javax.annotation.PreDestroy; import java.util.List; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; /** * @author <EMAIL> * @version 1.0 * @since v1.0 2017/11/13 17:07 */ @Component @Slf4j public class CuratorService { private CuratorFramework client; @Value("${zk.connectionTimeoutMs:5000}") private int connectionTimeoutMs; @Value("${zk.sessionTimeoutMs:60000}") private int sessionTimeoutMs; public Boolean init(String connectString) { client = CuratorFrameworkFactory.builder() .connectString(connectString) .connectionTimeoutMs(connectionTimeoutMs) .sessionTimeoutMs(sessionTimeoutMs) .canBeReadOnly(false) .retryPolicy(new ExponentialBackoffRetry(1000, 3)) .build(); return initCuratorClient(); } private Boolean initCuratorClient() { client.start(); try { if (!client.blockUntilConnected(connectionTimeoutMs, TimeUnit.MILLISECONDS)) { client.close(); return false; } } catch (InterruptedException e) { log.error("error initCurator client", e); } return true; } @PreDestroy public void destroy() { client.close(); } public String create(String path) throws Exception { return createwithMode(path, "", CreateMode.PERSISTENT); } public String create(String path, String data) throws Exception { Assert.notNull(data, "data must be not null"); return createwithMode(path, data, CreateMode.PERSISTENT); } public String create(String path, Object data) throws Exception { Assert.notNull(data, "data must be not null"); return createwithMode(path, data, CreateMode.PERSISTENT); } public String createwithMode(String path, CreateMode createMode) throws Exception { return client.create().creatingParentsIfNeeded().withMode(createMode).forPath(path); } public String createwithMode(String path, String data, CreateMode createMode) throws Exception { Assert.notNull(data, "data must be not null"); return client.create().creatingParentsIfNeeded().withMode(createMode) .forPath(path, data.getBytes()); } public String createwithMode(String path, Object data, CreateMode createMode) throws Exception { Assert.notNull(data, "data must be not null"); return client.create().creatingParentsIfNeeded().withMode(createMode) .forPath(path, JSON.toJSONBytes(data)); } public Stat update(String path) throws Exception { return client.setData().forPath(path); } public Stat update(String path, String data) throws Exception { Assert.notNull(data, "data must be not null"); return client.setData().forPath(path, data.getBytes()); } public Stat update(String path, Object data) throws Exception { Assert.notNull(data, "data must be not null"); return client.setData().forPath(path, JSON.toJSONBytes(data)); } public void delete(String path) throws Exception { client.delete().deletingChildrenIfNeeded().inBackground().forPath(path); } public String getData(String path) throws Exception { return new String(client.getData().forPath(path)); } public <T> T getData(String path, Class<T> valueType) throws Exception { return JSON.parseObject(client.getData().forPath(path), valueType); } public List<String> getChildren(String path) { try { return client.getChildren().forPath(path); } catch (Exception e) { //node not exist throw this exception return null; } } public boolean isExists(String path) throws Exception { return client.checkExists().forPath(path) != null; } /** * 用来监控一个ZNode的子节点. 当一个子节点增加, 更新,删除时, Path Cache会改变它的状态, 会包含最新的子节点, 子节点的数据和状态。 */ public PathChildrenCache addListener(String path, PathChildrenCacheListener pathChildrenCacheListener, Executor executor) throws Exception { //设置节点的cache PathChildrenCache pathChildrenCache = new PathChildrenCache(client, path, true); //设置监听器和处理过程 pathChildrenCache.getListenable().addListener(pathChildrenCacheListener, executor); //开始监听 pathChildrenCache.start(); return pathChildrenCache; } public PathChildrenCache addListener(String path, PathChildrenCacheListener pathChildrenCacheListener, PathChildrenCache.StartMode startMode, Executor executor) throws Exception { //设置节点的cache PathChildrenCache pathChildrenCache = new PathChildrenCache(client, path, true); //设置监听器和处理过程 pathChildrenCache.getListenable().addListener(pathChildrenCacheListener, executor); //开始监听 pathChildrenCache.start(startMode); return pathChildrenCache; } /** * 当节点的数据修改或者删除时,Node Cache能更新它的状态包含最新的改变。操作和Path cache类似, 只是getCurrentData()返回的类型不同 */ public void addListener(String path, NodeCacheListener nodeCacheListener, Executor executor) throws Exception { //设置节点的cache NodeCache nodeCache = new NodeCache(client, path); //设置监听器和处理过程 nodeCache.getListenable().addListener(nodeCacheListener, executor); //开始监听 nodeCache.start(); } } <file_sep>CREATE TABLE `sh_config` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `reg_namespace` varchar(64) NOT NULL COMMENT '注册中心的命名空间', `reg_id` varchar(64) NOT NULL COMMENT '注册中心名称', `reg_server_list` varchar(64) NOT NULL COMMENT '注册中心地址', `data_source_name` varchar(64) NOT NULL COMMENT '数据源名称', `status` tinyint(3) unsigned NOT NULL DEFAULT '0' COMMENT '同步状态,0表示未同步,1表示已同步,2表示已修改待同步', `create_by` varchar(32) NOT NULL COMMENT '创建人', `update_by` varchar(32) NOT NULL COMMENT '修改人', `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '修改时间', PRIMARY KEY (`id`), KEY `idx_create_time` (`create_time`), KEY `idx_update_time` (`update_time`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='分片配置表'; CREATE TABLE `sh_metadata` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID', `type` tinyint(3) unsigned NOT NULL DEFAULT '1' COMMENT '数据库类型,1-mysql,2-ms,3-shard', `properties` text NOT NULL COMMENT '数据库属性', `data_source_name` varchar(64) NOT NULL COMMENT '数据库名称', `create_by` varchar(32) NOT NULL COMMENT '创建人', `update_by` varchar(32) NOT NULL COMMENT '修改人', `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '修改时间', PRIMARY KEY (`id`), KEY `idx_create_time` (`create_time`), KEY `idx_update_time` (`update_time`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='分片数据源表'; <file_sep>package com.caocao.shardingjdbc.console.dal.ldap; import com.sun.org.apache.xerces.internal.impl.dv.util.Base64; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.naming.Context; import javax.naming.NamingException; import javax.naming.directory.DirContext; import javax.naming.directory.InitialDirContext; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Hashtable; @Slf4j @Component("ldapHelper") public class LdapHelper { private DirContext ctx; @Autowired private LdapConfig ldapConfig; @SuppressWarnings(value = "unchecked") public DirContext getCtx() { //设置连接LDAP的实现工厂 Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); // 指定LDAP服务器的主机名和端口号 env.put(Context.PROVIDER_URL, ldapConfig.getProviderUrl() + ldapConfig.getRoot()); //给环境提供认证方法 env.put(Context.SECURITY_AUTHENTICATION, "simple"); //指定进入的目录识别名DN env.put(Context.SECURITY_PRINCIPAL, "cn=" + ldapConfig.getAccount()); //进入的目录密码 env.put(Context.SECURITY_CREDENTIALS, ldapConfig.getPassword().trim()); log.info(ldapConfig.getProviderUrl() + ldapConfig.getRoot()); log.info(ldapConfig.getAccount()); log.info(ldapConfig.getPassword()); try { // 链接ldap // 得到初始目录环境的一个引用 ctx = new InitialDirContext(env); log.info("认证成功"); } catch (javax.naming.AuthenticationException e) { log.error("认证失败", e); } catch (Exception e) { log.error("认证出错:", e); } return ctx; } public void closeCtx() { try { ctx.close(); } catch (NamingException ex) { log.error("error close ctx", ex); } } @SuppressWarnings(value = "unchecked") public boolean verifySHA(String ldappw, String inputpw) throws NoSuchAlgorithmException { // MessageDigest 提供了消息摘要算法,如 MD5 或 SHA,的功能,这里LDAP使用的是SHA-1 MessageDigest md = MessageDigest.getInstance("SHA-1"); // 取出加密字符 if (ldappw.startsWith("{SSHA}")) { ldappw = ldappw.substring(6); } else if (ldappw.startsWith("{SHA}")) { ldappw = ldappw.substring(5); } // 解码BASE64 byte[] ldappwbyte = Base64.decode(ldappw); byte[] shacode; byte[] salt; // 前20位是SHA-1加密段,20位后是最初加密时的随机明文 if (ldappwbyte.length <= 20) { shacode = ldappwbyte; salt = new byte[0]; } else { shacode = new byte[20]; salt = new byte[ldappwbyte.length - 20]; System.arraycopy(ldappwbyte, 0, shacode, 0, 20); System.arraycopy(ldappwbyte, 20, salt, 0, salt.length); } // 把用户输入的密码添加到摘要计算信息 md.update(inputpw.getBytes()); // 把随机明文添加到摘要计算信息 md.update(salt); // 按SSHA把当前用户密码进行计算 byte[] inputpwbyte = md.digest(); // 返回校验结果 return MessageDigest.isEqual(shacode, inputpwbyte); } }
bfe046f3d1c005f30fa9b30231a4a4655c6e6d5c
[ "Java", "SQL" ]
9
Java
maozhibin/sharding-jdbc-console
98bdc0d3b3b51408476c518acd3e67bb9c4d978c
1e41a1b84ea253c8142929392843510b490170e5
refs/heads/main
<repo_name>singh102/DePaul-SE452-Group8<file_sep>/espy/src/main/java/com/depaul/se452/group8/espy/Profile.java package com.depaul.se452.group8.espy; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class Profile { @RequestMapping("/profile") public String profile() { return "Profile Page!"; } } <file_sep>/espy/src/main/java/com/depaul/se452/group8/espy/Friends.java package com.depaul.se452.group8.espy; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class Friends { @RequestMapping("/friends") public String friends() { return "Friends Page!"; } } <file_sep>/espy/readme.md Espy An image sharing application amongst friends Current pages include: - localhost:8080 - localhost:8080/profile - localhost:8080/friendsearch - localhost:8080/friends
b45ff787b3c20aa09e9377591ea7e857b8ccbd87
[ "Markdown", "Java" ]
3
Java
singh102/DePaul-SE452-Group8
4ce893941e13d33ff27b6d73b761f71d12ae13c1
ea765b8fcd18b84fca2c65fc84ea941cabdeb768
refs/heads/master
<repo_name>Edlward/robomaster<file_sep>/XDRM_OMNIKNIGHT/Inc/StatusMachine.h #ifndef __STATUSMACHINE_H #define __STATUSMACHINE_H #include "Driver_Beltraise.h" #include "Driver_Chassis.h" #include "Driver_GuideWheel.h" #include "Driver_Manipulator.h" #include "Driver_Remote.h" #include "Driver_Sensor.h" #include "config.h" void StatusMachine_Init(void); void StatusMachine(void const * argument); extern InputMode_e InputMode; #endif <file_sep>/XDRM_OMNIKNIGHT/MDK-ARM/XDRM_OMNIKNIGHT/XDRM_OMNIKNIGHT.build_log.htm <html> <body> <pre> <h1>µVision Build Log</h1> <h2>Tool Versions:</h2> IDE-Version: ¦ÌVision V5.22.0.0 Copyright (C) 2016 ARM Ltd and ARM Germany GmbH. All rights reserved. License Information: 111 ΢ÈíÓû§, ΢ÈíÖйú, LIC=9WSCX-HFU0W-CWC2K-ZF8U8-PV1YG-FN170 Tool Versions: Toolchain: MDK-ARM Plus Version: 5.22 Toolchain Path: D:\stm32\mdk\ARM\ARMCC\Bin C Compiler: Armcc.exe V5.06 update 4 (build 422) Assembler: Armasm.exe V5.06 update 4 (build 422) Linker/Locator: ArmLink.exe V5.06 update 4 (build 422) Library Manager: ArmAr.exe V5.06 update 4 (build 422) Hex Converter: FromElf.exe V5.06 update 4 (build 422) CPU DLL: SARMCM3.DLL V5.22 Dialog DLL: DCM.DLL V1.13.9.0 Target DLL: STLink\ST-LINKIII-KEIL_SWO.dll V2.0.18.0 Dialog DLL: TCM.DLL V1.21.0.0 <h2>Project:</h2> F:\Robomaster\git repertory\XDRM_OMNIKNIGHT\MDK-ARM\XDRM_OMNIKNIGHT.uvprojx Project File Date: 03/10/2019 <h2>Output:</h2> *** Using Compiler 'V5.06 update 4 (build 422)', folder: 'D:\stm32\mdk\ARM\ARMCC\Bin' Build target 'XDRM_OMNIKNIGHT' compiling BSP.c... compiling Data_Judge.c... compiling stm32f4xx_it.c... compiling BSP_NVIC.c... compiling BSP_USART.c... ..\Src\BSP_USART.c(226): error: #127: expected a statement else if(huart->Instance==USART6) ..\Src\BSP_USART.c(248): warning: #12-D: parsing restarts here after previous syntax error hdma_usart6_rx.Init.Channel = MA_CHANNEL_5; ..\Src\BSP_USART.c(265): error: #20: identifier "huart" is undefined _HAL_LINKDMA(huart,hdmarx,hdma_usart6_rx); ..\Src\BSP_USART.c(284): error: #20: identifier "huart" is undefined _HAL_LINKDMA(huart,hdmatx,hdma_usart6_tx); ..\Src\BSP_USART.c(295): error: #169: expected a declaration } ..\Src\BSP_USART.c(356): warning: At end of source: #12-D: parsing restarts here after previous syntax error ..\Src\BSP_USART.c: 2 warnings, 4 errors "XDRM_OMNIKNIGHT\XDRM_OMNIKNIGHT.axf" - 4 Error(s), 2 Warning(s). <h2>Software Packages used:</h2> Package Vendor: ARM http://www.keil.com/pack/ARM.CMSIS.5.0.0.pack ARM::CMSIS:CORE:5.0.0 CMSIS (Cortex Microcontroller Software Interface Standard) * Component: CORE Version: 5.0.0 <h2>Collection of Component include folders:</h2> F:\Robomaster\git repertory\XDRM_OMNIKNIGHT\MDK-ARM\RTE\_XDRM_OMNIKNIGHT D:\stm32\mdk\ARM\PACK\ARM\CMSIS\5.0.0\CMSIS\Include D:\stm32\mdk\ARM\PACK\Keil\STM32F4xx_DFP\2.11.0\Drivers\CMSIS\Device\ST\STM32F4xx\Include <h2>Collection of Component Files used:</h2> * Component: ARM::CMSIS:CORE:5.0.0 Target not created. Build Time Elapsed: 00:00:19 </pre> </body> </html> <file_sep>/XDRM_OMNIKNIGHT/Src/StatusMachine.c #include "StatusMachine.h" #include "SuperviseTask.h" #include "ControlTask.h" WorkState_e WorkState; WorkState_e LastWorkState = STOP_STATE; extern uint32_t time_tick_1ms; static void WorkStateSwitchProcess(void) { //如果从其他模式切换到prapare模式,要将一系列参数初始化 if((LastWorkState != WorkState) && (WorkState == PREPARE_STATE)) { ControlLoopTaskInit(); RemoteTaskInit(); } } void SetWorkState(WorkState_e state) { WorkState = state; } WorkState_e GetWorkState(void) { return WorkState; } void WorkStateFSM(void) { //几种直接换状态的特殊情况 LastWorkState = WorkState; if(Is_Lost_Error_Set(LOST_ERROR_RC) || InputMode == STOP) //存疑,直接使用InputMode和使用函数GetInputMode()有什么区别,我暂时认为没有区别 { WorkState = STOP_STATE; return; }//还没有加陀螺仪以及校准功能,所以目前只有遥控器失控这一种特殊状况 switch (WorkState) { case PREPARE_STATE: { if(time_tick_1ms > PREPARE_TIME_TICK_MS) { if(InputMode == REMOTE_INPUT) { WorkState = NORMAL_RC_STATE; } if(InputMode == KEYBOARD_INPUT) { WorkState = KEYBOARD_RC_STATE; } } }break; case NORMAL_RC_STATE: { if(InputMode == STOP) { WorkState = STOP_STATE; } }break; case KEYBOARD_RC_STATE: { if(InputMode == STOP) { WorkState = STOP_STATE; } }break; case STOP_STATE: { if(InputMode != STOP) { WorkState = PREPARE_STATE; } }break; } WorkStateSwitchProcess(); } void Input_Mode_Select(void) { if(RC_CtrlData.rc.s2 == STICK_UP) { InputMode = REMOTE_INPUT; } if(RC_CtrlData.rc.s2 == STICK_CENTRAL) { InputMode = KEYBOARD_INPUT; } if(RC_CtrlData.rc.s2 == STICK_DOWN) { InputMode = STOP; } } InputMode_e GetInputMode(void) { return InputMode; } void StatusMachine_Init(void) { WorkState = PREPARE_STATE; } void StatusMachine_Update(void) { Input_Mode_Select(); WorkStateFSM(); } void StatusMachine(void const * argument) { portTickType xLastWakeTime; xLastWakeTime = xTaskGetTickCount(); /* Infinite loop */ for(;;) { StatusMachine_Update(); vTaskDelayUntil(&xLastWakeTime,1/portTICK_RATE_MS);//此时处于阻塞态 } /* USER CODE END Can_Send_Task */ }
bcbb0c48997c50052a5c0b534944cd790c32cb42
[ "C", "HTML" ]
3
C
Edlward/robomaster
54eede527114762fa859e8f1cea0dc5022fdac92
af7071c0be9dff7b248b95c32b6f3752b8c06577
refs/heads/master
<file_sep>from profile_fragment_quality import ProfileFragmentQuality, ProfileFragmentQualityResult <file_sep># Running Demos 1) Ensure that you have activated an environment with `rosetta` and `fragment_profiling` installed. 2) Ensure that you have correctly configured `ipython` to display notebooks by adding the following to `~/.ipython/profile_default/ipython_notebook_config.py`: ````python import socket c.NotebookApp.ip = socket.gethostname() c.NotebookApp.open_browser = False c.NotebookApp.port = 8888 ```` 3) Run `ipython notebook` in the `examples` directory and open the displayed url. <file_sep>import unittest import logging import os from os import path import numpy from interface_fragment_matching.fragment_fitting.lookup import FragmentMatchLookup from interface_fragment_matching.fragment_fitting.store import FragmentDatabase, FragmentSpecification from interface_fragment_matching.structure_database import StructureDatabase from fragment_profiling.profile_backbone_quality import ProfileBackboneQuality class TestProfileBackboneQuality(unittest.TestCase): @classmethod def setUpClass(cls): import rosetta rosetta.init("-out:levels", "all:warning") from interface_fragment_matching.parallel import openmp_utils openmp_utils.omp_set_num_threads(1) def setUp(self): import rosetta fragment_db = FragmentDatabase("/work/fordas/workspace/fragment_fitting/threshold_test_fragments/test_sets.h5") self.test_fragments = fragment_db.fragments["source_fragments_4_mer"].read() test_fragment_length = fragment_db.fragments["source_fragments_4_mer"].attrs.fragment_length test_fragment_atoms = fragment_db.fragments["source_fragments_4_mer"].attrs.fragment_atoms.split(",") self.test_fragment_spec = FragmentSpecification(test_fragment_length, tuple(test_fragment_atoms)) pass_test_structure = rosetta.pose_from_pdb(path.join(path.dirname(__file__), "foldit_17_0001.pdb" )) self.pass_test_residues = StructureDatabase.extract_residue_entries_from_pose(pass_test_structure) _, self.pass_test_fragments = self.test_fragment_spec.fragments_from_source_residues(self.pass_test_residues) fail_test_structure = rosetta.pose_from_pdb(path.join(path.dirname(__file__), "foldit_18_0001.pdb" )) self.fail_test_residues = StructureDatabase.extract_residue_entries_from_pose(fail_test_structure) _, self.fail_test_fragments = self.test_fragment_spec.fragments_from_source_residues(self.fail_test_residues) def test_profiler(self): profiler = ProfileBackboneQuality(self.test_fragments, self.test_fragment_spec) pass_results = profiler.perform_backbone_analysis(self.pass_test_fragments).result_summary self.assertTrue(not any(numpy.isnan(pass_results["match_distance"]))) profiler = ProfileBackboneQuality(self.test_fragments, self.test_fragment_spec) fail_results = profiler.perform_backbone_analysis(self.fail_test_fragments).result_summary self.assertTrue(any(numpy.isinf(fail_results["match_distance"]))) <file_sep>#!/usr/bin/env python from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages, Extension from Cython.Distutils import build_ext from Cython.Build import cythonize from os import path import subprocess #Cython extensions can be built in the standard fashion via distribute #but files including numpy headers must have numpy include path specified. import numpy #Versioning logic def get_git_version(): """Get current version tag via call to git describe. Version tags are of the format: v<major>.<minor>.<patch> """ try: version_string = subprocess.check_output(["git", "describe", "--match", "v*"]) return version_string.strip().lstrip("v") except: return "0.0.0" #Cython build logic cython_subdirs = [ "fragment_profiling", ] cython_modules= cythonize([path.join(d, "*.pyx") for d in cython_subdirs]) for r in cython_modules: r.extra_compile_args=["-fopenmp"] r.extra_link_args=["-fopenmp"] def pkgconfig(*packages, **kw): flag_map = {'-I': 'include_dirs', '-L': 'library_dirs', '-l': 'libraries'} for token in subprocess.check_output(["pkg-config", "--libs", "--cflags"] + list(packages)).strip().split(" "): kw.setdefault(flag_map.get(token[:2]), []).append(token[2:]) return kw include_dirs = [numpy.get_include(), path.abspath(".")] setup( name="fragment_profiling", description="Modules for structure fragment profiling.", author="<NAME>", author_email="<EMAIL>", url="https://github.com/fordas/fragment_profiling/", version=get_git_version(), provides=["fragment_profiling"], packages=find_packages(), install_requires=["interface_fragment_matching", "numpy", "matplotlib"], setup_requires=["Cython>=0.18"], tests_require=["nose", "nose-html", "coverage", "nose-progressive"], test_suite = "nose.collector", cmdclass = {'build_ext': build_ext}, #Extra options to cythonize are *not* the same 'Extension' #See Cython.Compiler.Main.CompilationOptions for details # #In particular, include_dirs must be specified in setup # as opposed to Extension if globs are used. include_dirs=include_dirs, ext_modules = cython_modules ) <file_sep>import logging import numpy from interface_fragment_matching.tasks.utility import TaskBase from interface_fragment_matching.structure_database.store import StructureDatabase from .profile_fragment_quality import ProfileFragmentQuality, FragmentProfilerParameters from .store import FragmentProfilingDatabase # Set default omp parameters for interactive use from interface_fragment_matching.parallel import openmp_utils if not openmp_utils.omp_get_max_threads(): logging.warning("omp_set_num_threads(%s)", 4) openmp_utils.omp_set_num_threads(4) class ProfileFragmentQualityTask(TaskBase): """Perform fragment quality profiling on structure residues.""" @property def state_keys(self): return ["fragment_specification", "profile_source_database", "logscore_substitution_profile", "select_fragments_per_query_position"] def __init__(self, fragment_specification, profile_source_database, logscore_substitution_profile, select_fragments_per_query_position): """Create profiling task. fragent_specifiction - Specifiction used to defined profiled fragments. profile_source_database - Source database to profiling queries. logscore_substitution_profile - Substitution profile used in profiler. select_fragments_per_query_position - Result fragments per position. """ self.fragment_specification = fragment_specification self.profile_source_database = profile_source_database self.logscore_substitution_profile = logscore_substitution_profile self.select_fragments_per_query_position = select_fragments_per_query_position TaskBase.__init__(self) def setup(self): """Load source structure database and prepare profiler.""" source_residues = StructureDatabase(self.profile_source_database).residues.read() self.profiler = ProfileFragmentQuality( source_residues, self.logscore_substitution_profile, self.select_fragments_per_query_position) TaskBase.setup(self) def execute(self, target_residues): """Segment target residues into fragments and perform per-fragment profiling.""" _, target_fragments = self.fragment_specification.fragments_from_source_residues( target_residues, additional_per_residue_fields=["bb", "sc", "ss"]) return self.profiler.perform_fragment_analysis(target_fragments) class BenchmarkedProfileFragmentQualityTask(TaskBase): """Perform fragment quality profiling on structure residues via a benchmarked profiling configuration.""" @property def state_keys(self): return ["profiling_database", "profile_benchmark_name", "profiler_parameters"] def __init__(self, profiling_database, profile_benchmark_name, profiler_parameters): """Create profiling task. profiling_database - Source profiling database. profile_benchmark_name - Source profiling database. profiler_parameters - Profiling parameters for run. """ self.profiling_database = profiling_database self.profile_benchmark_name = profile_benchmark_name self.profiler_parameters = profiler_parameters TaskBase.__init__(self) def setup(self): """Load source structure database and prepare profiler.""" with FragmentProfilingDatabase(self.profiling_database) as prof_db: source_residues, source_benchmarks = prof_db.get_profiling_benchmark(self.profile_benchmark_name) if not self.profiler_parameters in source_benchmarks: raise ValueError("Provided profiler_parameters %s not present in database. Available parameters:\n%s", self.profiler_parameters, source_benchmarks.keys()) self.profiler = ProfileFragmentQuality( source_residues, self.profiler_parameters.logscore_substitution_profile, self.profiler_parameters.select_fragments_per_query_position, source_benchmarks) TaskBase.setup(self) def execute(self, target_residues): """Segment target residues into fragments and perform per-fragment profiling.""" _, target_fragments = self.profiler_parameters.fragment_specification.fragments_from_source_residues( target_residues, additional_per_residue_fields=["bb", "sc", "ss"]) return self.profiler.perform_fragment_analysis(target_fragments) class BenchmarkProfileFragmentQualityTask(ProfileFragmentQualityTask): @property def state_keys(self): return super(BenchmarkProfileFragmentQualityTask, self).state_keys + ["target_structure_database", "return_fragments_per_query_position"] def __init__(self, target_structure_database, fragment_specification, profile_source_database, logscore_substitution_profile, select_fragments_per_query_position, return_fragments_per_query_position): ProfileFragmentQualityTask.__init__(self, fragment_specification, profile_source_database, logscore_substitution_profile, select_fragments_per_query_position) self.target_structure_database = target_structure_database self.return_fragments_per_query_position = return_fragments_per_query_position def setup(self): super(BenchmarkProfileFragmentQualityTask, self).setup() self.target_residue_cache = StructureDatabase(self.target_structure_database).residue_cache def execute(self, target_structure_ids): self.logger.info("execute(<%s ids>)", len(target_structure_ids)) ids = numpy.atleast_1d(numpy.array(target_structure_ids)).astype("u4") spans = self.target_residue_cache.id_span(ids) source_residues = numpy.concatenate([self.target_residue_cache.residues[spans[i]["start"]:spans[i]["end"]] for i in xrange(len(spans))]) self.logger.info("source_residues: <%s residues> ", len(source_residues)) result = ProfileFragmentQualityTask.execute(self, source_residues) return result.prune_fragments_by_start_residue().generate_result_summary(self.return_fragments_per_query_position) <file_sep>import logging import os from os import path import itertools import tables class FragmentProfilingDatabase(object): logger = logging.getLogger("FragmentProfilingDatabase") """Table-backed fragment profiling database. Stores residue reference and fragment profiling benchmarking data. Contains table entries: /fragment_profiling_benchmarks/ """ def __init__(self, store): """Load fragment database view over store.""" self.store = None if isinstance(store, basestring): self.logger.info("Opening file: %s", store) try: is_store = tables.is_pytables_file(store) except tables.HDF5ExtError: is_store = False if is_store: if os.access(store, os.W_OK): self.store = tables.open_file(store, "r+") else: self.store = tables.open_file(store, "r") else: raise ValueError("Store is not a PyTables file: %s" % store) elif isinstance(store, tables.file.File): self.logger.info("Opening : %s", store) self.store = store else: raise ValueError("Unable to open store: %s" % store) def __hash__(self): return hash(self.store.filename) def __repr__(self): return "%s(store=<%s>)" % ( self.__class__.__name__, self.store.filename) def __enter__(self): """Support for with statement.""" return self def __exit__(self, *args, **kwargs): """Support for with statement.""" self.close() def close(self): """Close database handle and underlying store.""" if self.store is not None: self.logger.debug("Closing store: %s", self.store) self.store.close() def is_setup(self): """Check if database is setup with standard paths.""" return ("/fragment_profiling_benchmarks" in self.store) def setup(self): """Create core tables and groups within store.""" self.logger.info("Setting up store: %s", self.store) self.store.create_group("/", "fragment_profiling_benchmarks", "Profiling benchmark sets.") self.store.flush() @property def profiling_benchmarks(self): """Return list of fragment profiling benchmark sets.""" return set(i._v_name for i in self.store.iter_nodes("/fragment_profiling_benchmarks")) def add_profiling_benchmark(self, name, target_residue_table, profiling_results): """Add profiler benchmark data to database.""" self.store.create_group("/fragment_profiling_benchmarks", name, name) groupname = path.join("/fragment_profiling_benchmarks", name) if ":" in target_residue_table: self.store.create_external_link(groupname, "residues", target_residue_table) else: self.store.create_soft_link(groupname, "residues", target_residue_table) self.store.create_group(groupname, "benchmark_sets", "Calculated benchmark distributions for target residues.") benchmark_group = path.join(groupname, "benchmark_sets") for c, (params, quantile_results) in zip(itertools.count(), profiling_results.items()): qt = self.store.create_table(benchmark_group, "profile_%i" % c, quantile_results) qt.attrs["profile_parameters"] = params qt.flush() self.store.flush() def get_profiling_benchmark(self, name): """Get profiler data from the given benchmark set name.""" profiler_residues = self.store.get_node(path.join("/fragment_profiling_benchmarks", name, "residues")) profiler_residues = profiler_residues().read() profiler_benchmarks = {} for b in self.store.get_node(path.join("/fragment_profiling_benchmarks", name, "benchmark_sets")): profiler_benchmarks[b.attrs["profile_parameters"]] = b.read() return profiler_residues, profiler_benchmarks <file_sep>import unittest import numpy import numpy.testing from interface_fragment_matching.fragment_fitting.rmsd_calc import atom_array_broadcast_rmsd from interface_fragment_matching.fragment_fitting.store import FragmentSpecification from interface_fragment_matching.structure_database import StructureDatabase from fragment_profiling.profile_fragment_quality import ProfileFragmentQuality class TestProfileFragmentQuality(unittest.TestCase): @classmethod def setUpClass(cls): from interface_fragment_matching.parallel import openmp_utils openmp_utils.omp_set_num_threads(2) def setUp(self): structure_db = StructureDatabase("/work/fordas/test_sets/vall_store.h5") test_structure_residues = structure_db.residues.readWhere("id == 1") self.test_fragment_spec = FragmentSpecification(9, "CA") self.source_test_segment = test_structure_residues[:self.test_fragment_spec.fragment_length + 2] self.test_structures = numpy.empty((750, len(self.source_test_segment)), self.source_test_segment.dtype) self.test_structures[:] = numpy.expand_dims(self.source_test_segment, 0) self.test_structures["id"] = numpy.arange(750).reshape((750, 1)) self.test_structures["sc"]["aa"] = "A" self.test_structures["sc"]["aa"][...,-2:] = "G" _, self.test_query_fragments = self.test_fragment_spec.fragments_from_source_residues( self.source_test_segment, additional_per_residue_fields=["bb", "sc", "ss"]) self.test_query_rmsds = atom_array_broadcast_rmsd( self.test_query_fragments["coordinates"], self.test_query_fragments["coordinates"]) def test_profiler(self): query_fragment = self.test_query_fragments[1].copy() query_fragment["sc"]["aa"] = self.test_structures[0]["sc"]["aa"][:9] # Perform query w/ fragment 0 sequence and fragment 1 conformation. # Should select all fragment 0 instances profiler_one = ProfileFragmentQuality(self.test_structures.ravel(), "blosum100", 750) result_one = profiler_one.perform_fragment_analysis(numpy.expand_dims(query_fragment, 0)) numpy.testing.assert_array_almost_equal( result_one.selected_fragment_rmsds, numpy.repeat(self.test_query_rmsds[0,1], 750).reshape(1, 750)) numpy.testing.assert_array_almost_equal( result_one.selected_fragments["resn"], numpy.repeat(self.test_query_fragments[0]["resn"], 750).reshape(1, 750)) numpy.testing.assert_array_almost_equal( numpy.sort(result_one.selected_fragments["id"].ravel()), numpy.arange(750)) # Should select all fragment 0 and single fragment 1 profiler_two = ProfileFragmentQuality(self.test_structures.ravel(), "blosum100", 750 * 2) result_two = profiler_two.perform_fragment_analysis(numpy.expand_dims(query_fragment, 0)) numpy.testing.assert_array_almost_equal( numpy.sort(result_two.selected_fragment_rmsds), numpy.repeat( [self.test_query_rmsds[0, 0], self.test_query_rmsds[0,1]], 750).reshape(1, 750 * 2)) numpy.testing.assert_array_almost_equal( numpy.sort(result_two.selected_fragments["resn"]), numpy.repeat( [self.test_query_fragments[0]["resn"], self.test_query_fragments[1]["resn"]], 750).reshape(1, 750 * 2)) numpy.testing.assert_array_almost_equal( numpy.sort(result_two.selected_fragments["id"].ravel()), numpy.repeat(numpy.arange(750), 2)) <file_sep>#ifndef _fragment_fitting_rmsd_calc_QCP_Kernal_HPP_ #define _fragment_fitting_rmsd_calc_QCP_Kernal_HPP_ #include <cstdlib> #include <algorithm> #include <functional> #include <limits> #include <queue> #include <utility> #include <vector> namespace fragment_profiling { template <class Real, class AlphabetIntegralType, class Index> class ProfileCalculator { public: ProfileCalculator() {} virtual ~ProfileCalculator() {} int select_by_additive_profile_score( Real* input_profile, int sequence_length, int alphabet_size, AlphabetIntegralType* source_sequences, Index* source_start_indicies, int num_sequences, Index* result_indicies, Real* result_scores, int result_count) { typedef typename std::pair<Real, Index> ScorePair; typedef typename std::priority_queue< ScorePair, std::vector<ScorePair>, std::greater<ScorePair> > ResultQueue; ResultQueue global_results; #pragma omp parallel { ResultQueue local_results; #pragma omp for schedule(static) for (int n = 0; n < num_sequences; n++) { ScorePair index_score(0, source_start_indicies[n]); for (int p = 0; p < sequence_length; p++) { index_score.first += input_profile[(p * alphabet_size) + source_sequences[source_start_indicies[n] + p]]; } if (local_results.size() < result_count || index_score > local_results.top()) { local_results.push(index_score); while (local_results.size() > result_count) { local_results.pop(); } } } #pragma omp critical { while (!local_results.empty()) { if(global_results.size() < result_count || local_results.top() > global_results.top()) { global_results.push(local_results.top()); while (global_results.size() > result_count) { global_results.pop(); } } local_results.pop(); } } } int final_result_count; for (final_result_count = 0; !global_results.empty(); final_result_count++) { result_indicies[final_result_count] = global_results.top().second; result_scores[final_result_count] = global_results.top().first; global_results.pop(); } return final_result_count; } void extract_additive_profile_scores( Real* input_profile, int sequence_length, int alphabet_size, AlphabetIntegralType* source_sequences, Index* source_start_indicies, int num_sequences, Real* outscore) { #pragma omp parallel for schedule(static) for (int n = 0; n < num_sequences; n++) { outscore[n] = 0; for (int p = 0; p < sequence_length; p++) { outscore[n] += input_profile[(p * alphabet_size) + source_sequences[source_start_indicies[n] + p]]; } } } }; } #endif <file_sep>import logging logging.basicConfig(level=logging.INFO, format="%(asctime)-15s - %(name)s - %(levelname)s - %(message)s") import itertools import jug from jug import Task, TaskGenerator, Tasklet, bvalue, barrier from jug.compound import CompoundTask import numpy import tables import rosetta from interface_fragment_matching.parallel.utility import map_partitions from interface_fragment_matching.structure_database.store import StructureDatabase from interface_fragment_matching.fragment_fitting.store import FragmentSpecification from fragment_profiling.tasks import BenchmarkProfileFragmentQualityTask from fragment_profiling.store import FragmentProfilingDatabase from fragment_profiling.profile_fragment_quality import FragmentProfilerParameters def read_structure_ids(db): return StructureDatabase(db).structures.read()["id"] def agglomerative_reduction_task(reduction_function, maximum_reduction_entries, sub_values): if len(sub_values) <= maximum_reduction_entries: return Task(reduction_function, sub_values) splits = range(0, len(sub_values), maximum_reduction_entries) subresults = [agglomerative_reduction_task(reduction_function, maximum_reduction_entries, sub_values[s:e]) for s, e in zip(splits, splits[1:] + [len(sub_values)])] return Task(reduction_function, subresults) def agglomerative_reduce(reduction_function, maximum_reduction_entries, values): return CompoundTask(agglomerative_reduction_task, reduction_function, maximum_reduction_entries, values) def extract_result_summary_table(result): summary_table = numpy.empty( result.query_fragments.shape, dtype = result.query_fragments[["id", "resn"]].dtype.descr + [("lookup_rmsd", result.selected_fragment_rmsds.dtype, result.selected_fragment_rmsds[0].shape)]) summary_table["id"] = result.query_fragments["id"] summary_table["resn"] = result.query_fragments["resn"] summary_table["lookup_rmsd"] = numpy.sort(result.selected_fragment_rmsds, axis=-1) return summary_table # Define function so jug status show more informative name than 'concatenate' def reduce_result_summary(summary_data): return numpy.concatenate(summary_data) def profile_structure_collection(target_structure_database, target_ids, fragment_specification, profile_source_database, logscore_substitution_profile, select_fragments_per_query_position, keep_top_fragments_per_query_position): # Add one to result set size to accommodate fragment pruning. profiler_task = BenchmarkProfileFragmentQualityTask(target_structure_database, fragment_specification, profile_source_database, logscore_substitution_profile, select_fragments_per_query_position, keep_top_fragments_per_query_position) profiler_results = map_partitions(profiler_task, target_ids, 4000) result_summary = agglomerative_reduction_task(reduce_result_summary, 100, profiler_results) return result_summary def generate_quantile_summary(result_summary_table, quantiles = numpy.linspace(0, 1, 101)): from scipy.stats.mstats import mquantiles import pandas summary_table = pandas.DataFrame.from_items([("id", result_summary_table["id"]), ("rmsd", result_summary_table["quartile"][...,0])]) result = numpy.empty_like(quantiles, dtype=[("quantile", float), ("global_quantile_value", float), ("worst_per_structure_quantile_value", float)]) result["quantile"] = quantiles result["global_quantile_value"] = mquantiles(summary_table["rmsd"].values, quantiles) result["worst_per_structure_quantile_value"] = mquantiles(summary_table.groupby("id")["rmsd"].max().values, quantiles) return result def dict_element_product(options_dict): ks = options_dict.keys() return [tuple(zip(ks, vs)) for vs in itertools.product(*[options_dict[k] for k in ks])] profile_source_database = "/work/fordas/test_sets/vall_store.h5" target_structure_database = "/work/fordas/test_sets/vall_store.h5" target_ids = Task(read_structure_ids, target_structure_database) keep_top_fragments_per_query_position = 5 initial_candidate_parameter_values = dict( logscore_substitution_profile = ('blosum100',), select_fragments_per_query_position = (300, 200), fragment_specification = (FragmentSpecification(9, "CA"), FragmentSpecification(9, ("N", "CA", "C"))) ) query_size_sweep_parameter_values = dict( logscore_substitution_profile = ('blosum100',), select_fragments_per_query_position = (10, 20, 50, 100, 200, 400, 500, 1000), fragment_specification = (FragmentSpecification(9, "CA"), )) parameter_keys = initial_candidate_parameter_values.keys() logging.info("parameter_keys: %s", parameter_keys) parameter_sets = set(dict_element_product(initial_candidate_parameter_values) + dict_element_product(query_size_sweep_parameter_values)) result_summaries = [] quantile_summaries = [] for parameter_values in sorted(parameter_sets): input_parameter_values = dict(parameter_values) logging.info("parameter_values: %s", input_parameter_values) final_result_summary = CompoundTask( profile_structure_collection, target_structure_database, target_ids, input_parameter_values["fragment_specification"], profile_source_database, input_parameter_values["logscore_substitution_profile"], input_parameter_values["select_fragments_per_query_position"], keep_top_fragments_per_query_position) result_summaries.append((parameter_values, final_result_summary)) barrier() quantile_summaries.append((parameter_values, Task(generate_quantile_summary, final_result_summary))) def write_summary_store(store_name, collection_name, target_residue_name, quantile_summaries): quantile_summaries = dict(( FragmentProfilerParameters(**dict(q)), v) for q, v in quantile_summaries) with FragmentProfilingDatabase(tables.open_file(store_name, "w")) as profile_db: profile_db.setup() profile_db.add_profiling_benchmark(collection_name, "/work/fordas/test_sets/vall_store.h5:/residues", quantile_summaries) Task(write_summary_store, "vall_store_fragment_profiling.h5", "vall_benchmarking", "%s:/residues" % profile_source_database, quantile_summaries) <file_sep>import logging from collections import namedtuple import numpy from interface_fragment_matching.fragment_fitting.lookup import FragmentMatchLookup from interface_fragment_matching.fragment_fitting.store import FragmentDatabase, FragmentSpecification class ProfileBackboneQuality(object): logger = logging.getLogger("fragment_profiling.profile_backbone_quality.ProfileBackboneQuality") @staticmethod def from_database(fragment_database_name, fragment_group_name): """Initialize profiler from the given database path and fragment group.""" with FragmentDatabase(fragment_database_name) as fragment_database: test_fragments = fragment_database.fragments[fragment_group_name].read() test_fragment_length = fragment_database.fragments[fragment_group_name].attrs.fragment_length test_fragment_atoms = fragment_database.fragments[fragment_group_name].attrs.fragment_atoms.split(",") test_fragment_spec = FragmentSpecification(test_fragment_length, test_fragment_atoms) return ProfileBackboneQuality(test_fragments, test_fragment_spec) def __init__(self, source_fragments, fragment_spec): self.source_fragments = source_fragments self.fragment_spec = fragment_spec self.lookup = FragmentMatchLookup(self.source_fragments) def perform_backbone_analysis(self, query_fragments): """Perform backbone analysis on given fragments.""" query_fragment_coordinates = self.fragment_spec.fragments_to_coordinate_array(query_fragments) if not query_fragment_coordinates.shape[-2] == self.fragment_spec.fragment_length * len(self.fragment_spec.fragment_atoms): raise ValueError("query_fragments of incorrect length") lookup_result = self.lookup.closest_matching_fragment(query_fragment_coordinates) lookup_result_quantiles = numpy.ones_like(lookup_result, dtype=float) lookup_result_quantiles[numpy.isinf(lookup_result["match_distance"])] = numpy.nan return ProfileBackboneQualityResult(query_fragments, lookup_result, lookup_result_quantiles) class ProfileBackboneQualityResult(namedtuple("ProfileBackboneQualityResultTuple", ["query_fragments", "lookup_results", "lookup_result_quantiles"])): """Result container for fragment profiling runs.""" @property def result_summary(self): result_summary = numpy.zeros_like(self.lookup_results, dtype=[ ("query_id", "u4"), ("query_resn", "u4"), ("match_id", "u4"), ("match_resn", "u4"), ("match_distance", float), ("threshold_distance", float), ("match_quantile", float)]) result_summary["query_id"] = self.query_fragments["id"] result_summary["query_resn"] = self.query_fragments["resn"] result_summary["match_distance"] = self.lookup_results["match_distance"] result_summary["match_quantile"] = self.lookup_result_quantiles result_summary["match_id"] = self.lookup_results["match"]["id"] result_summary["match_resn"] = self.lookup_results["match"]["resn"] result_summary["threshold_distance"] = self.lookup_results["match"]["threshold_distance"] return result_summary def residue_maximum_rmsd(self, source_residues, source_fragment_spec): from interface_fragment_matching.structure_database.store import ResidueCache residue_max_distance = numpy.empty_like(source_residues, dtype=float) residue_max_distance[:] = 0 source_cache = ResidueCache(source_residues) for i in range(len(self.query_fragments)): f = self.query_fragments[i] distance = self.lookup_results[i]["match_distance"] fstart = source_cache.residue_index(f) fseg = residue_max_distance[fstart: fstart + source_fragment_spec.fragment_length] fseg[fseg < distance] = distance return residue_max_distance def plot_profile(self, ax = None): from matplotlib import pylab if ax is None: ax = pylab.gca() result_summary = self.result_summary match_residual = result_summary["match_distance"] - result_summary["threshold_distance"] indicies = numpy.arange(len(match_residual)) nonmatching_points = list(numpy.flatnonzero(numpy.isinf(match_residual))) l = True for s, e in zip([0] + nonmatching_points, nonmatching_points + [len(match_residual)] ): ax.plot(indicies[s:e], match_residual[s:e], color="blue", label=("Match residual." if l else None)) l = False l = True for n in nonmatching_points: ax.axvspan(n - .5, n + .5, color="red", alpha=.5, label=("Match failure." if l else None)) l = False ax.legend() def display_profile(self, source_residues, source_fragment_spec, good_res_threshold = .2, bad_res_threshold = .35): from interface_fragment_matching.interactive.embed import residues_display import matplotlib.colors cmap = matplotlib.colors.LinearSegmentedColormap.from_list("gr", ["green", "gold", "red"]) sm = matplotlib.cm.ScalarMappable(matplotlib.colors.Normalize(vmin=good_res_threshold, vmax=bad_res_threshold), cmap=cmap) residue_maximum_distance = self.residue_maximum_rmsd(source_residues, source_fragment_spec) res_color = [matplotlib.colors.rgb2hex(c) for c in sm.to_rgba(residue_maximum_distance)] color_selector = ["%s:residue %i" % e for e in zip(res_color, xrange(1, len(res_color) + 1))] return residues_display(source_residues, color=color_selector) <file_sep>import logging import copy from collections import namedtuple import numpy from .profile_calculation import extract_logscore_profile_scores, select_by_additive_profile_score from interface_fragment_matching.fragment_fitting.rmsd_calc import atom_array_broadcast_rmsd from interface_fragment_matching.fragment_fitting.store import FragmentSpecification FragmentProfilerParameters = namedtuple("FragmentProfilerParameters", ["fragment_specification", "logscore_substitution_profile", "select_fragments_per_query_position"]) class ProfileFragmentQuality(object): logger = logging.getLogger("fragment_profling.profile_fragment_quality.ProfileFragmentQuality") aa_codes ='ARNDCEQGHILKMFPSTWYV' aa_encoding = dict((aa, i) for i, aa in enumerate(aa_codes)) def __init__(self, source_residues, logscore_substitution_profile, select_fragments_per_query_position, profiler_benchmark_summaries = {}): self.source_residues = source_residues self.encoded_source_residue_sequences = self.sequence_array_to_encoding(source_residues["sc"]["aa"]) if isinstance(logscore_substitution_profile, basestring): import Bio.SubsMat.MatrixInfo assert logscore_substitution_profile in Bio.SubsMat.MatrixInfo.available_matrices self.logscore_substitution_profile_name = logscore_substitution_profile self.logscore_substitution_profile_data = Bio.SubsMat.MatrixInfo.__dict__[logscore_substitution_profile] else: self.logscore_substitution_profile_name = None self.logscore_substitution_profile_data = logscore_substitution_profile self.logscore_substitution_profile_data = self.encode_score_table(self.logscore_substitution_profile_data) self.select_fragments_per_query_position = select_fragments_per_query_position # Cache fragment start indicies over multiple profiling runs. self._cached_fragment_start_length = None self._cached_fragment_start_indicies = None self.profiler_benchmark_summaries = dict(profiler_benchmark_summaries) def get_fragment_start_residues(self, fragment_length): """Get all starting indicies in self.source_residues for the given fragment length.""" if fragment_length != self._cached_fragment_start_length: fspec = FragmentSpecification(fragment_length) self._cached_fragment_start_length = fragment_length self._cached_fragment_start_indicies = fspec.fragment_start_residues_from_residue_array(self.source_residues) return self._cached_fragment_start_indicies def perform_fragment_analysis(self, fragments): """Perform profile-based fragment quality analysis for given fragments. fragments - array((n,), dtype=[("sc", ("aa", "S1")), ("coordinates", ...)] returns - ProfileFragmentQualityResult """ self.logger.info("perform_fragment_analysis(<%s fragments>)", len(fragments)) fragments = numpy.array(fragments) (num_query_fragments,) = fragments.shape fspec = FragmentSpecification.from_fragment_dtype(fragments.dtype) source_fragment_start_indicies = self.get_fragment_start_residues(fspec.fragment_length) # Select dummy fragment with fspec to get dtype per_position_selected_fragments = numpy.empty( (len(fragments), self.select_fragments_per_query_position), dtype = fspec.fragments_from_start_residues( self.source_residues, numpy.array([0]), additional_per_residue_fields=["bb", "sc", "ss"]).dtype) per_position_selection_scores = numpy.empty_like(per_position_selected_fragments, dtype=float) per_position_selection_rmsds = numpy.empty_like(per_position_selection_scores) for n in xrange(len(fragments)): self.logger.debug("profiling fragment: %s", n) frag = fragments[n] self.logger.debug("profiling sequence: %s", frag["sc"]["aa"]) frag_sequence = self.sequence_array_to_encoding(frag["sc"]["aa"]) frag_profile = self.position_profile_from_sequence(frag_sequence, self.logscore_substitution_profile_data) self.logger.debug("profile table: %s", frag_profile) score_selections = select_by_additive_profile_score( frag_profile, self.encoded_source_residue_sequences, source_fragment_start_indicies, self.select_fragments_per_query_position) assert len(score_selections) == self.select_fragments_per_query_position per_position_selection_scores[n] = score_selections["score"] per_position_selected_fragments[n] = fspec.fragments_from_start_residues( self.source_residues, score_selections["index"], additional_per_residue_fields=["bb", "sc", "ss"]) per_position_selection_rmsds[n] = atom_array_broadcast_rmsd( fragments[n]["coordinates"], per_position_selected_fragments[n]["coordinates"]) search_parameters = FragmentProfilerParameters(fspec, self.logscore_substitution_profile_name, self.select_fragments_per_query_position) if search_parameters in self.profiler_benchmark_summaries: query_benchmark_data = self.profiler_benchmark_summaries[search_parameters] quantile_indicies = numpy.searchsorted(query_benchmark_data["global_quantile_value"], per_position_selection_rmsds) quantile_indicies[quantile_indicies >= len(query_benchmark_data["global_quantile_value"])] = len(query_benchmark_data["global_quantile_value"]) - 1 selected_fragment_quantiles = query_benchmark_data["quantile"][quantile_indicies] else: if self.profiler_benchmark_summaries: # Log warning if profiler has benchmark data but user's query isn't benchmarked. self.logger.warning("Query parameters not benchmarked, result quantiles will not be calculated. %s", search_parameters) selected_fragment_quantiles = None return ProfileFragmentQualityResult(fragments, per_position_selected_fragments, per_position_selection_rmsds, selected_fragment_quantiles) def profile_fragment_scoring(self, fragments): fragments = numpy.array(fragments) (num_query_fragments,) = fragments.shape fspec = FragmentSpecification.from_fragment_dtype(fragments.dtype) source_fragment_start_indicies = self.get_fragment_start_residues(fspec.fragment_length) # Pre-allocate result score tables. source_fragment_total_scores = numpy.empty((len(fragments), len(source_fragment_start_indicies)), dtype=self.logscore_substitution_profile_data.dtype) for n in xrange(len(fragments)): frag = fragments[n] frag_sequence = self.sequence_array_to_encoding(frag["sc"]["aa"]) frag_profile = self.position_profile_from_sequence(frag_sequence, self.logscore_substitution_profile_data) extract_logscore_profile_scores( frag_profile, self.encoded_source_residue_sequences, source_fragment_start_indicies, source_fragment_total_scores[n]) return source_fragment_total_scores def position_profile_from_sequence(self, input_sequence, score_table): """Create position specific profile table from input sequence and score table. input_sequence - array-like((sequence_length), int) integer encoded input sequence. score_table - array((n, n)) score table. returns - array((sequence_length, n)) position specific score. """ assert score_table.ndim == 2 and score_table.shape[0] == score_table.shape[1] profile = numpy.zeros((len(input_sequence), score_table.shape[1]), dtype=score_table.dtype) for i in xrange(len(input_sequence)): profile[i] = score_table[input_sequence[i]] return profile def encode_score_table(self, score_table): """Convert pairwise score table to integer sequence encoding. score_table - {(from, to) : score, [...]} dictionary of score table entries. score_table is assumed to be pre-encoded if array input provided. returns - array((encoding_size, encoding_size), float) score table. """ if isinstance(score_table, numpy.ndarray): return score_table.copy() result = numpy.zeros((len(self.aa_encoding), len(self.aa_encoding)), dtype=float) for (f, t), v in score_table.items(): if f in self.aa_encoding and t in self.aa_encoding: result[self.aa_encoding[f], self.aa_encoding[t]] = v result[self.aa_encoding[t], self.aa_encoding[f]] = v return result def sequence_array_to_encoding(self, sequence_array): """Convert sequence array to integer encoding.""" result = numpy.empty_like(sequence_array, dtype="u2") result[:] = max(self.aa_encoding.values()) + 1 for aa, i in self.aa_encoding.items(): result[sequence_array == aa] = i assert numpy.alltrue(result != max(self.aa_encoding.values()) + 1) return result def encoding_to_sequence_array(self, encoding_array): """Convert encoded aa array to sequence array.""" result = numpy.empty_like(encoding_array, dtype="S1") result[:] = "." for aa, i in self.aa_encoding.items(): result[encoding_array == i] = aa assert numpy.alltrue(result != ".") return result class ProfileFragmentQualityResult(namedtuple("ProfileFragmentQualityResult", ["query_fragments", "selected_fragments", "selected_fragment_rmsds", "selected_fragment_quantiles"])): """Result container for fragment profiling runs.""" #def __new__(_cls, query_fragments, selected_fragments, selected_fragment_rmsds, selected_fragment_quantiles = None): #"""Create new result tuple, defaulting to no selected_fragment_quantiles.""" #return super(FragmentSpecification, _cls).__new__(_cls, query_fragments, selected_fragments, selected_fragment_rmsds, selected_fragment_quantiles) @property def result_fragment_count(self): return self.selected_fragments.shape[1] @property def query_fragment_count(self): return self.selected_fragments.shape[0] def generate_result_summary(self, fragment_count = 0): """Generate descriptive summary of result, optionally including top fragment_count fragments. returns - Summary array fields: "id" - query id "resn" - query resn "count" - total fragment count "mean" - mean fragment rmsd "std" - fragment rmsd stddev "quartile" - 0, .25, .5, .75, 1.0 quantiles of result rmsds ["selected_fragments" - top fragments] ["fragment_quantile" - fragment profile quantile] """ result_dtype = [ ("id", "u4"), ("resn", "u4"), ("count", "u4"), ("mean", float), ("std", float), ("quartile", float, (5,))] if fragment_count and fragment_count > 0: result_dtype += [("selected_fragments", self.selected_fragments.dtype, (fragment_count,))] if self.selected_fragment_quantiles is not None: result_dtype += [("fragment_quantile", float)] result = numpy.empty_like( self.query_fragments, result_dtype) result["id"] = self.query_fragments["id"] result["resn"] = self.query_fragments["resn"] result["count"] = self.selected_fragments.shape[-1] numpy.mean(self.selected_fragment_rmsds, axis=-1, out = result["mean"]) numpy.std(self.selected_fragment_rmsds, axis=-1, out = result["std"]) qr = numpy.percentile(self.selected_fragment_rmsds, [0., 25., 50., 75., 100.], axis=-1) for q in xrange(len(qr)): result["quartile"][:,q] = qr[q] if fragment_count and fragment_count > 0: fragment_selections = numpy.argsort(self.selected_fragment_rmsds)[...,:fragment_count] idx = (numpy.expand_dims(numpy.arange(fragment_selections.shape[0]), -1), fragment_selections) result["selected_fragments"] = self.selected_fragments[idx] if self.selected_fragment_quantiles is not None: result["fragment_quantile"] = numpy.min(self.selected_fragment_quantiles, axis=-1) return result def restrict_to_top_fragments(self, fragment_count): """Return result subset corrosponding to top fragment_count fragments, as ranked by rmsd.""" if fragment_count >= self.selected_fragments.shape[1]: return copy.deepcopy(self) fragment_selections = numpy.argsort(self.selected_fragment_rmsds)[...,:fragment_count] # Create broadcasted selection indicies for fragment selections idx = (numpy.expand_dims(numpy.arange(fragment_selections.shape[0]), -1), fragment_selections) return ProfileFragmentQualityResult(self.query_fragments.copy(), self.selected_fragments[idx], self.selected_fragment_rmsds[idx], self.selected_fragment_quantiles[idx] if not self.selected_fragment_quantiles is None else None) def prune_fragments_by_start_residue(self): """Remove result fragments with identical id/resn as query fragment. Reduces size of result set by amount needed to remove matching fragments. """ from interface_fragment_matching.structure_database.store import ResidueCache matching_start_residue_mask = \ numpy.expand_dims(ResidueCache.residue_unique_id(self.query_fragments), -1) == \ ResidueCache.residue_unique_id(self.selected_fragments) max_num_duplicates = max(numpy.sum(matching_start_residue_mask, axis=-1)) # Set fragments with matching start residue to infinite RMSD and select subset of fragments # by rmsd. work_copy = copy.deepcopy(self) work_copy.selected_fragment_rmsds[matching_start_residue_mask] = numpy.inf return work_copy.restrict_to_top_fragments(self.result_fragment_count - max_num_duplicates) def plot_per_position_fragment_analysis(self, position, target_axis = None): from matplotlib import pylab position = int(position) if position < 0 or position >= self.selected_fragment_rmsds.shape[0]: raise ValueError("Invalid fragment position specified.") if target_axis is None: target_axis = pylab.gca() fragment_rmsds = numpy.sort(self.selected_fragment_rmsds[position], axis=-1) target_axis.set_title("Fragment %s rmsd distribution." % position) target_axis.hist(fragment_rmsds, bins=50, normed=True) target_axis.grid(False, axis="y") target_axis.set_xlabel("RMSD") target_axis = target_axis.twinx() target_axis.set_yscale("symlog") target_axis.plot(fragment_rmsds, pylab.arange(len(fragment_rmsds)), label="Fragment count at RMSD.", color="red") target_axis.legend() return target_axis def plot_all_fragment_analysis(self, target_axis = None): from matplotlib import pylab if target_axis is None: fig = pylab.figure() target_axis = fig.gca() target_axis.set_title("Per-position fragment profile.") target_axis.set_xlabel("Position") target_axis.set_ylabel("Fragment RMSD distribution.") target_axis.boxplot(self.selected_fragment_rmsds.T) if self.selected_fragment_quantiles is not None: rs = self.generate_result_summary() ax2 = target_axis.twinx() ax2.plot( numpy.arange(len(rs)) + 1, rs["fragment_quantile"], color="red", alpha=.7, linewidth=4, label="Fragment benchmark quantile.") ax2.set_ylim(0, 1) ax2.grid("off", axis="y") ax2.set_ylabel("Benchmark quantile.") ax2.legend(loc="best")
7e9752593c5fbdd2ca3ca38e70d0bc6ee9d1d38d
[ "Markdown", "Python", "C++" ]
11
Python
asford/fragment_profiling
7e600a0f056f1c88226773d37259a7714afe5852
8af2416514f6f89a97ffcc4f5ac7f898295bb02d
refs/heads/main
<file_sep>import firebase from "firebase/app"; import "firebase/auth"; import "firebase/firestore"; import "firebase/storage"; import "firebase/database"; var firebaseConfig = { apiKey: "<KEY>", authDomain: "crud-firebase-ae.firebaseapp.com", projectId: "crud-firebase-ae", storageBucket: "crud-firebase-ae.appspot.com", messagingSenderId: "615771571293", appId: "1:615771571293:web:9e1677a0619b3ebabdf9b4", }; // Initialize Firebase var app = firebase.initializeApp(firebaseConfig); const firestore = app.firestore(); export const firebaseStore = { contacts: firestore.collection("contacts"), formatDoc: (doc) => { return { id: doc.id, ...doc.data() }; }, }; export default app.database().ref();
a4058c974c14ff57fbe0d14840fb5517dd64525b
[ "JavaScript" ]
1
JavaScript
AbdelrahmanEssamA/firebase-crud
98d2e2f31eb056f62f39f0480148b987460c88ad
3a17a0dc112c50fe1db971a17cdbcca8b18eeedc
refs/heads/master
<file_sep><?php declare(strict_types=1); namespace IS\SyliusEcommpayPlugin\Form\Type; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Form\FormEvent; use Symfony\Component\Form\FormEvents; final class EcommpayGatewayConfigurationType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('projectId', TextType::class) ->add('secretKey', TextType::class) ; } } <file_sep><?php declare(strict_types=1); namespace IS\SyliusEcommpayPlugin; use Payum\Core\Extension\Context; use Payum\Core\Extension\ExtensionInterface; use Payum\Core\Request\Convert; use Sylius\Bundle\PayumBundle\Request\GetStatus; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; use Symfony\Component\Routing\RouterInterface; final class LocaleExtension implements ExtensionInterface { /** * @var RouterInterface */ protected $router; /** * @var string */ protected $thankYouRoute; /** * @var string */ protected $locale; /** * @param RouterInterface $router * @param string $thankYouRoute */ public function __construct(RouterInterface $router, string $thankYouRoute) { $this->router = $router; $this->thankYouRoute = $thankYouRoute; } public function onPreExecute(Context $context) { } public function onExecute(Context $context) { $previousStack = $context->getPrevious(); $previousStackSize = count($previousStack); if ($previousStackSize !== 2) { return; } $request = $context->getRequest(); if (!$request instanceof GetStatus) { return; } $this->locale = $request->getFirstModel()->getOrder()->getLocaleCode(); } public function onPostExecute(Context $context) { $previousStack = $context->getPrevious(); $previousStackSize = count($previousStack); if ($previousStackSize !== 2) { return; } $request = $context->getRequest(); if (!$context->getRequest() instanceof Convert) { return; } $result = $request->getResult(); $result['merchant_success_url'] = $this->router->generate( $this->thankYouRoute, ['_locale' => $this->locale], UrlGeneratorInterface::ABSOLUTE_URL ); $result['language_code'] = $this->locale; $request->setResult($result); } } <file_sep><?php declare(strict_types=1); namespace IS\SyliusEcommpayPlugin; use Sylius\Bundle\CoreBundle\Application\SyliusPluginTrait; use Symfony\Component\HttpKernel\Bundle\Bundle; final class ISSyliusEcommpayPlugin extends Bundle { use SyliusPluginTrait; } <file_sep># ISSyliusEcommpayPlugin ## Installation ```bash $ composer require infinite-software/sylius-ecommpay-plugin ``` Add plugin dependencies to your app/AppKernel.php file: ```php public function registerBundles() { return array_merge(parent::registerBundles(), [ ... new IS\SyliusEcommpayPlugin\ISSyliusEcommpayPlugin(), ]); } ``` Add new Payment Method in your project Admin section with Ecommpay gateway, where you should add provided `secretkey` and `project_id`. Ask Ecommpay Support to set Callback URL to `http://example.com/payment/notify/unsafe/ecommpay` (or reassign route from this action to another place if needed) ## Adding Payment Page extra parameters If you need prepend parameters before sending request to Ecommpay (for example from https://developers.ecommpay.com/ru/ru_PP_Parameters.html), copy contents of `Payum\Ecommpay\Action\ConvertPaymentAction` class into a new file located in `src/Payment/Ecommpay/ConvertPaymentAction`: ```php namespace App\Payment\Ecommpay; //use ...; final class ConvertPaymentAction implements ActionInterface, ApiAwareInterface { ... /** * {@inheritDoc} * * @param Convert $request */ public function execute($request) { RequestNotSupportedException::assertSupports($this, $request); /** @var PaymentInterface $payment */ $payment = $request->getSource(); /** @var OrderInterface $order */ $params = [ 'payment_id' => $payment->getNumber(), 'payment_amount' => $payment->getTotalAmount(), 'payment_currency' => $payment->getCurrencyCode(), 'project_id' => $this->api['projectId'], 'customer_id' => $payment->getClientId(), // my extra parameter 'force_payment_method' => 'card' ]; $request->setResult($params); } ... } ``` And lastly declare it as service in `services.yaml`. Do not forget to make service `public` like this: ```yaml App\Payment\Ecommpay\ConvertPaymentAction: public: true tags: - { name: payum.action, factory: ecommpay, alias: payum.action.convert_payment } ```
be72900b48a948fe9d9700e9a39585435fdc0b7e
[ "Markdown", "PHP" ]
4
PHP
InfiniteSoftware/ISSyliusEcommpayPlugin
2cc8300178978a3c9a025bb5c79d8d8878aaf5e0
839aa8395fd190f66ce9cffab0f4cd70e168bd3c
refs/heads/master
<file_sep>#include <iostream> using namespace std; int main(){ float A, B; char menu; cout<<endl; cout<< "--------Program Kalkulator Sederhana--------"<<endl; cout<< "============================================"<<endl; cout<< " Masukan Nilai A : "; cin>> A; cout<< " Masukan Nilai B : "; cin>> B; while (B==0) { cout<< "\nNilai B Tidak Boleh NOL "; cout<< "\nMasukan Nilai B : "; cin>> B; } do{ cout<<endl; cout<< " Pilih Jenis Operasinya :"; cout<< " \n1. Perkalian"; cout<< " \n2. Penjumlahan"; cout<< " \n3. Pengurangan"; cout<< " \n4. Pembagian"; cout<< " \n0. Keluar Applikasi"; cout<< " \nMasukan Pilihan : ";cin>> menu; cout<<endl; switch (menu){ case '1' : cout<< "Hasil Perkalian dari "<< A <<" * "<<B<<" : "<< A*B<< endl; cout<<endl; break; case '2': cout<< "Hasil Penjumlahan dari "<< A <<" + "<<B<<" : "<< A+B<< endl; cout<<endl; break; case '3': cout<< "Hasil Pengurangan dari "<< A <<" - "<<B<<" : "<< A-B<< endl; cout<<endl; break; case '4': cout<< "Hasil Pembagian dari "<< A <<" / "<<B<<" : "<< A/B<< endl; cout<<endl; break; case '0' : return 0; default : cout<< "NO pilihan "<<menu<< " Tidak Ada"<<endl; break; } } while (menu = 1-4); } <file_sep># Praktikum06 Program Kalkulator Sederhana Menggunakan Switch ``` Alur Algortima : 1. Deklarasi variable input A dan B dengan type data float 2. Deklarasi vaariable menu dengan type data char 3. Untuk mencegah nilai B=NOL dengan kode : while (B==0) { cout<< "\nNilai B Tidak Boleh NOL "; cout<< "\nMasukan Nilai B : "; cin>> B; } Penjelasan : Agar ketika memilih menu pembagian teteap ada angka yang di tampilkan 4. Menggunakan Perulangan DO-WHILE untuk perulangan menu, dengan kode : do{ cout<<endl; cout<< " Pilih Jenis Operasinya :"; cout<< " \n1. Perkalian"; cout<< " \n2. Penjumlahan"; cout<< " \n3. Pengurangan"; cout<< " \n4. Pembagian"; cout<< " \n0. Keluar Applikasi"; cout<< " \nMasukan Pilihan : ";cin>> menu; cout<<endl; while (menu = 1-4); } 5. Menggunakan pilihan Menu Switch, dengan kode : switch (menu){ case '1' : cout<< "Hasil Perkalian dari "<< A <<" * "<<B<<" : "<< A*B<< endl; cout<<endl; break; case '2': cout<< "Hasil Penjumlahan dari "<< A <<" + "<<B<<" : "<< A+B<< endl; cout<<endl; break; case '3': cout<< "Hasil Pengurangan dari "<< A <<" - "<<B<<" : "<< A-B<< endl; cout<<endl; break; case '4': cout<< "Hasil Pembagian dari "<< A <<" / "<<B<<" : "<< A/B<< endl; cout<<endl; break; case '0' : return 0; default : cout<< "NO pilihan "<<menu<< " Tidak Ada"<<endl; break; } ``` Berikut Pseudo-Code : ``` 1. A = ...A <-- 2. B = ...B <-- 3. if(B==0) then goto no 2, else goto no 4 4. Pilih menu =...menu : <-- 1,2,3,4 5. if(menu>4) print "No pilihan Menu Tidak Ada", else goto no 4 6. if(menu=0) goto no 7 7. END ``` Berikut kode Lengkapnya : ``` #include <iostream> using namespace std; int main(){ float A, B; char menu; cout<<endl; cout<< "--------Program Kalkulator Sederhana--------"<<endl; cout<< "============================================"<<endl; cout<< " Masukan Nilai A : "; cin>> A; cout<< " Masukan Nilai B : "; cin>> B; while (B==0) { cout<< "\nNilai B Tidak Boleh NOL "; cout<< "\nMasukan Nilai B : "; cin>> B; } do{ cout<<endl; cout<< " Pilih Jenis Operasinya :"; cout<< " \n1. Perkalian"; cout<< " \n2. Penjumlahan"; cout<< " \n3. Pengurangan"; cout<< " \n4. Pembagian"; cout<< " \n0. Keluar Applikasi"; cout<< " \nMasukan Pilihan : ";cin>> menu; cout<<endl; switch (menu){ case '1' : cout<< "Hasil Perkalian dari "<< A <<" * "<<B<<" : "<< A*B<< endl; cout<<endl; break; case '2': cout<< "Hasil Penjumlahan dari "<< A <<" + "<<B<<" : "<< A+B<< endl; cout<<endl; break; case '3': cout<< "Hasil Pengurangan dari "<< A <<" - "<<B<<" : "<< A-B<< endl; cout<<endl; break; case '4': cout<< "Hasil Pembagian dari "<< A <<" / "<<B<<" : "<< A/B<< endl; cout<<endl; break; case '0' : return 0; default : cout<< "NO pilihan "<<menu<< " Tidak Ada"<<endl; break; } } while (menu = 1-4); } ``` Berikut Hasilnya : ![img](https://raw.githubusercontent.com/danangadita91/Praktikum06/master/Kalkulator/B%3D%3D0.png) ![img](https://raw.githubusercontent.com/danangadita91/Praktikum06/master/Kalkulator/Jenis%20Operasi%20(1).png) ![img](https://raw.githubusercontent.com/danangadita91/Praktikum06/master/Kalkulator/Jenis%20Operasi%20(2).png)
e281987767d543072ff2f35e4d9d8388ae11539f
[ "Markdown", "C++" ]
2
C++
danangadita91/Praktikum06
18df4cc05d82df36f3b2b2797b8d0c986a32c722
bccb89197d5dfc497392d9447167b54379fa9cef
refs/heads/master
<repo_name>atakannguvenn/Python-Student-Database<file_sep>/README.md # Python-Midterm This was our midterm question in programming design class. <file_sep>/student.py class basic : def __init__(self, name, ID, DOB): self.name = name self.id = ID self.DOB = DOB def print_id(self): print(self.id) class student(basic): def __init__(self, name, ID, DOB, SID, grade1, grade2, grade3): super().__init__(name, ID, DOB) self.SID = SID self.grade1 = grade1 self.grade2 = grade2 self.grade3 = grade3 def average(self): avg = (int(self.grade1) + int(self.grade2) + int(self.grade3))/3 print(avg) y = 0 names = [] ID = [] DOB = [] SID = [] grade1 = [] grade2 = [] grade3 = [] sorted_order = [] sorted_version = [] fp = open("student.txt", "r+") student_raw = fp.read() print (student_raw) student_info = student_raw.split() for x in range(len(student_info)): n = x % 7 if n == 0: names.append(student_info[x]) if n == 1: ID.append(student_info[x]) if n == 2: DOB.append(student_info[x]) if n == 3: SID.append(student_info[x]) if n == 4: grade1.append(student_info[x]) if n == 5: grade2.append(student_info[x]) if n == 6: grade3.append(student_info[x]) student1 = student(names[0], ID[0], DOB[0], SID[0], grade1[0], grade2[0], grade3[0]) student2 = student(names[1], ID[1], DOB[1], SID[1], grade1[1], grade2[1], grade3[1]) student3 = student(names[2], ID[2], DOB[2], SID[2], grade1[2], grade2[2], grade3[2]) student4 = student(names[3], ID[3], DOB[3], SID[3], grade1[3], grade2[3], grade3[3]) student5 = student(names[4], ID[4], DOB[4], SID[4], grade1[4], grade2[4], grade3[4]) print("id of student1 is") student1.print_id() print("student1 info is\n", student1.__dict__) print("student2 info is\n", student2.__dict__) print("gpa for student1 is") student1.average() for x in grade2: y = int(x) + y avg = y/5 print("avg of grade2 is" ,avg) #finding the sorted version index order sorted_order = sorted(range(len(grade2)), key=lambda k: grade2[k]) for x in range(5): sorted_version.append(names[sorted_order[x]]) sorted_version.append(" ") sorted_version.append(ID[sorted_order[x]]) sorted_version.append(" ") sorted_version.append(DOB[sorted_order[x]]) sorted_version.append(" ") sorted_version.append(SID[sorted_order[x]]) sorted_version.append(" ") sorted_version.append(grade1[sorted_order[x]]) sorted_version.append(" ") sorted_version.append(grade2[sorted_order[x]]) sorted_version.append(" ") sorted_version.append(grade3[sorted_order[x]]) sorted_version.append("\n") sorted_version_str = ' '.join(sorted_version) print(sorted_version_str) fp.write(sorted_version_str) fp.close()
7edc65939e28ef220b36b0806018eb93ee97a4d1
[ "Markdown", "Python" ]
2
Markdown
atakannguvenn/Python-Student-Database
4c1f2ecead942dd11e047dd469bacf44bf7b1a00
58f80bf17c63047c1f1e7080a80718fcb68dc960
refs/heads/master
<file_sep>import pypyodbc import random as rand ### TODO: Break generating bits into discrete static functions class Character(): def __init__(self): connection = pypyodbc.connect("Driver={SQL Server};Server=localhost;Database=MazeRats;Trusted_Connection=Yes;") self.cursor = connection.cursor() self.gender = rand.randint(0,1) self.firstname = "" self.surname = "" if self.gender == 0: self.cursor.execute("SELECT Name from FemaleNames WHERE NameID =" + str(rand.randint(1,36))) else: self.cursor.execute("SELECT Name from MaleNames WHERE NameID =" + str(rand.randint(1,36))) self.firstname = self.cursor.fetchone()[0] coin = rand.randint(0,1) if coin == 0: self.cursor.execute("SELECT Name FROM UpperSurnames WHERE NameID =" + str(rand.randint(1,36))) else: self.cursor.execute("SELECT Name FROM LowerSurnames WHERE NameID =" + str(rand.randint(1,36))) self.surname = self.cursor.fetchone()[0] self.abilities = { 1 : ("+2", "+1", "+0"), 2 : ("+2", "+0", "+1"), 3 : ("+1", "+2", "+0"), 4 : ("+0", "+2", "+1"), 5 : ("+1", "+0", "+2"), 6 : ("+0", "+1", "+2") }[rand.randint(1,6)] self.startfeature = { 1 : "+1 attack bonus", 2 : "One spell slot", 3 : "Path - " }[rand.randint(1,3)] if self.startfeature == "Path - ": self.startfeature = { 1 : "Briarborn - Tracking, foraging, survival.", 2 : "Fingersmith - Tinkering, picking locks or pockets", 3 : "Roofrunner - Climbing, leaping, balancing.", 4 : "Shadowjack - Moving silently, hiding in shadows." }[rand.randint(1,4)] if self.startfeature == "One spell slot": self.spell = self.randomSpell() self.startfeature += " - " + self.spell self.items = [] for i in range(0, 6): while True: choice = rand.randint(1,36) query = "SELECT GearName FROM StartingGear WHERE GearID =" + str(choice) self.cursor.execute(query) result = self.cursor.fetchone()[0] if result not in self.items: self.items.append(result) break self.weapons = [] for i in range(0, 2): while True: choice = rand.randint(1, 18) query = "SELECT WeaponName, WeaponType FROM Weapons WHERE WeaponID =" + str(choice) self.cursor.execute(query) res = self.cursor.fetchone() weap = res[0] wtype = res[1] if weap not in self.weapons: self.weapons.append(str(weap + " (" + wtype + ")")) break self.cursor.execute("SELECT AppearanceName FROM Appearance WHERE AppearanceID =" + str(rand.randint(1,36))) self.appearance = self.cursor.fetchone()[0] self.cursor.execute("SELECT DetailName FROM PhysicalDetail WHERE DetailID =" + str(rand.randint(1,36))) self.physdetail = self.cursor.fetchone()[0] self.cursor.execute("SELECT BackgroundName FROM Background WHERE BackgroundID =" + str(rand.randint(1,36))) self.bg = self.cursor.fetchone()[0] self.cursor.execute("SELECT ClothingName FROM Clothing WHERE ClothingID =" + str(rand.randint(1,36))) self.clothing = self.cursor.fetchone()[0] self.cursor.execute("SELECT PersonalityName FROM Personality WHERE PersonalityID =" + str(rand.randint(1,36))) self.person = self.cursor.fetchone()[0] self.cursor.execute("SELECT MannerismName FROM Mannerism WHERE MannerismID =" + str(rand.randint(1,36))) self.manner = self.cursor.fetchone()[0] def returnChar(self): self.thechar = self.firstname + " " + self.surname \ + "\nAbilities: Strength " + self.abilities[0] + ", Dexterity " + self.abilities[1] \ + ", Will " + self.abilities[2] \ + "\nStarting feature: " + self.startfeature \ + "\nItems: " + ", ".join(self.items) \ + "\nWeapons: " + ", ".join(self.weapons) \ + "\nAppearance: " + self.appearance \ + "\nPhysical detail: " + self.physdetail \ + "\nBackground: " + self.bg \ + "\nClothing: " + self.clothing \ + "\nPersonality: " + self.person \ + "\nMannerism: " + self.manner return self.thechar def randomSpell(self): spelltype = rand.randint(1,12) if spelltype == 1: self.cursor.execute("SELECT SName FROM SpellPhysicalEffects WHERE SID =" + str(rand.randint(1,36))) spell = self.cursor.fetchone()[0] self.cursor.execute("SELECT SName FROM SpellPhysicalForms WHERE SID =" + str(rand.randint(1,36))) spell += " " + self.cursor.fetchone()[0] elif spelltype == 2: self.cursor.execute("SELECT SName FROM SpellPhysicalEffects WHERE SID =" + str(rand.randint(1,36))) spell = self.cursor.fetchone()[0] self.cursor.execute("SELECT SName FROM SpellEtherealForms WHERE SID =" + str(rand.randint(1,36))) spell += " " + self.cursor.fetchone()[0] elif spelltype == 3: self.cursor.execute("SELECT SName FROM SpellEtherealEffects WHERE SID =" + str(rand.randint(1,36))) spell = self.cursor.fetchone()[0] self.cursor.execute("SELECT SName FROM SpellPhysicalForms WHERE SID =" + str(rand.randint(1,36))) spell += " " + self.cursor.fetchone()[0] elif spelltype == 4: self.cursor.execute("SELECT SName FROM SpellEtherealEffects WHERE SID =" + str(rand.randint(1,36))) spell = self.cursor.fetchone()[0] self.cursor.execute("SELECT SName FROM SpellEtherealForms WHERE SID =" + str(rand.randint(1,36))) spell += " " + self.cursor.fetchone()[0] elif spelltype == 5: self.cursor.execute("SELECT SName FROM SpellPhysicalElements WHERE SID =" + str(rand.randint(1,36))) spell = self.cursor.fetchone()[0] self.cursor.execute("SELECT SName FROM SpellPhysicalForms WHERE SID =" + str(rand.randint(1,36))) spell += " " + self.cursor.fetchone()[0] elif spelltype == 6: self.cursor.execute("SELECT SName FROM SpellPhysicalElements WHERE SID =" + str(rand.randint(1,36))) spell = self.cursor.fetchone()[0] self.cursor.execute("SELECT SName FROM SpellEtherealForms WHERE SID =" + str(rand.randint(1,36))) spell += " " + self.cursor.fetchone()[0] elif spelltype == 7: self.cursor.execute("SELECT SName FROM SpellEtherealElements WHERE SID =" + str(rand.randint(1,36))) spell = self.cursor.fetchone()[0] self.cursor.execute("SELECT SName FROM SpellPhysicalForms WHERE SID =" + str(rand.randint(1,36))) spell += " " + self.cursor.fetchone()[0] elif spelltype == 8: self.cursor.execute("SELECT SName FROM SpellEtherealElements WHERE SID =" + str(rand.randint(1,36))) spell = self.cursor.fetchone()[0] self.cursor.execute("SELECT SName FROM SpellEtherealForms WHERE SID =" + str(rand.randint(1,36))) spell += " " + self.cursor.fetchone()[0] elif spelltype == 9: self.cursor.execute("SELECT SName FROM SpellPhysicalEffects WHERE SID =" + str(rand.randint(1,36))) spell = self.cursor.fetchone()[0] self.cursor.execute("SELECT SName FROM SpellPhysicalElements WHERE SID =" + str(rand.randint(1,36))) spell += " " + self.cursor.fetchone()[0] elif spelltype == 10: self.cursor.execute("SELECT SName FROM SpellPhysicalEffects WHERE SID =" + str(rand.randint(1,36))) spell = self.cursor.fetchone()[0] self.cursor.execute("SELECT SName FROM SpellEtherealElements WHERE SID =" + str(rand.randint(1,36))) spell += " " + self.cursor.fetchone()[0] elif spelltype == 11: self.cursor.execute("SELECT SName FROM SpellEtherealEffects WHERE SID =" + str(rand.randint(1,36))) spell = self.cursor.fetchone()[0] self.cursor.execute("SELECT SName FROM SpellPhysicalElements WHERE SID =" + str(rand.randint(1,36))) spell += " " + self.cursor.fetchone()[0] elif spelltype == 12: self.cursor.execute("SELECT SName FROM SpellEtherealEffects WHERE SID =" + str(rand.randint(1,36))) spell = self.cursor.fetchone()[0] self.cursor.execute("SELECT SName FROM SpellEtherealElements WHERE SID =" + str(rand.randint(1,36))) spell += " " + self.cursor.fetchone()[0] return spell<file_sep>import discord from discord.ext import commands from os import path from prefix import prefix import sys class fun(): def __init__(self, bot): self.bot = bot # Simply throws out a lot of trumpets. dootdoot thnkx mr skeltal @commands.command(description="Knee deep in the doot.") async def doot(self): await self.bot.say(":trumpet:" * 200) #translate text to full width @commands.command(description='As wide as text will get.') async def ominous(self, text : str): ominous_text = "" for c in text: if c == ' ': ominous_text += " " else: # Get the full-width unicode text equivalent of the character ominous_text += chr(0xFEE0 + ord(c)) ominous_text = prefix.choosePrefix() + ominous_text await self.bot.say(ominous_text) def setup(bot): bot.add_cog(fun(bot))<file_sep> from os import pardir from os import path import random class prefix(): # Pick a polite prefix. def choosePrefix(): prefix_list = open(path.abspath(path.join(path.curdir, 'files', 'polite_prefixes.txt'))) \ .readlines() return (prefix_list[random.randint(0, len(prefix_list) - 1)] + '\n')<file_sep>import discord from discord.ext import commands import secret import logging import sys import os #mr handy's framework is built on Brown bot by @wethegreenpeople sys.path.append(os.path.join(sys.path[0],'modules')) #sys.path.insert(0, r'./modules') #logger = logging.getLogger('discord') #logger.setLevel(logging.INFO) #handler = logging.FileHandler(filename='discord.log', encoding='utf-8', mode='w') #handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s')) #logger.addHandler(handler) description = '''Good to be back, sir.''' bot = commands.Bot(command_prefix=']', description=description) @bot.event async def on_ready(): print('Logged in as') print(bot.user.name) print(bot.user.id) print('------') await bot.change_status(discord.Game(name="]help for commands.")) bot.load_extension("fun") bot.load_extension("dice") bot.load_extension("codephrase") bot.load_extension('comic') bot.load_extension('generators') @bot.event async def on_message(message): if message.channel.is_private and message.content.startswith('http') and message.author != bot.user: try: invite = await bot.get_invite(message.content) if isinstance(invite.server, discord.Object): await bot.accept_invite(invite) await bot.send_message(message.channel, 'Joined the server.') log.info('Joined server {0.server.name} via {1.author.name}'.format(invite, message)) else: log.info('Attempted to rejoin {0.server.name} via {1.author.name}'.format(invite, message)) await bot.send_message(message.channel, 'Already in that server.') except: log.info('Failed to join a server invited by {0.author.name}'.format(message)) await bot.send_message(message.channel, 'Could not join server.') finally: return await bot.process_commands(message) # Loads modules manually for testing and whatnot @bot.command(pass_context=True, hidden="True") async def load(ctx, extension_name:str): if ctx.message.author.id == "<PASSWORD>" or "<PASSWORD>": try: bot.load_extension(extension_name) except (AttributeError, ImportError) as e: await bot.say("```py\n{}: {}\n```".format(type(e).__name__, str(e))) return await bot.say("{} loaded.".format(extension_name)) else: await bot.say("You do not have permission to load/unload cogs") # Unloads for whatever reason @bot.command(pass_context=True, hidden=True) async def unload(ctx, extension_name:str): if ctx.message.author.id == "<PASSWORD>" or "<PASSWORD>": bot.unload_extension(extension_name) await bot.say("{} unloaded.".format(extension_name)) else: await bot.say("You do not have permission to load/unload cogs") # Refreshes modules because unloading and then loading is work for peasents. @bot.command(pass_context=True, hidden=True) async def refresh(ctx, extension_name:str): if ctx.message.author.id: bot.unload_extension(extension_name) bot.load_extension(extension_name) await bot.say("Module refreshed") else: await bot.say("You don't have permission to refresh this module") bot.loop.set_debug(True) bot.run(secret.botToken)<file_sep> import discord from discord.ext import commands from os import path from prefix import prefix import random import sys class codephrase(): def __init__(self, bot): self.bot = bot @commands.command(description="Generate a code phrase.") async def codephrase(self): coin = random.randint(0,1) result = "" # get the first list of code words, using system-agnostic path # delimiters list1 = open(path.join(path.curdir, 'files', 'code1.txt')) \ .read().split() # pick a random word firstword = list1[random.randint(0,48)] #lather, rinse, repeat list2 = open(path.join(path.curdir, 'files', 'code2.txt')) \ .read().split() secondword = list2[random.randint(0,52)] thirdword = list2[random.randint(0,52)] if coin == 0: result = firstword + ' ' + secondword else: result = firstword + ' ' + secondword + ' ' + thirdword result = prefix.choosePrefix() + "Your code phrase is " + result + "." await self.bot.say(result) def setup(bot): bot.add_cog(codephrase(bot)) <file_sep>import bot_ability import mrhandy import inspect import lxml.html import os import random import re #import soundcloud import urllib.request from urllib.parse import quote ##### TO DO ### - full width mode ### - kick it with a dope verse / drop fire bars ### - certified hot flames / hot fire ### - jargon file random entry getter ### - # instantiate a soundcloud client #client = soundcloud.Client(client_id = os.environ.get("SOUNDCLOUD_CLIENT_ID")) #get the slack client from the main bot module #slack_client = mrhandy.get_slack_client() class ComicPost(): #change this once we have more comics, if ever command_name = 'achewood' command_keywords = ['achewood'] command_helptext = '`Achewood:` Post a random Achewood strip, or '\ 'search for strip containing "dialog in quotes."' command_manpage = "To be implemented later." def initialize_action(self, command): if '"' not in command: response = self.get_achewood() elif '"' in command: response = self.get_achewood(command[command.find('"'):command.rfind('"')]) return bot_ability.choose_polite_prefix() + ' ' + response def get_achewood(self, *arg): # If no search argument is supplied, grab a random strip using urllib and lxml if len(arg) == 0: page = urllib.request.urlopen('http://www.ohnorobot.com/random.pl?comic=636') doc = lxml.html.parse(page) imgurl = doc.xpath('//img/@src') return 'http://www.achewood.com' + imgurl[1] else: # if there's a search term, first turn it into a searchable string search = ' '.join(arg) search = search.replace('"', '') search = quote(search) # run the search with ohnorobot searchpage = urllib.request.urlopen('http://www.ohnorobot.com/index.php?s=' \ + search + '&Search=Search&comic=636') doc = lxml.html.parse(searchpage).getroot() # get the links from the results page links = doc.xpath('//a/@href') # if there're no results, say so if 'letsbefriends.php' in links[2]: return "No strip containing that dialog was found, sir. My apologies." else: # otherwise return the best result best_result = links[2] page = urllib.request.urlopen(best_result) doc = lxml.html.parse(page) imgurl = doc.xpath('//img/@src') return 'http://www.achewood.com' + imgurl[1] class DiceRoller(): command_name = 'roll' command_keywords = ['roll'] command_helptext = '`Roll:` Use `Roll XdY` to roll dice, where X is the number ' \ "of dice and Y is the type of dice, e.g. `roll 2d10`. " \ "Or, use `Roll X [color] <Y [color] ...>` to roll Star Wars: " \ "Edge of the Empire dice. This will definitely crash if you " \ "don't use exactly right syntax. E.g. `roll 1 purple 1 yellow`" command_manpage = "To be implemented later." def __init__(self): self.edge_dice = {'blue':['blank','blank','advantages','successes',\ 'successes, advantages','advantages, advantages'], 'black':['blank','blank','threats','threats', \ 'failures','failures'], 'purple':['blank','threats','threats','threats', \ 'failures', 'threats, failures', 'threats, threats',\ 'failures, failures'], 'green':['blank','successes', 'successes', 'advantages', \ 'advantages', 'successes, advantages', 'successes, successes', \ 'advantages, advantages'], 'yellow':['blank','advantages','successes','successes',\ 'advantages, advantages', 'advantages, advantages', \ 'successes, advantages', 'successes, advantages', \ 'successes, advantages', 'successes, successes', \ 'successes, successes', 'triumphs'], 'red':['blank', 'threats', 'threats', 'failures', 'failures', \ 'threats, threats', 'threats, threats', 'threats, failures', \ 'threats, failures', 'failures, failures', 'failures, failures', \ 'despairs']} def initialize_action(self, command): # check if command wants standard dice or star wars dice if (re.search('[0-9]{1,3}d[0-9]{1,3}', command)): return self.roll_standard_dice(command) elif any(word in command for word in self.edge_dice.keys()): return self.roll_edge_dice(command) # roll normal dice, eg roll 2d20 def roll_standard_dice(self, command): # make sure the command matches the necessary pattern if len(re.findall("[0-9]{1,3}", command)) != 0: # a list of the digit groups in the command using a regular expression digits = re.findall("[0-9]{1,3}", command) # break the list down into number of dice... dice_no = digits[0] # and the type (ie sides) of the dice dice_type = digits[1] response = "Rolling " + dice_no + "d" + dice_type + ": " result_list = [] # for number of dice to roll... for i in range(int(dice_no)): # roll the y-sided die roll = random.randint(1, int(dice_type)) # append it to the result list for summing the total result_list.append(roll) # append it to the response string response += str(roll) # as long as it's not the last die being rolled, also append a comma if i != int(dice_no) - 1: response += ", " # return the response and the total return bot_ability.choose_polite_prefix() + '\n' + \ response + " = " + str(sum(result_list)) else: return "Terribly sorry, sir, but that is an incorrect command." def roll_edge_dice(self, command): ### TO DO: ### - Fix this absolutely idiotic code. ### - Cancel out the appropriate rolls (successes/failures, etc) and ### deliver the total. ### - Show which dice are yielding which rolls. # split the input into dice type and number each type is rolled rolls = re.findall('\d \w*', command) # split that into a list roll_list = [s.split(' ') for s in rolls] rolldict = {} # turn the list into a dict with type:number pairs rolldict.update({roll_list[i][1]:roll_list[i][0] for i in range(len(roll_list))}) response = 'Rolling: ' roll_results = [] total_results = [] for key, value in rolldict.items(): # get the die from the edge_dice dict die = self.edge_dice[key] for i in range(int(value)): # generate a random roll roll = random.randint(0, len(die) - 1) roll_results.append(die[roll]) roll_results = (' '.join(roll_results).replace(',','')).split(' ') count += 1 total_results += [str(roll_results.count(word)) + ' ' + word \ for word in roll_results] response = ', '.join((list(set(total_results)))) return bot_ability.choose_polite_prefix() + '\n' + "Rolled: " + response ## Class for the generator bot function class Generator(): command_name = 'generate' command_keywords = ['generate'] command_helptext = "`Generate code phrases:` use the " \ "keywords `generate` and `code` to generate " \ "top-secret code phrases. *TO DO:* expand to generate " \ "names, etc." command_manpage = "To be implemented later." def initialize_action(self, command): codephrase = self.generate_codephrase() return bot_ability.choose_polite_prefix() + ' ' + \ "Your code phrase is " + codephrase + "." # Generate codephrase. def generate_codephrase(self): ####TO DO - multiple codephrases at once, fix magic numbers #flip a coin to see if we're making two- or three-word code phrases coin = random.randint(0,1) # get the first list of code words, using system-agnostic path # delimiters list1 = open(os.path.join(os.path.curdir, 'files', 'code1.txt')) \ .read().split() # pick a random word firstword = list1[random.randint(0,48)] #lather, rinse, repeat list2 = open(os.path.join(os.path.curdir, 'files', 'code2.txt')) \ .read().split() secondword = list2[random.randint(0,52)] thirdword = list2[random.randint(0,52)] if coin == 0: return firstword + ' ' + secondword else: return firstword + ' ' + secondword + ' ' + thirdword # Class for the help display function class HelpDisplay(): command_name = 'help' command_keywords = ['help'] command_helptext = "`Help:` Displays information on available commands." command_manpage = "To be implemented later." def initialize_action(self, command): # use reflection to get list of classes in this module ability_objects = [x[1] for x in inspect.getmembers(bot_ability, inspect.isclass)] response = [] # for each item, add its helptext to the response for item in ability_objects: response.append(item.command_helptext) response = sorted(response) return '\n'.join(response) ''' class NerdAlert(): command_name = 'nerd' command_keywords = ['who', 'the nerd'] command_helptext = "`Who's the nerd:` Ask who the nerd currently is. " \ " *TO DO:* Build the Nerd Accumulator and SCoring Algorithm Response" \ " (N.A.S.C.A.R.)" def initialize_action(self, command): #basic who is the nerd support chance = random.randint(0,100) if chance >= 98: the_nerd = "<NAME> is the nerd now, sir." else: users = list(slack_client.api_call("users.list").get('members')) the_nerd = users[random.randint(0, len(users) - 1)].get('real_name') if the_nerd == 'Mr. Handy': return "It would appear I am the nerd now, sir, although I must say "\ "I'm not pleased with the notion." else: return the_nerd + " is the nerd now, sir." ''' class OminousMode(): command_name = 'ominous' command_keywords = ['make', 'ominous'] command_helptext = '`Make "text" ominous:` Make text very ominous.' command_manpage = 'To be implemented later.' def initialize_action(self, command): normal_text = command[command.find('"') + 1:command.rfind('"')] ominous_text = "" for c in normal_text: if c == ' ': ominous_text += " " else: # Get the full-width unicode text equivalent of the character ominous_text += chr(0xFEE0 + ord(c)) return ominous_text ''' # Class for the soundcloud music retriever class SoundCloud(): ##need to make this better command_name = 'kick it' command_keywords = ['kick it'] command_helptext = "`Kick it:` Kick it with a tasty groove. "\ "*TO DO:* Make... better. " command_manpage = 'To be implemented later.' def initialize_action(self, command): tracks = client.get('/playlists/46223708/tracks') random_track = random.randint(0, (len(tracks) - 1)) playtrack = tracks[random_track].permalink_url return bot_ability.choose_polite_prefix() + ' ' + playtrack ''' # Pick a polite prefix. def choose_polite_prefix(): prefix_list = open(os.path.join( os.path.curdir, 'files', 'polite_prefixes.txt')) \ .readlines() return prefix_list[random.randint(0, len(prefix_list) - 1)]<file_sep>import discord from discord.ext import commands from os import path from prefix import prefix import random import sys class dice(): def __init__(self, bot): self.bot = bot @commands.command(description="roll dice in NdN+X format.") async def roll(self, dice : str): mod = -1 try: if '+' in dice: mod = dice[dice.index('+') + 1:] dice = dice[0:dice.index('+')] rolls, limit = map(int, dice.split('d')) except Exception: await self.bot.say('Format has to be in NdN+x!') return resultsum = 0 result = ', '.join(str(random.randint(1, limit)) for r in range(rolls)) for r in (result.split(', ')): resultsum += int(r) if mod != -1: result += ' = ' + str(resultsum) result += ' + ' + str(mod) resultsum += int(mod) result += ' = ' + str(resultsum) result = prefix.choosePrefix() + result await self.bot.say(result) def setup(bot): bot.add_cog(dice(bot))<file_sep>import discord from discord.ext import commands from mazerats import Character from os import path from prefix import prefix import pypyodbc import random as rand import sys class generators(): def __init__(self, bot): self.bot = bot @commands.command(description="Generate a variety of things. Syntax: ']random <schema> <argument>' \n " \ "e.g. ']random mazerats character'") async def random(self, schema : str, arg : str, count=1): # try: i = 0 if schema == 'mazerats': ch = Character() if arg == 'character': result = prefix.choosePrefix() while (i < count): ch = Character() result += ch.returnChar() + "\n\n" i += 1 if arg == 'spell': result = prefix.choosePrefix() while (i < count): result += ch.randomSpell() + "\n" i += 1 await self.bot.say(result) # except Exception: # await self.bot.say('Format must be "]random <schema> <argument>".') # return def setup(bot): bot.add_cog(generators(bot))<file_sep>import discord from discord.ext import commands import lxml.html from os import path from prefix import prefix import random import sys import urllib.request from urllib.parse import quote class comic(): def __init__(self, bot): self.bot = bot @commands.command(description = "Get an achewood") async def achewood(self, *search): result = "" # If no search argument is supplied, grab a random strip using urllib and lxml if len(search) == 0: page = urllib.request.urlopen('http://www.ohnorobot.com/random.pl?comic=636') doc = lxml.html.parse(page) imgurl = doc.xpath('//img/@src') result = 'http://www.achewood.com' + imgurl[1] else: # if there's a search term, first turn it into a searchable string search = ' '.join(search) search = search.replace('"', '') search = quote(search) # run the search with ohnorobot searchpage = urllib.request.urlopen('http://www.ohnorobot.com/index.php?s=' \ + search + '&Search=Search&comic=636') doc = lxml.html.parse(searchpage).getroot() # get the links from the results page links = doc.xpath('//a/@href') # if there're no results, say so if 'letsbefriends.php' in links[2]: result = "No strip containing that dialog was found, sir. My apologies." else: # otherwise return the best result best_result = links[2] page = urllib.request.urlopen(best_result) doc = lxml.html.parse(page) imgurl = doc.xpath('//img/@src') result = 'http://www.achewood.com' + imgurl[1] result = prefix.choosePrefix() + result await self.bot.say(result) def setup(bot): bot.add_cog(comic(bot))
b2f34e5d5d0f99f3b448dd14e3ed2eea62e079bf
[ "Python" ]
9
Python
cayce-crane/discordbot
b0872bc90f777401eacac48bfd0efe36ab1e744b
7de9fd507acb2d269593e641a48d4011ee3a65b9
refs/heads/master
<file_sep>package com.example.slafuente.imc.modelo; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; /** * Created by slafuente on 22/01/2017. */ public class BaseDatosRegistro extends SQLiteOpenHelper{ //Query para crear la tabla usuario private static final String sqlCreacionTablaUsuarios = "" + "CREATE TABLE usuario(email TEXT PRIMARY KEY, password TEXT)"; /** * Constructor de BaseDatosRegistro * @param context el contexto * @param nombre nombre de la bbdd * @param cursorFactory * @param version version de la bbdd */ public BaseDatosRegistro(Context context, String nombre, SQLiteDatabase.CursorFactory cursorFactory, int version) { super(context,nombre,cursorFactory,version); } /** * Called when the database is created for the first time. This is where the * creation of tables and the initial population of the tables should happen. */ @Override public void onCreate(SQLiteDatabase db) { db.execSQL(sqlCreacionTablaUsuarios); } /** * Called when the database needs to be upgraded. The implementation * should use this method to drop tables, add tables, or do anything else it * needs to upgrade to the new schema version. */ @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { //extraer datos antgua version (selects) //crear nueva version (create) //copiar datos antiguos a los nuevos (inserts) //everything by sql queries } /** * Cerramos la base de datos * @param db base de datos */ private void cerrarBaseDatos(SQLiteDatabase db) { db.close(); } /** * Insertamos un usuario en bbdd * @param usuario */ public void insertarUsuario(Usuario usuario) { SQLiteDatabase db = this.getWritableDatabase(); db.execSQL("INSERT INTO usuario (email, password) VALUES ('"+ usuario.getEmail() + "'" + ", '" + usuario.getPassword() + "')"); cerrarBaseDatos(db); } /** * Buscamos y retornamos el usuario en la bbdd * @param email * @return Usuario encontrado */ public Usuario buscarUsuario(String email, String password) { Usuario usuario = null; SQLiteDatabase db = this.getReadableDatabase(); String consulta = "SELECT email,password FROM usuario WHERE email ='" + email +"' AND " + "password ='"+ password +"'"; Cursor cursor = db.rawQuery(consulta, null); if (cursor != null && cursor.getCount() > 0) { cursor.moveToFirst(); Log.d(getClass().getCanonicalName(), "email es " + cursor.getString(0)); Log.d(getClass().getCanonicalName(), "password es " + cursor.getString(1)); usuario = new Usuario(cursor.getString(0), cursor.getString(1)); } //Cerramos cursor y bbdd cursor.close(); cerrarBaseDatos(db); return usuario; } /** * Comprobamos que exista el usuario en bbdd mirando si existe el email * @param email * @return boolean con usuario esta o no en bbdd */ public boolean existeUsuario(String email) { boolean existe = false; SQLiteDatabase db = this.getReadableDatabase(); String consulta = "SELECT email FROM usuario WHERE email ='" + email +"'"; Cursor cursor = db.rawQuery(consulta, null); if (cursor != null && cursor.getCount() > 0) { existe = true; } //Cerramos cursor y bbdd cursor.close(); cerrarBaseDatos(db); return existe; } } <file_sep>package com.example.slafuente.imc.vista; import android.content.Intent; import android.net.Uri; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import com.example.slafuente.imc.R; import com.example.slafuente.imc.vista.PantallaFoto; public class SeleccionarFotoActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_seleccionar_foto); Intent intentpidefoto = new Intent(); intentpidefoto.setAction(Intent.ACTION_PICK); intentpidefoto.setType("image/*");//TIPO MIME startActivityForResult(intentpidefoto, 30); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { //super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK) { //El usuario ha seleccionado una foto Uri uri = data.getData(); Intent selectFoto = new Intent(getApplicationContext(), PantallaFoto.class); selectFoto.putExtra("imageUri", uri.toString()); startActivity(selectFoto); } else { Log.e("ERROR" , "El usuario le dio a salir "); } } } <file_sep>package com.example.slafuente.imc.vista; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import com.example.slafuente.imc.negocio.AdapterPropio; import com.example.slafuente.imc.R; import java.util.ArrayList; public class ResultActivity extends AppCompatActivity { private TextView textView = null; //Array que asociaremos al adaptador ArrayList<String> alist = new ArrayList<String>(); String[] array = new String[] { "< 16 DESNUTRIDO", " => 16 < 18,5 BAJO PESO", "=> 18,5 < 25 NORMAL", ">=25 < 31 SOBREPESO", ">= 31 OBESIDAD" }; //ListAdapter adaptador = null;*/ AdapterPropio ap = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_result); for (int i = 0; i< array.length; i++) { alist.add(i,array[i]); } //Creación del adaptador, vamos a escoger el layout //adaptador = new ArrayAdapter<String>(this, R.layout.fila, array); textView = (TextView)findViewById(R.id.textviewFila) ; ap = new AdapterPropio(this, alist); Button button = (Button)findViewById(R.id.botonMostrar); TextView resultView = (TextView)findViewById(R.id.textResult2); Intent intent = getIntent(); String result = intent.getStringExtra(MainActivity.EXTRA_RESULT_IMC); resultView.setText(result); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Asociamos el adaptador a la vista. ListView lv = (ListView) findViewById(R.id.listaPesos); lv.setAdapter(ap); } }); } }
950485c4787106bc7f464ee3576efbe6fe0094a8
[ "Java" ]
3
Java
ruizsergi/practicaIMC
cc5e64935c192f8380f594e89c5495e9cd0539cc
8e3fee5568f54f30dc992e530508c5f935e6e16a
refs/heads/master
<repo_name>LinFanChing/book-test<file_sep>/CG/float-point-pitfall.md 浮点数相关的陷阱 ================ 误差修正 -------- ## 简述 因为被计算机表示浮点数的方式所限制,CPU在进行浮点数计算时会出现误差。如执行`0.1 + 0.2 == 0.3`结果往往为`false`,在四则运算中,加减法对精度的影响较小,而乘法对精度的影响更大,除法的对精度的影响最大。所以,在设计算法时,为了提高最终结果的精度,要尽量减少计算的数量,尤其是乘法和除法的数量。 浮点数与浮点数之间不能直接比较,要引入一个`eps`常量。`eps`是epsilon($$\varepsilon$$)的简写,在数学中往往代表任意小的量。在对浮点数进行大小比较时,如果他们的差的绝对值小于这个量,那么我们就认为他们是相等的,从而避免了浮点数精度误差对浮点数比较的影响。eps在大部分题目时取`1e-8`就够了,但要根据题目实际的内容进行调整。 ## 模板代码 ```cpp // sgn返回x经过eps处理的符号,负数返回-1,正数返回1,x的绝对值如果足够小,就返回0。 const double eps = 1e-8; int sgn(double x) { return x < -eps ? -1 : x > eps ? 1 : 0; } ``` | 整型比较 | 等价的浮点数比较 | |----------|-------------------| | `a == b` | `sgn(a - b) == 0` | | `a > b` | `sgn(a - b) > 0` | | `a >= b` | `sgn(a - b) >= 0` | | `a < b` | `sgn(a - b) < 0` | | `a <= b` | `sgn(a - b) <= 0` | | `a != b` | `sgn(a - b) != 0` | 输入输出 -------- 用`scanf`输入浮点数时,`double`的占位符是`%lf`,但是浮点数`double`在`printf`系列函数中的标准占位符是`%f`而不是`%lf`,使用时最好使用前者,因为虽然后者在大部分的计算机和编译器中能得到正确结果,但在有些情况下会出错(比如在POJ上)。 开方 ---- 当提供给C语言中的标准库函数`double sqrt (double x)`的`x`为负值时,`sqrt`会返回`nan`,输出时会显示成`nan`或`-1.#IND00`(根据系统的不同)。在进行计算几何编程时,经常有对接近零的数进行开方的情况,如果输入的数是一个极小的负数,那么`sqrt`会返回`nan`这个错误的结果,导致输出错误。解决的方法就是将`sqrt`包装一下,在每次开方前进行判断。 #### 示例代码 ```cpp double my_sqrt(double x) { return sgn(x) == 0 ? 0.0 : sqrt(x); } ``` 负零 ---- 大部分的标程的输出是不会输出负零的,如下面这段程序: ```cpp int main() { printf("%.2f\n", -0.0000000001); return 0; } ``` 会输出`-0.00`。有时这样的结果是错误的,所以在没有Special Judge的题目要求四舍五入时,不要忘记对负零进行特殊判断。 但有的标程也不会进行这样的特殊判断,所以在WA时不要放弃摸索。 <file_sep>/README.md 前言 ==== 这是总的算法手册的前言。 <file_sep>/SUMMARY.md 目录 ==== <small>这些内容会与其他同学的`SUMMARY.md`合并起来。</small> * [计算几何](CG/README.md) * [浮点数相关的陷阱](CG/float-point-pitfall.md) * [向量](CG/vector.md) * [线段](CG/segment.md) * [三角形](CG/triangle.md) * [多边形](CG/polygon.md) * [凸包](CG/convex.md) * [半平面](CG/halfplane.md) * [圆](CG/circle.md) * [三维计算几何](CG/3d.md) <file_sep>/CG/vector.md 向量 ==== ## 简介 向量,又称矢量,是既有大小又有方向的量,向量的长度即向量的大小称为向量的模。在计算几何中,从$$A$$指向$$B$$的向量记作$$\vec{AB}$$。$$n$$维向量可以用$$n$$个实数来表示。向量的基本运算包括加减法、数乘、点积、叉积和混合积。使用向量这一个基本的数据结构,我们可以用向量表示点和更复杂的各种图形。 ## 注意事项 我们一般用一个二维向量来表示点。注意,在有些计算几何相关的题目中,坐标是可以利用整形储存的。在做这样的题目时,坐标一定要用整形变量储存,否则精度上容易出错。具体的将点的坐标用整形变量储存可以需要使用一些技巧,比如计算中计算平方或将坐标扩大二倍等方式。 ```cpp // Pt是Point的缩写 struct Pt { double x, y; Pt() { } Pt(double x, double y) : x(x), y(y) { } }; double norm(Pt p) { return sqrt(p.x*p.x + p.y*p.y); } void print(Pt p) { printf("(%f, %f)", p.x, p.y); } ``` ## 基本计算 ### 加减法 $$\vec{a} \pm \vec{b} = (a_x \pm b_x, a_y \pm b_y)$$ 向量的加减法遵从平行四边形法则和三角形法则。 ##### 示例代码 ```cpp Pt operator - (Pt a, Pt b) { return Pt(a.x - b.x, a.y - b.y); } Pt operator + (Pt a, Pt b) { return Pt(a.x + b.x, a.y + b.y); } ``` ### 长度 向量$$\vec{a}=(a_x, a_y)$$的长度是$$\sqrt{a_x^2+a_y^2}$$。 ##### 示例代码 ```cpp double len(Pt p) { return sqrt(sqr(p.x)+sqr(p.y)); } ``` ### 数乘 $$a\vec{b} = (a b_x, a b_y)$$。 向量的数乘是一个向量和实数的运算。$$a$$如果是零,那么结果是一个零向量,如果$$a$$是一个负数,那么结果向量会改变方向。 ##### 示例代码 ```cpp Pt operator * (double A, Pt p) { return Pt(p.x*A, p.y*A); } Pt operator * (Pt p, double A) { return Pt(p.x*A, p.y*A); } ``` ### 点积 又称内积。 $$\vec{a} \cdot \vec{b} = a_xb_x + a_yb_y = |\vec{a}||\vec{b}|\cos\theta$$,其中$$\theta$$是$$\vec{a}$$与$$\vec{b}$$的夹角。 #### 应用 点积可以用来计算两向量的夹角。 $$ \cos\beta = \frac{\vec{a} \cdot \vec{b}}{|\vec{a}||\vec{b}|} $$ ##### 示例代码 ```cpp double dot(Pt a, Pt b) { return a.x * b.x + a.y * b.y; } ``` ### 叉积 叉积又称外积。叉积运算得到的是一个向量,它的大小是$$\vec{a}$$和$$\vec{b}$$所构成的平行四边形的面积,方向与$$\vec{a}$$和$$\vec{b}$$所在平面垂直,$$\vec{a}$$、$$\vec{b}$$与$$\vec{a} \times \vec{b}$$成右手系。 设两向量$$\vec{a}=(a_x, a_y)$$与$$\vec{b}=(b_x, b_y)$$,它们在二维平面上的的叉积为: $$\vec{a} \times \vec{b} = a_xb_y - a_yb_x$$ ##### 示例代码 ```cpp double det(Pt a, Pt b) { return a.x * b.y - a.y * b.x; } ``` #### 性质与应用 叉积拥有两个重要的性质——面积与方向。 两向量叉积得到新向量的长度为这两个所构成的平行四边形的面积,利用这个性质我们可以求三角形的面积。 两向量叉积能反映出两向量方向的信息。如果$$\vec{a} \times \vec{b}$$的符号为正,那么$$\vec{b}$$在$$\vec{a}$$的逆时针方向;如果符号为负,那么$$\vec{b}$$在$$\vec{a}$$的顺时针方向;如果结果为零的话,那么$$\vec{a}$$与$$\vec{b}$$共线。 <center><img src="images/叉积性质的应用.png" style="width:600px;" /></center> | 计算结果 | $$b$$与$$a$$的方向 | |----------------------|--------------------------| | $$|b \times a| > 0$$ | $$a$$在$$b$$的逆时针方向 | | $$|b \times a| = 0$$ | $$a$$与$$b$$共线 | | $$|b \times a| < 0$$ | $$a$$在$$b$$的顺时针方向 | ## 模板代码 ```cpp Pt operator - (Pt a, Pt b) { return Pt(a.x - b.x, a.y - b.y); } Pt operator + (Pt a, Pt b) { return Pt(a.x + b.x, a.y + b.y); } Pt operator * (double A, Pt p) { return Pt(p.x*A, p.y*A); } Pt operator * (Pt p, double A) { return Pt(p.x*A, p.y*A); } Pt operator / (Pt p, double A) { return Pt(p.x/A, p.y/A); } ``` <file_sep>/CG/triangle.md 三角形 ====== ## 三角形的面积 三角形的面积可以由叉积直接求出。 $$ S_{\triangle ABC} = |\frac{1}{2} \vec{AB} \times \vec{AC}| $$ ## 判断点在三角形内 判断点$$P$$在三角形 ABC 内部常用的又两种方法,面积法和叉积法。 ### 面积法 $$ S_{\triangle PAB} + S_{\triangle PAC} + S_{\triangle PBC} = S_{\triangle ABC} $$ ### 叉积法 利用叉积的正负号判断,如图所示,AP在向量AC的顺时针方向,CP在向量BC的顺时针方向,BP在向量BC的顺时针方向,利用这一性质推广,那么可以利用叉积的正负号来判断一个点是否在一个凸多边形内部。 ## 三角形的重心 三角形三条中线的交点叫做三角形重心。 ### 性质 设三角形重心为$$O$$,$$BC$$边中点为$$D$$,则有$$AO = 2OD$$。 ### 求重心的方法 三角形的重心是三角形三个顶点的坐标的平均值。 ## 三角形的外心 三角形三边的垂直平分线的交点,称为三角形外心。 ### 性质 外心到三顶点距离相等。过三角形各顶点的圆叫做三角形的外接圆,外接圆的圆心即三角形外心,这个三角形叫做这个圆的内接三角形。 ## 三角形的内心 三角形内心为三角形三条内角平分线的交点。 ### 性质 与三角形各边都相切的圆叫做三角形的内切圆,内切圆的圆心即是三角形内心,内心到三角形三边距离相等。这个三角形叫做圆的外切三角形。 ## 三角形的垂心 三角形三边上的三条高线交于一点,称为三角形垂心。 ### 性质 锐角三角形的垂心在三角形内;直角三角形的垂心在直角的顶点;钝角三角形的垂心在三角形外。 ## 费马点 费马点是在一个三角形中,到3个顶点距离之和最小的点。 ### 计算方法 1. 若三角形ABC的3个内角均小于120度,那么3条距离连线正好平分费马点所在的周角。所以三角形的费马点也称为三角形的等角中心。 2. 若三角形有一内角不小于120度,则此钝角的顶点就是距离和最小的点。 #### 等角中心的计算方法 做任意一条边的外接等边三角形,得到另一点,将此点与此边在三角形中对应的点相连。如此再取另一边作同样的连线,相交点即费马点。 ```cpp #include <math.h> struct point{double x,y;}; struct line{point a,b;}; double distance(point p1,point p2){ return sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y)); } //已知两条直线求出交点 point intersection(line u,line v){ point ret=u.a; double t=((u.a.x-v.a.x)*(v.a.y-v.b.y)-(u.a.y-v.a.y)*(v.a.x-v.b.x)) /((u.a.x-u.b.x)*(v.a.y-v.b.y)-(u.a.y-u.b.y)*(v.a.x-v.b.x)); ret.x+=(u.b.x-u.a.x)*t; ret.y+=(u.b.y-u.a.y)*t; return ret; } //外心 point circumcenter(point a,point b,point c){ line u,v; u.a.x=(a.x+b.x)/2; u.a.y=(a.y+b.y)/2; u.b.x=u.a.x-a.y+b.y; u.b.y=u.a.y+a.x-b.x; v.a.x=(a.x+c.x)/2; v.a.y=(a.y+c.y)/2; v.b.x=v.a.x-a.y+c.y; v.b.y=v.a.y+a.x-c.x; return intersection(u,v); } //内心 point incenter(point a,point b,point c){ line u,v; double m,n; u.a=a; m=atan2(b.y-a.y,b.x-a.x); n=atan2(c.y-a.y,c.x-a.x); u.b.x=u.a.x+cos((m+n)/2); u.b.y=u.a.y+sin((m+n)/2); v.a=b; m=atan2(a.y-b.y,a.x-b.x); n=atan2(c.y-b.y,c.x-b.x); v.b.x=v.a.x+cos((m+n)/2); v.b.y=v.a.y+sin((m+n)/2); return intersection(u,v); } //垂心 point perpencenter(point a,point b,point c){ line u,v; u.a=c; u.b.x=u.a.x-a.y+b.y; u.b.y=u.a.y+a.x-b.x; v.a=b; v.b.x=v.a.x-a.y+c.y; v.b.y=v.a.y+a.x-c.x; return intersection(u,v); } //重心 //到三角形三顶点距离的平方和最小的点 //三角形内到三边距离之积最大的点 point barycenter(point a,point b,point c){ line u,v; u.a.x=(a.x+b.x)/2; u.a.y=(a.y+b.y)/2; u.b=c; v.a.x=(a.x+c.x)/2; v.a.y=(a.y+c.y)/2; v.b=b; return intersection(u,v); } //费马点(模拟退火) point fermentpoint(point a,point b,point c){ point u,v; double step=fabs(a.x)+fabs(a.y)+fabs(b.x)+fabs(b.y)+fabs(c.x)+fabs(c.y); int i,j,k; u.x=(a.x+b.x+c.x)/3; u.y=(a.y+b.y+c.y)/3; while (step>1e-10) for (k=0;k<10;step/=2,k++) for (i=-1;i<=1;i++) for (j=-1;j<=1;j++){ v.x=u.x+step*i; v.y=u.y+step*j; if(distance(u,a)+distance(u,b)+distance(u,c) > distance(v,a)+distance(v,b)+distanc e(v,c)) u=v; } return u; } ``` <file_sep>/CG/halfplane.md 半平面 ====== ## 简介 1. 什么是半平面?顾名思义,半平面就是指平面的一半,我们知道,一条直线可以将平面分为两个部分,那么这两个部分就叫做两个半平面。 2. 半平面怎么表示呢?二维坐标系下,直线可以表示为 ax + by + c = 0,那么两个半平面则可以表示为 ax + by + c >= 0 和 ax + by + c < 0,这就是半平面的表示方法。 3. 半平面的交是什么? 其实就是一个方程组,让你画出满足若干个式子的坐标系上的区域(类似于线性规划的可行域),方程组就是由类似于上面的这些不等式组成的。 4. 半平面交可以干什么? 半平面交虽然说是半平面的问题,但它其实就是关于直线的问题。一个一个的半平面其实就是一个一个有方向的直线而已。 ## 半平面交求法 我们用一个向量$$(x_1,y_1)\rightarrow(x_x,y_x)$$的左侧来描述一个半平面。首先将半平面按照极角排序,极角相同的则只保留最左侧的一个。然后用一个双端队列维护这些半平面:按照顺序插入,在插入半平面$$p_i$$之前判断双端队列尾部的两个半平面的交点是否在半平面$$p_i$$内,如果不是则删除最后一个半平面;判断双端队列尾部的两个半平面交是否在半平面$$p_i$$内,如果不是则删除第一个半平面。插入完毕之后再处理一下双端队列两端多余的半平面,最后求出尾端和顶端的两个半平面的交点即可。 ### 模板代码 ```cpp // 计算半平面交 void halfplane_intersect(vector<HP> &v, Convex &output) { sort(v.begin(), v.end(), cmp_HP); deque<HP> q; deque<Pt> ans; q.push_back(v[0]); int n = v.size(); for (int i = 1; i < n; ++i) { if (sgn(arg(v[i].t-v[i].s) - arg(v[i-1].t-v[i-1].s)) == 0) continue; while (ans.size() > 0 && !satisfy(ans.back(), v[i])) { ans.pop_back(); q.pop_back(); } while (ans.size() > 0 && !satisfy(ans.front(), v[i])) { ans.pop_front(); q.pop_front(); } ans.push_back(crosspoint(q.back(), v[i])); q.push_back(v[i]); } while (ans.size() > 0 && !satisfy(ans.back(), q.front())) { ans.pop_back(); q.pop_back(); } while (ans.size() > 0 && !satisfy(ans.front(), q.back())) { ans.pop_front(); q.pop_front(); } ans.push_back(crosspoint(q.back(), q.front())); output = vector<Pt>(ans.begin(), ans.end()); } ``` ## 凸多边形交 ```cpp // 凸多边形交 void convex_intersection(const Convex &v1, const Convex &v2, Convex &out) { vector<HP> h; for (int i = 0, n = v1.size(); i < n; ++i) h.push_back(HP(v1[i], v1[nxt(i)])); for (int i = 0, n = v2.size(); i < n; ++i) h.push_back(HP(v2[i], v2[nxt(i)])); halfplane_intersect(h, out); } ``` <file_sep>/CG/polygon.md 多边形 ====== ## 简单多边形 简单多边形是边不相交的多边形,大部分我们在编程竞赛中的计算几何题目中的多边形都是简单多边形,所以在这个手册中所提到的多边形都是简单多边形。 ## 判断点在多边形内 ### 判断方法 判断点在多边形内:从该点做一条水平向右的射线,统计射线与多边形相交的情况,若相交次数为偶数,则说明该点在形外,否则在形内。为了便于交点在定点或射线与某些边重合时的判断,可以将每条边看成左开右闭的线段,即若交点为左端点就不计算。 ### 示例代码 ```cpp #define nxt(x) ((x+1)%n) int PtInPolygon(Pt p, Polygon &a) { int num = 0, d1, d2, k, n = size(a); for (int i = 0; i < n; ++i) { if (PtOnSegment(p, a[i], a[nxt(i)])) { return 2; } k = sgn(det(a[nxt(i)]-a[i], p-a[i])); d1 = sgn(a[i].y - p.y); d2 = sgn(a[nxt(i)] - p.y); if (k > 0 && d1 <= 0 && d2 > 0) num++; if (k < 0 && d2 <= 0 && d1 > 0) num--; } return num != 0; } ``` ## 多边形的面积 ### 求法 多边形的面积可以靠三角剖分求得。对多边形的每一条边和原点$$O$$所组成的三角形通过叉积求有向面积并简单求和,就可以求得多边形的有向面积。而且通过求得的有向面积能判断出多边形中点的方向。如果输入多边形点的方向是按照逆时针给出的话,求得的面积就是正数,如果输入的多边形的点是按照顺时针给出的话,求得的面积就是负数。 #### 示例代码 ```cpp #define nxt(x) ((x+1)%n) double polygon_area(const Polygon &p) { double ans = 0.0; int n = p.size(); for (int i = 0; i < n; ++i) ans += det(p[i], p[nxt(i)]); return ans / 2.0; } ``` ## 多边形的重心 ### 算法 将多边形分割为三角形的并,并对每个三角形求重心,然后以三角形的有向面积为权值将所有面积加权求和即可。 #### 示例代码 ```cpp #define nxt(x) ((x+1)%n) Pt polygon_mass_center(const Polygon &p) { Pt ans = Pt(0, 0); double area = polygon_area(p); if (sgn(area) == 0) return ans; int n = p.size(); for (int i = 0; i < n; ++i) ans = ans + (p[i]+p[nxt(i)]) * det(p[i], p[nxt(i)]); return ans / area / 6.0; } ``` ## 多边形内的格点数 ### Pick公式 给定顶点坐标均是整点的简单多边形,有: ``` 面积 = 内部格点数 + 边上格点数 / 2 - 1 ``` ### 边界的格点数 把每条边当作左开右闭的区间避免重复,一条左开右闭的线段$$AB$$上的格点数为$$gcd(B_x-A_x,B_y-A_y)$$。 ```cpp int polygon_border_point_cnt(const Polygon &p) { int ans = 0; int n = p.size(); for (int i = 0; i < n; ++i) ans += gcd(Abs(int(p[next(i)].x-p[i].x)), Abs(int(p[next(i)].y-p[i].y))); return ans; } int polygon_inside_point_cnt(const Polygon &p) { return int(polygon_area(p)) + 1 - polygon_border_point_cnt(p) / 2; } ``` <file_sep>/_book/CG/3d.html <!DOCTYPE HTML> <html lang="en" > <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <title>三维计算几何 | 前言</title> <meta content="text/html; charset=utf-8" http-equiv="Content-Type"> <meta name="description" content=""> <meta name="generator" content="GitBook 2.4.2"> <meta name="HandheldFriendly" content="true"/> <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no"> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-status-bar-style" content="black"> <link rel="apple-touch-icon-precomposed" sizes="152x152" href="../gitbook/images/apple-touch-icon-precomposed-152.png"> <link rel="shortcut icon" href="../gitbook/images/favicon.ico" type="image/x-icon"> <link rel="stylesheet" href="../gitbook/style.css"> <link rel="stylesheet" href="../gitbook/plugins/gitbook-plugin-katex/katex.min.css"> <link rel="stylesheet" href="../gitbook/plugins/gitbook-plugin-highlight/website.css"> <link rel="prev" href="../CG/circle.html" /> </head> <body> <div class="book" data-level="1.9" data-basepath=".." data-revision="Thu Feb 18 2016 14:48:02 GMT+0800 (中国标准时间)"> <div class="book-summary"> <div class="book-search" role="search"> <input type="text" placeholder="Type to search" class="form-control" /> </div> <nav role="navigation"> <ul class="summary"> <li class="chapter " data-level="0" data-path="index.html"> <a href="../index.html"> <i class="fa fa-check"></i> Introduction </a> </li> <li class="chapter " data-level="1" data-path="CG/index.html"> <a href="../CG/index.html"> <i class="fa fa-check"></i> <b>1.</b> 计算几何 </a> <ul class="articles"> <li class="chapter " data-level="1.1" data-path="CG/float-point-pitfall.html"> <a href="../CG/float-point-pitfall.html"> <i class="fa fa-check"></i> <b>1.1.</b> 浮点数相关的陷阱 </a> </li> <li class="chapter " data-level="1.2" data-path="CG/vector.html"> <a href="../CG/vector.html"> <i class="fa fa-check"></i> <b>1.2.</b> 向量 </a> </li> <li class="chapter " data-level="1.3" data-path="CG/segment.html"> <a href="../CG/segment.html"> <i class="fa fa-check"></i> <b>1.3.</b> 线段 </a> </li> <li class="chapter " data-level="1.4" data-path="CG/triangle.html"> <a href="../CG/triangle.html"> <i class="fa fa-check"></i> <b>1.4.</b> 三角形 </a> </li> <li class="chapter " data-level="1.5" data-path="CG/polygon.html"> <a href="../CG/polygon.html"> <i class="fa fa-check"></i> <b>1.5.</b> 多边形 </a> </li> <li class="chapter " data-level="1.6" data-path="CG/convex.html"> <a href="../CG/convex.html"> <i class="fa fa-check"></i> <b>1.6.</b> 凸包 </a> </li> <li class="chapter " data-level="1.7" data-path="CG/halfplane.html"> <a href="../CG/halfplane.html"> <i class="fa fa-check"></i> <b>1.7.</b> 半平面 </a> </li> <li class="chapter " data-level="1.8" data-path="CG/circle.html"> <a href="../CG/circle.html"> <i class="fa fa-check"></i> <b>1.8.</b> 圆 </a> </li> <li class="chapter active" data-level="1.9" data-path="CG/3d.html"> <a href="../CG/3d.html"> <i class="fa fa-check"></i> <b>1.9.</b> 三维计算几何 </a> </li> </ul> </li> <li class="divider"></li> <li> <a href="https://www.gitbook.com" target="blank" class="gitbook-link"> Published with GitBook </a> </li> </ul> </nav> </div> <div class="book-body"> <div class="body-inner"> <div class="book-header" role="navigation"> <!-- Actions Left --> <a href="#" class="btn pull-left toggle-summary" aria-label="Table of Contents"><i class="fa fa-align-justify"></i></a> <a href="#" class="btn pull-left toggle-search" aria-label="Search"><i class="fa fa-search"></i></a> <div id="font-settings-wrapper" class="dropdown pull-left"> <a href="#" class="btn toggle-dropdown" aria-label="Font Settings"><i class="fa fa-font"></i> </a> <div class="dropdown-menu font-settings"> <div class="dropdown-caret"> <span class="caret-outer"></span> <span class="caret-inner"></span> </div> <div class="buttons"> <button type="button" id="reduce-font-size" class="button size-2">A</button> <button type="button" id="enlarge-font-size" class="button size-2">A</button> </div> <div class="buttons font-family-list"> <button type="button" data-font="0" class="button">Serif</button> <button type="button" data-font="1" class="button">Sans</button> </div> <div class="buttons color-theme-list"> <button type="button" id="color-theme-preview-0" class="button size-3" data-theme="0">White</button> <button type="button" id="color-theme-preview-1" class="button size-3" data-theme="1">Sepia</button> <button type="button" id="color-theme-preview-2" class="button size-3" data-theme="2">Night</button> </div> </div> </div> <!-- Actions Right --> <div class="dropdown pull-right"> <a href="#" class="btn toggle-dropdown" aria-label="Share"><i class="fa fa-share-alt"></i> </a> <div class="dropdown-menu font-settings dropdown-left"> <div class="dropdown-caret"> <span class="caret-outer"></span> <span class="caret-inner"></span> </div> <div class="buttons"> <button type="button" data-sharing="twitter" class="button"> Share on Twitter </button> <button type="button" data-sharing="google-plus" class="button"> Share on Google </button> <button type="button" data-sharing="facebook" class="button"> Share on Facebook </button> <button type="button" data-sharing="weibo" class="button"> Share on Weibo </button> <button type="button" data-sharing="instapaper" class="button"> Share on Instapaper </button> </div> </div> </div> <a href="#" target="_blank" class="btn pull-right google-plus-sharing-link sharing-link" data-sharing="google-plus" aria-label="Google"><i class="fa fa-google-plus"></i></a> <a href="#" target="_blank" class="btn pull-right facebook-sharing-link sharing-link" data-sharing="facebook" aria-label="Facebook"><i class="fa fa-facebook"></i></a> <a href="#" target="_blank" class="btn pull-right twitter-sharing-link sharing-link" data-sharing="twitter" aria-label="Twitter"><i class="fa fa-twitter"></i></a> <!-- Title --> <h1> <i class="fa fa-circle-o-notch fa-spin"></i> <a href="../" >前言</a> </h1> </div> <div class="page-wrapper" tabindex="-1" role="main"> <div class="page-inner"> <section class="normal" id="section-"> <h1 id="%E4%B8%89%E7%BB%B4%E8%AE%A1%E7%AE%97%E5%87%A0%E4%BD%95">&#x4E09;&#x7EF4;&#x8BA1;&#x7B97;&#x51E0;&#x4F55;</h1> <h2 id="%E4%B8%89%E7%BB%B4%E5%87%B8%E5%8C%85">&#x4E09;&#x7EF4;&#x51F8;&#x5305;</h2> <pre><code class="lang-cpp"><span class="hljs-preprocessor">#<span class="hljs-keyword">include</span> <span class="hljs-string">&lt;cstdio&gt;</span></span> <span class="hljs-preprocessor">#<span class="hljs-keyword">include</span> <span class="hljs-string">&lt;cstring&gt;</span></span> <span class="hljs-preprocessor">#<span class="hljs-keyword">include</span> <span class="hljs-string">&lt;algorithm&gt;</span></span> <span class="hljs-preprocessor">#<span class="hljs-keyword">include</span> <span class="hljs-string">&lt;vector&gt;</span></span> <span class="hljs-preprocessor">#<span class="hljs-keyword">include</span> <span class="hljs-string">&lt;iomanip&gt;</span></span> <span class="hljs-preprocessor">#<span class="hljs-keyword">include</span> <span class="hljs-string">&lt;iostream&gt;</span></span> <span class="hljs-preprocessor">#<span class="hljs-keyword">include</span> <span class="hljs-string">&lt;cmath&gt;</span></span> <span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>; <span class="hljs-comment">/* Macros */</span> <span class="hljs-comment">/******************************************************************************/</span> <span class="hljs-preprocessor">#<span class="hljs-keyword">define</span> nxt(i) ((i+<span class="hljs-number">1</span>)%n)</span> <span class="hljs-preprocessor">#<span class="hljs-keyword">define</span> nxt2(i, x) ((i+<span class="hljs-number">1</span>)%((x).size()))</span> <span class="hljs-preprocessor">#<span class="hljs-keyword">define</span> prv(i) ((i+(x).size()-<span class="hljs-number">1</span>)%n)</span> <span class="hljs-preprocessor">#<span class="hljs-keyword">define</span> prv2(i, x) ((i+(x).size()-<span class="hljs-number">1</span>)%((x).size()))</span> <span class="hljs-preprocessor">#<span class="hljs-keyword">define</span> sz(x) (int((x).size()))</span> <span class="hljs-preprocessor">#<span class="hljs-keyword">define</span> setpre(x) do{cout&lt;&lt;setprecision(x)&lt;&lt;setiosflags(ios::fixed);}while(<span class="hljs-number">0</span>)</span> <span class="hljs-comment">/* Real number tools */</span> <span class="hljs-comment">/******************************************************************************/</span> <span class="hljs-keyword">const</span> <span class="hljs-keyword">double</span> PI = <span class="hljs-built_in">acos</span>(-<span class="hljs-number">1.0</span>); <span class="hljs-keyword">const</span> <span class="hljs-keyword">double</span> eps = <span class="hljs-number">1e-8</span>; <span class="hljs-function"><span class="hljs-keyword">double</span> <span class="hljs-title">mysqrt</span><span class="hljs-params">(<span class="hljs-keyword">double</span> x)</span> </span>{ <span class="hljs-keyword">return</span> x &lt;= <span class="hljs-number">0.0</span> ? <span class="hljs-number">0.0</span> : <span class="hljs-built_in">sqrt</span>(x); } <span class="hljs-function"><span class="hljs-keyword">double</span> <span class="hljs-title">sq</span><span class="hljs-params">(<span class="hljs-keyword">double</span> x)</span> </span>{ <span class="hljs-keyword">return</span> x*x; } <span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">sgn</span><span class="hljs-params">(<span class="hljs-keyword">double</span> x)</span> </span>{ <span class="hljs-keyword">return</span> x &lt; -eps ? -<span class="hljs-number">1</span> : x &gt; eps ? <span class="hljs-number">1</span> : <span class="hljs-number">0</span>; } <span class="hljs-comment">/* 3d Point */</span> <span class="hljs-comment">/******************************************************************************/</span> <span class="hljs-keyword">struct</span> Pt3 { <span class="hljs-keyword">double</span> x, y, z; Pt3() { } Pt3(<span class="hljs-keyword">double</span> x, <span class="hljs-keyword">double</span> y, <span class="hljs-keyword">double</span> z) : x(x), y(y), z(z) { } }; <span class="hljs-keyword">typedef</span> <span class="hljs-keyword">const</span> Pt3 cPt3; <span class="hljs-keyword">typedef</span> cPt3 &amp; cPt3r; Pt3 <span class="hljs-keyword">operator</span> + (cPt3r a, cPt3r b) { <span class="hljs-keyword">return</span> Pt3(a.x+b.x, a.y+b.y, a.z+b.z); } Pt3 <span class="hljs-keyword">operator</span> - (cPt3r a, cPt3r b) { <span class="hljs-keyword">return</span> Pt3(a.x-b.x, a.y-b.y, a.z-b.z); } Pt3 <span class="hljs-keyword">operator</span> * (cPt3r a, <span class="hljs-keyword">double</span> A) { <span class="hljs-keyword">return</span> Pt3(a.x*A, a.y*A, a.z*A); } Pt3 <span class="hljs-keyword">operator</span> * (<span class="hljs-keyword">double</span> A, cPt3r a) { <span class="hljs-keyword">return</span> Pt3(a.x*A, a.y*A, a.z*A); } Pt3 <span class="hljs-keyword">operator</span> / (cPt3r a, <span class="hljs-keyword">double</span> A) { <span class="hljs-keyword">return</span> Pt3(a.x/A, a.y/A, a.z/A); } <span class="hljs-keyword">bool</span> <span class="hljs-keyword">operator</span> == (cPt3r a, cPt3r b) { <span class="hljs-keyword">return</span> !sgn(a.x-b.x) &amp;&amp; !sgn(a.y-b.y) &amp;&amp; !sgn(a.z-b.z); } istream&amp; <span class="hljs-keyword">operator</span> &gt;&gt; (istream&amp; sm, Pt3 &amp;pt) { sm &gt;&gt; pt.x &gt;&gt; pt.y &gt;&gt; pt.z; <span class="hljs-keyword">return</span> sm; } ostream &amp; <span class="hljs-keyword">operator</span> &lt;&lt; (ostream&amp; sm, cPt3r pt) { sm &lt;&lt; <span class="hljs-string">&quot;(&quot;</span> &lt;&lt; pt.x &lt;&lt; <span class="hljs-string">&quot;, &quot;</span> &lt;&lt; pt.y &lt;&lt; <span class="hljs-string">&quot;, &quot;</span> &lt;&lt; pt.z &lt;&lt; <span class="hljs-string">&quot;)&quot;</span>; <span class="hljs-keyword">return</span> sm; } <span class="hljs-function"><span class="hljs-keyword">double</span> <span class="hljs-title">len</span><span class="hljs-params">(cPt3r p)</span> </span>{ <span class="hljs-keyword">return</span> mysqrt(sq(p.x) + sq(p.y) + sq(p.z)); } <span class="hljs-function"><span class="hljs-keyword">double</span> <span class="hljs-title">dist</span><span class="hljs-params">(cPt3r a, cPt3r b)</span> </span>{ <span class="hljs-keyword">return</span> len(a-b); } <span class="hljs-function">Pt3 <span class="hljs-title">unit</span><span class="hljs-params">(cPt3r p)</span> </span>{ <span class="hljs-keyword">return</span> p / len(p); } <span class="hljs-function">Pt3 <span class="hljs-title">det</span><span class="hljs-params">(cPt3r a, cPt3r b)</span> </span>{ <span class="hljs-keyword">return</span> Pt3(a.y*b.z-a.z*b.y, a.z*b.x-a.x*b.z, a.x*b.y-a.y*b.x); } <span class="hljs-function"><span class="hljs-keyword">double</span> <span class="hljs-title">dot</span><span class="hljs-params">(cPt3r a, cPt3r b)</span> </span>{ <span class="hljs-keyword">return</span> a.x*b.x + a.y*b.y + a.z*b.z; } <span class="hljs-function"><span class="hljs-keyword">double</span> <span class="hljs-title">mix</span><span class="hljs-params">(cPt3r a, cPt3r b, cPt3r c)</span> </span>{ <span class="hljs-keyword">return</span> dot(a, det(b, c)); } <span class="hljs-comment">/* 3d Line &amp; Segment */</span> <span class="hljs-comment">/******************************************************************************/</span> <span class="hljs-keyword">struct</span> Ln3 { Pt3 a, b; Ln3() { } Ln3(cPt3r a, cPt3r b) : a(a), b(b) { } }; <span class="hljs-keyword">typedef</span> <span class="hljs-keyword">const</span> Ln3 cLn3; <span class="hljs-keyword">typedef</span> cLn3 &amp; cLn3r; <span class="hljs-function"><span class="hljs-keyword">bool</span> <span class="hljs-title">ptonln</span><span class="hljs-params">(cPt3r a, cPt3r b, cPt3r c)</span> </span>{ <span class="hljs-keyword">return</span> sgn(len(det(a-b, b-c))) &lt;= <span class="hljs-number">0</span>; } <span class="hljs-comment">/* 3d Plane */</span> <span class="hljs-comment">/******************************************************************************/</span> <span class="hljs-keyword">struct</span> Pl { Pt3 a, b, c; Pl() { } Pl(cPt3r a, cPt3r b, cPt3r c) : a(a), b(b), c(c) { } }; <span class="hljs-keyword">typedef</span> <span class="hljs-keyword">const</span> Pl cPl; <span class="hljs-keyword">typedef</span> cPl &amp; cPlr; <span class="hljs-function">Pt3 <span class="hljs-title">nvec</span><span class="hljs-params">(cPlr pl)</span> </span>{ <span class="hljs-keyword">return</span> det(pl.a-pl.b, pl.b-pl.c); } <span class="hljs-comment">/* Solution */</span> <span class="hljs-comment">/******************************************************************************/</span> <span class="hljs-function"><span class="hljs-keyword">bool</span> <span class="hljs-title">cmp</span><span class="hljs-params">(cPt3r a, cPt3r b)</span> </span>{ <span class="hljs-keyword">if</span> (sgn(a.x-b.x)) <span class="hljs-keyword">return</span> sgn(a.x-b.x) &lt; <span class="hljs-number">0</span>; <span class="hljs-keyword">if</span> (sgn(a.y-b.y)) <span class="hljs-keyword">return</span> sgn(a.y-b.y) &lt; <span class="hljs-number">0</span>; <span class="hljs-keyword">if</span> (sgn(a.z-b.z)) <span class="hljs-keyword">return</span> sgn(a.z-b.z) &lt; <span class="hljs-number">0</span>; <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>; } <span class="hljs-keyword">struct</span> Face { <span class="hljs-keyword">int</span> a, b, c; Face() { } Face(<span class="hljs-keyword">int</span> a, <span class="hljs-keyword">int</span> b, <span class="hljs-keyword">int</span> c) : a(a), b(b), c(c) { } }; <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">convex3d</span><span class="hljs-params">(<span class="hljs-built_in">vector</span>&lt;Pt3&gt; &amp;p, <span class="hljs-built_in">vector</span>&lt;Pl&gt; &amp;out)</span> </span>{ sort(p.begin(), p.end(), cmp); p.erase(unique(p.begin(), p.end()), p.end()); random_shuffle(p.begin(), p.end()); <span class="hljs-built_in">vector</span>&lt;Face&gt; face; <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">2</span>; i &lt; sz(p); ++i) { <span class="hljs-keyword">if</span> (ptonln(p[<span class="hljs-number">0</span>], p[<span class="hljs-number">1</span>], p[i])) <span class="hljs-keyword">continue</span>; swap(p[i], p[<span class="hljs-number">2</span>]); <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> j = i + <span class="hljs-number">1</span>; j &lt; sz(p); ++j) <span class="hljs-keyword">if</span> (sgn(mix(p[<span class="hljs-number">1</span>]-p[<span class="hljs-number">0</span>], p[<span class="hljs-number">2</span>]-p[<span class="hljs-number">1</span>], p[j]-p[<span class="hljs-number">0</span>])) != <span class="hljs-number">0</span>) { swap(p[j], p[<span class="hljs-number">3</span>]); face.push_back(Face(<span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>)); face.push_back(Face(<span class="hljs-number">0</span>, <span class="hljs-number">2</span>, <span class="hljs-number">1</span>)); <span class="hljs-keyword">goto</span> found; } } found: <span class="hljs-built_in">vector</span>&lt;<span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt; &gt; mark(sz(p), <span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt;(sz(p), <span class="hljs-number">0</span>)); <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> v = <span class="hljs-number">3</span>; v &lt; sz(p); ++v) { <span class="hljs-built_in">vector</span>&lt;Face&gt; tmp; <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; sz(face); ++i) { <span class="hljs-keyword">int</span> a = face[i].a, b = face[i].b, c = face[i].c; <span class="hljs-keyword">if</span> (sgn(mix(p[a]-p[v], p[b]-p[v], p[c]-p[v])) &lt; <span class="hljs-number">0</span>) { mark[a][b] = mark[b][a] = v; mark[b][c] = mark[c][b] = v; mark[c][a] = mark[a][c] = v; }<span class="hljs-keyword">else</span>{ tmp.push_back(face[i]); } } face = tmp; <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; sz(tmp); ++i) { <span class="hljs-keyword">int</span> a = face[i].a, b = face[i].b, c = face[i].c; <span class="hljs-keyword">if</span> (mark[a][b] == v) face.push_back(Face(b, a, v)); <span class="hljs-keyword">if</span> (mark[b][c] == v) face.push_back(Face(c, b, v)); <span class="hljs-keyword">if</span> (mark[c][a] == v) face.push_back(Face(a, c, v)); } } out.clear(); <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; sz(face); ++i) out.push_back(Pl(p[face[i].a], p[face[i].b], p[face[i].c])); } <span class="hljs-built_in">vector</span>&lt;Pt3&gt; p; <span class="hljs-built_in">vector</span>&lt;Pl&gt; out; <span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{ <span class="hljs-keyword">int</span> n; <span class="hljs-built_in">cin</span> &gt;&gt; n; <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; n; ++i) { Pt3 pt; <span class="hljs-built_in">cin</span> &gt;&gt; pt; p.push_back(pt); } convex3d(p, out); <span class="hljs-keyword">double</span> area = <span class="hljs-number">0.0</span>; <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; sz(out); ++i) area += len(det(out[i].a-out[i].b, out[i].b-out[i].c)); setpre(<span class="hljs-number">3</span>); <span class="hljs-built_in">cout</span> &lt;&lt; area / <span class="hljs-number">2.0</span> &lt;&lt; <span class="hljs-string">&quot;\n&quot;</span>; <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>; } </code></pre> </section> </div> </div> </div> <a href="../CG/circle.html" class="navigation navigation-prev navigation-unique" aria-label="Previous page: 圆"><i class="fa fa-angle-left"></i></a> </div> </div> <script src="../gitbook/app.js"></script> <script src="../gitbook/plugins/gitbook-plugin-livereload/plugin.js"></script> <script> require(["gitbook"], function(gitbook) { var config = {"fontSettings":{"theme":null,"family":"sans","size":2}}; gitbook.start(config); }); </script> </body> </html> <file_sep>/CG/convex.md 凸包 ==== ## 点的有序化 凸包算法多要先对点进行排序。点排序的主要方法有两种——极角排序和水平排序。 ### 极角排序 极角排序一般选择一个点做极点,然后以这个点为中心建立极坐标,将输入的点按照极角从小到大排序,如果两个点的极角相同,那么将距离极点较远的点排在前面。 ### 水平排序 水平排序将所有点按照$$y$$坐标从小到大排列,$$y$$坐标相同的则按照$$x$$坐标从小到大排序。选取排序后最前面的$$A$$点和最后面的$$B$$点,将$$\vec{AB}$$右边的点按照次序取出,再将左侧的点按照次序逆序取出后连起来就是最终的结果。 ### 比较 虽然水平排序比较复杂,但水平排序因为不涉及三角函数操作,精度较高,在条件相同时,最好选择水平排序。 ## 凸包求法 ### Graham 扫描法 Graham 算法是在某种意义上来说求解二维静态凸包的一种最优的算法,这种算法目前被广泛的应用于对各种以二维静态凸包为基础的 ACM 题目的求解。Graham 算法的时间复杂度大约是 nlogn,因此在求解二维平面上几万个点构成的凸包时,消耗的时间相对较少。 #### 算法描述 这里描述的 Graham 算法是经过改进后的算法而不是原始算法,因为改进之后的算法更易于对算法进行编码。 1. 已知有 n 个点的平面点集 p(p[0]~p[n-1]),找到二维平面中最下最左的点,即 y 坐标最小的点。若有多个 y 值最小的点,取其中 x 值最小的点。 2. 以这个最下最左的点作为基准点(即 p[0]),对二维平面上的点进行极角排序。 3. 将 p[0]、p[1]、p[2]三个点压入栈中(栈用 st 表示,top 表示栈顶指针的位置)。并将 p[0]的值赋给 p[n]。 4. 循环遍历平面点集 p[3]到 p[n]。对于每个 p[i]( 3<=i<=n)若存在 p[i]在向量st[top-1]st[top]的顺时针方(包括共线)向且栈顶元素不多于 2 个时,将栈顶元素出栈,直到 p[i]在向量 st[top-1]st[top]的逆时针方向或栈中元素个数小于 3 时将 p[i]入栈。 5. 循环结束后,栈 st 中存储的点正好就是凸包的所有顶点,且这些顶点以逆时针的顺序存储在栈中(st[0]~st[top-1])。注意:由于第三步中,将 p[0]的值赋给了 p[n],此时栈顶元素 st[top]和 st[0]相同,因为最后入栈的点是 p[n]。 由于 Graham 算法是基于极角排序的,对平面上所有点极角排序的时间复杂度是nlogn,而之后逐点扫描的过程的时间复杂度是 n,因此整个 Graham 算法的时间复杂度接近 nlogn。 #### 实现细节的注意事项 ##### 极角大小问题 实际实现 Graham 算法的极角排序并不是真正的按照极角大小排序,因为计算机在表示和计算浮点数时会有一定的误差。一般会利用叉积判断两个点的相对位置来实现极角排序的功能。假设以确定平面中最下最左的点(基准点)P,并已知平面上其它两个不同的点 A B。若点 A 在向量 PB 的逆时针方向,那么我们认为 A 的极角大于 B 的极角,反之 A 的极角小于 B 的极角(具体实现应借助叉积)。 ##### 极角相同点的处理 在 Graham 算法中,经常会出现两个点极角相同的情况。对于具有相同极角的两个不同点 A B,那么我们应该把 A B 两点的按照距离基准点距离的降序排列。而对于完全重合的两点,可以暂不做处理。 ### 模板代码 ```cpp typedef vector<Pt> Convex; // 排序比较函数,水平序 bool comp_less(Pt a, Pt b) { return sgn(a.x-b.x) < 0 || (sgn(a.x-b.x) == 0 && sgn(a.y-b.y) < 0); } // 返回a中点计算出的凸包,结果存在res中 void convex_hull(Convex &res, vector<Pt> a) { res.resize(2 * a.size() + 5); sort(a.begin(), a.end(), comp_less); a.erase(unique(a.begin(), a.end()), a.end()); int m = 0; for (int i = 0; i < int(a.size()); ++i) { while (m>1 && sgn(det(res[m-1] - res[m-2], a[i] - res[m-2])) <= 0) --m; res[m++] = a[i]; } int k = m; for (int i = int(a.size()) - 2; i >= 0; --i) { while (m>k && sgn(det(res[m-1] - res[m-2], a[i] - res[m-2])) <= 0) --m; res[m++] = a[i]; } res.resize(m); if (a.size() > 1) res.resize(m-1); } ``` ### Jarvis 步进法 Jarvis 步进法运用了一种称为打包的技术来计算一个点集 Q 的凸包。算法的运行时间 为 O(nh),其中 h 为凸包 CH(Q)的顶点数。 当 h 为 O(lg(n)),Jarvis 步进法在渐进意义上 比 Graham 算法的速度快一点。 从直观上看,可以把 Jarvis 步进法相像成在集合 Q 的外面紧紧的包了一层纸。开始 时,把纸的末端粘在集合中最低的点上,即粘在与 Graham 算法开始时相同的点 p0 上。该 点为凸包的一个顶点。把纸拉向右边使其绷紧,然后再把纸拉高一些,知道碰到一个点。 该点也必定为凸包中的一个顶点。使纸保持绷紧状态,用这种方法继续围绕顶点集合,直 到回到原始点 p0。 更形式的说,Jarvis 步进法构造了 CH(Q)的顶点序列 H=(P0,P1,…,Ph-1),其中 P0 为 原始点。如图所示,下一个凸包顶点 P1 具有相对与 P0 的最小极角。(如果有数个这样的 点,选择最远的那个点作为 P1。)类似地,P2 具有相对于 P1 的最小的极角,等等。当达 到最高顶点,如 Pk(如果有数个这样的点,选择最远的那个点)时,我们构造好了 CH(Q) 的右链了,为了构造其左链,从 Pk 开始选取相对于 Pk 具有最小极角的点作为 Pk+1,这时 的 x 轴是原 x 轴的反方向,如此继续,根据负 x 轴的极角逐渐形成左链,知道回到原始点 P0。 ## 旋转卡壳 ### 模板代码 ```cpp // 计算凸包a的直径 double convex_diameter(const Convex &a, int &first, int &second) { int n = a.size(); double ans = 0.0; first = second = 0; if (n == 1) return ans; for (int i = 0, j = 1; i < n; ++i) { while (sgn(det(a[nxt(i)]-a[i], a[j]-a[i]) - det(a[nxt(i)]-a[i], a[nxt(j)]-a[i])) < 0) j = nxt(j); double d = max((a[i]-a[j]).norm(), (a[nxt(i)]-a[nxt(j)]).norm()); if (d > ans) ans=d, first=i, second=j; } return ans; } ``` <file_sep>/CG/segment.md # 线段 ## 直线与线段的表示方法 我们可以用一条线段的两个端点来表示一条线段。直线的表示有两种方式,一种方式是使用二元一次方程$$y=kx+b$$来表示,另一种是用直线上任意一条长度不为零的线段来表示。由于使用方程表示接近垂直于某坐标轴的直线时容易产生精度误差,所以我们通常使用直线上的某条线段来表示直线。 ```cpp struct Sg { Pt s, t; Sg() { } Sg(Pt s, Pt t) : s(s), t(t) { } Sg(double a, double b, double c, double d) : s(a, b), t(c, d) { } }; ``` ## 点在线段上的判断 判断点$$C$$在线段$$AB$$上的两条依据: 1. $$\vec{CA}\cdot\vec{CB} = 0$$。 2. $$C$$在以$$AB$$为对角顶点的矩形内。 #### 示例代码 ```cpp bool PtOnSegment(Pt s, Pt t, Pt a) { return !det(a-s, a-t) && min(s.x, t.x) <= a.x && a.x <= max(s.x, t.x) && min(s.y, t.y) <= a.y && a.y <= max(s.y, t.y); } ``` ### 另一种方法 判断点$$C$$在$$AB$$为对角线定点的矩形内较麻烦,可以直接判断$$\vec{CA}\cdot\vec{CB}$$的符号来判断$$C$$在直线$$AB$$上是否在$$AB$$之间。 <center><img src="images/test.png" style="width:300px;" /></center> #### 示例代码 ```cpp bool PtOnSegment(Pt p, Pt a, Pt b) { return !sgn(det(p-a, b-a)) && sgn(dot(p-a, p-b)) <= 0; } ``` 把上例代码中的`<=`改成`==`就能实现不含线段端点的点在线段上的判断。 ## 点在直线上的判断 点在直线上的判断很简单只要把点在线段上的判断的步骤2去掉即可。 #### 示例代码 ```cpp bool PtOnLine(Pt p, Pt s, Pt t) { return !sgn(det(p-a, b-a)); } ``` ## 求点到直线的投影 <center><img src="images/point-line-projection.png" style="width:300px;" /></center> #### 示例代码 ```cpp Pt PtLineProj(Pt s, Pt t, Pt p) { double r = dot(p-s, t-s) / (t - s).norm(); return s + (t - s) * r; } ``` ## 判断直线关系 直线有相交和平行两种关系,靠叉乘能简单判断。 ```cpp bool parallel(Pt a, Pt b, Pt s, Pt t) { return !sgn(det(a-b, s-t)); } ``` ## 判断线段关系 线段有相交和不相交两种关系,通常按照以下步骤判断。 1. 快速排斥试验 2. 跨立试验 ### 快速排斥试验 设以线段$$P_1P_2$$为对角线的矩形为$$R$$,设以线段$$Q_1Q_2$$为对角线的矩形为$$T$$,如果$$R$$和$$T$$不相交,显然两线段不会相交。 ### 跨立试验 如果两线段相交,则两线段必然相互跨立对方。若$$P_1P_2$$跨立$$Q_1Q_2$$,则矢量$$\vec{Q_1P_1}$$和$$\vec{Q_1P_2}$$位于矢量$$\vec{Q_1Q_2}$$的两侧,即$$\vec{Q_1P_1} \times \vec{Q_1Q_2} \cdot \vec{Q_1Q_2} \times \vec{Q_1Q_2} < 0$$。上式可改写成$$\vec{Q_1P_1} \times \vec{Q_1Q_2} \cdot \vec{Q_1Q_2} \times \vec{Q_1P_2} > 0$$。当$$\vec{Q_1P_1} \times \vec{Q_1Q_2} = 0$$时,说明$$\vec{Q_1P_1}$$和$$\vec{Q_1Q_2}$$共线,但是因为已经通过快速排斥试验,所以$$P_1$$一定在线段$$Q_1Q_2$$上;同理,$$\vec{Q_1Q_2} \times \vec{Q_1P_2} = 0$$说明$$P_2$$一定在线段$$Q_1Q_2$$上。所以判断$$P_1P_2$$跨立$$Q_1Q_2$$的依据是:$$\vec{Q_1P_1} \times \vec{Q_1Q_2} \cdot \vec{Q_1Q_2} \ times vec{Q_1P_2} \geq 0$$。同理判断$$Q_1Q_2$$跨立$$P_1P_2$$的依据是:$$\vec{P_1Q_1} \times \vec{P_1P_2} \cdot \vec{P_1P_2} \times \vec{P_1Q_2} \geq 0$$。 <center><img src="images/线段相交判断.png" style="width:900px;" /></center> ## 求点到线段的距离 <!-- <center><img src="images/china.jpg" style="width:400px;" /></center> --> 求线段$$ab$$到点p最短距离的方法为: 根据点$$p$$到的投影点的位置进行判断的方法: 1. 判断线段$$pa$$和$$ab$$所成的夹角,如果是钝角,那么$$|pa|$$是点到线段的最短距离。 2. 判断线段$$pb$$和$$ab$$所成的夹角,如果是钝角,那么$$|pb|$$是点到线段的最短距离。 3. 线段$$pa$$和线段$$pb$$与$$ab$$所成的夹角都不为钝角,那么点$$p$$到线段$$ab$$的距离是点$$p$$到直线$$ab$$的距离,这个距离可以用面积法直接算出来。 #### 示例代码 ```cpp double PtSegmentDist(Pt a, Pt b, Pt p) { if (sgn(dot(p-a, b-a)) <= 0) return (p-a).norm(); if (sgn(dot(p-b, a-b)) <= 0) return (p-b).norm(); return fabs(det(a-p, b-p)) / (a-b).norm(); } ``` <file_sep>/CG/3d.md 三维计算几何 ============ ## 三维凸包 ```cpp #include <cstdio> #include <cstring> #include <algorithm> #include <vector> #include <iomanip> #include <iostream> #include <cmath> using namespace std; /* Macros */ /******************************************************************************/ #define nxt(i) ((i+1)%n) #define nxt2(i, x) ((i+1)%((x).size())) #define prv(i) ((i+(x).size()-1)%n) #define prv2(i, x) ((i+(x).size()-1)%((x).size())) #define sz(x) (int((x).size())) #define setpre(x) do{cout<<setprecision(x)<<setiosflags(ios::fixed);}while(0) /* Real number tools */ /******************************************************************************/ const double PI = acos(-1.0); const double eps = 1e-8; double mysqrt(double x) { return x <= 0.0 ? 0.0 : sqrt(x); } double sq(double x) { return x*x; } int sgn(double x) { return x < -eps ? -1 : x > eps ? 1 : 0; } /* 3d Point */ /******************************************************************************/ struct Pt3 { double x, y, z; Pt3() { } Pt3(double x, double y, double z) : x(x), y(y), z(z) { } }; typedef const Pt3 cPt3; typedef cPt3 & cPt3r; Pt3 operator + (cPt3r a, cPt3r b) { return Pt3(a.x+b.x, a.y+b.y, a.z+b.z); } Pt3 operator - (cPt3r a, cPt3r b) { return Pt3(a.x-b.x, a.y-b.y, a.z-b.z); } Pt3 operator * (cPt3r a, double A) { return Pt3(a.x*A, a.y*A, a.z*A); } Pt3 operator * (double A, cPt3r a) { return Pt3(a.x*A, a.y*A, a.z*A); } Pt3 operator / (cPt3r a, double A) { return Pt3(a.x/A, a.y/A, a.z/A); } bool operator == (cPt3r a, cPt3r b) { return !sgn(a.x-b.x) && !sgn(a.y-b.y) && !sgn(a.z-b.z); } istream& operator >> (istream& sm, Pt3 &pt) { sm >> pt.x >> pt.y >> pt.z; return sm; } ostream & operator << (ostream& sm, cPt3r pt) { sm << "(" << pt.x << ", " << pt.y << ", " << pt.z << ")"; return sm; } double len(cPt3r p) { return mysqrt(sq(p.x) + sq(p.y) + sq(p.z)); } double dist(cPt3r a, cPt3r b) { return len(a-b); } Pt3 unit(cPt3r p) { return p / len(p); } Pt3 det(cPt3r a, cPt3r b) { return Pt3(a.y*b.z-a.z*b.y, a.z*b.x-a.x*b.z, a.x*b.y-a.y*b.x); } double dot(cPt3r a, cPt3r b) { return a.x*b.x + a.y*b.y + a.z*b.z; } double mix(cPt3r a, cPt3r b, cPt3r c) { return dot(a, det(b, c)); } /* 3d Line & Segment */ /******************************************************************************/ struct Ln3 { Pt3 a, b; Ln3() { } Ln3(cPt3r a, cPt3r b) : a(a), b(b) { } }; typedef const Ln3 cLn3; typedef cLn3 & cLn3r; bool ptonln(cPt3r a, cPt3r b, cPt3r c) { return sgn(len(det(a-b, b-c))) <= 0; } /* 3d Plane */ /******************************************************************************/ struct Pl { Pt3 a, b, c; Pl() { } Pl(cPt3r a, cPt3r b, cPt3r c) : a(a), b(b), c(c) { } }; typedef const Pl cPl; typedef cPl & cPlr; Pt3 nvec(cPlr pl) { return det(pl.a-pl.b, pl.b-pl.c); } /* Solution */ /******************************************************************************/ bool cmp(cPt3r a, cPt3r b) { if (sgn(a.x-b.x)) return sgn(a.x-b.x) < 0; if (sgn(a.y-b.y)) return sgn(a.y-b.y) < 0; if (sgn(a.z-b.z)) return sgn(a.z-b.z) < 0; return false; } struct Face { int a, b, c; Face() { } Face(int a, int b, int c) : a(a), b(b), c(c) { } }; void convex3d(vector<Pt3> &p, vector<Pl> &out) { sort(p.begin(), p.end(), cmp); p.erase(unique(p.begin(), p.end()), p.end()); random_shuffle(p.begin(), p.end()); vector<Face> face; for (int i = 2; i < sz(p); ++i) { if (ptonln(p[0], p[1], p[i])) continue; swap(p[i], p[2]); for (int j = i + 1; j < sz(p); ++j) if (sgn(mix(p[1]-p[0], p[2]-p[1], p[j]-p[0])) != 0) { swap(p[j], p[3]); face.push_back(Face(0, 1, 2)); face.push_back(Face(0, 2, 1)); goto found; } } found: vector<vector<int> > mark(sz(p), vector<int>(sz(p), 0)); for (int v = 3; v < sz(p); ++v) { vector<Face> tmp; for (int i = 0; i < sz(face); ++i) { int a = face[i].a, b = face[i].b, c = face[i].c; if (sgn(mix(p[a]-p[v], p[b]-p[v], p[c]-p[v])) < 0) { mark[a][b] = mark[b][a] = v; mark[b][c] = mark[c][b] = v; mark[c][a] = mark[a][c] = v; }else{ tmp.push_back(face[i]); } } face = tmp; for (int i = 0; i < sz(tmp); ++i) { int a = face[i].a, b = face[i].b, c = face[i].c; if (mark[a][b] == v) face.push_back(Face(b, a, v)); if (mark[b][c] == v) face.push_back(Face(c, b, v)); if (mark[c][a] == v) face.push_back(Face(a, c, v)); } } out.clear(); for (int i = 0; i < sz(face); ++i) out.push_back(Pl(p[face[i].a], p[face[i].b], p[face[i].c])); } vector<Pt3> p; vector<Pl> out; int main() { int n; cin >> n; for (int i = 0; i < n; ++i) { Pt3 pt; cin >> pt; p.push_back(pt); } convex3d(p, out); double area = 0.0; for (int i = 0; i < sz(out); ++i) area += len(det(out[i].a-out[i].b, out[i].b-out[i].c)); setpre(3); cout << area / 2.0 << "\n"; return 0; } ``` <file_sep>/CG/circle.md 圆 == ## 圆与线求交 将线段AB写成参数方程P=A+t(B-A),带入圆的方程,得到一个一元二次方程。解出t就可以求得线段所在直线与圆的交点。如果0<=t<=1则说明点在线段上。 ```cpp void circle_cross_line(Pt a, Pt b, Pt o, double r, Pt ret[], int &num) { double ox = o.x, oy = o.y, ax = a.x, ay = a.y, bx = b.x, by = b.y; double dx = bx-ax, dy = by-ay; double A = dx*dx + dy*dy; double B = 2*dx*(ax-ox) + 2*dy*(ay-oy); double C = sqr(ax-ox) + sqr(ay-oy) - sqr(r); double delta = B*B - 4*A*C; num = 0; if (sgn(delta) >= 0) { double t1 = (-B - Sqrt(delta)) / (2*A); double t2 = (-B + Sqrt(delta)) / (2*A); if (sgn(t1-1) <= 0 && sgn(t1) >= 0) ret[num++] = Pt(ax + t1*dx, ay + t1*dy); if (sgn(t2-1) <= 0 && sgn(t2) >= 0) ret[num++] = Pt(ax + t2*dx, ay + t2*dy); } } ``` ## 圆与圆求交 ```cpp // 计算圆a和圆b的交点,注意要先判断两圆相交 void circle_circle_cross(Pt ap, double ar, Pt bp, double br, Pt p[]) { double d = (ap - bp).norm(); double cost = (ar*ar + d*d - br*br) / (2*ar*d); double sint = sqrt(1.0 - cost*cost); Pt v = (bp - ap) / (bp - ap).norm() * ar; p[0] = ap + rotate(v, cost, -sint); p[1] = ap + rotate(v, cost, sint); } ``` ## 圆与多边形交 ## 圆的面积并 <file_sep>/CG/README.md 计算几何 ======== 计算几何在ACM/ICPC竞赛的题目中属于较容易的内容。但计算几何往往代码量多,有时需要按照多种情况进行讨论,还有考虑到复杂的浮点数精度问题,所以常常容易卡题。所以计算几何对平时模板的积累就非常重要。 * [浮点数相关的陷阱](float-point-pitfall.md) * [向量](vector.md) * [线段](segment.md) * [三角形](triangle.md) * [多边形](polygon.md) * [凸包](convex.md) * [半平面](halfplane.md) * [圆](circle.md) * [三维计算几何](3d.md) <file_sep>/_book/CG/tmp.cpp bool PtOnSegment(Pt s, Pt t, Pt a) { return !det(a-s, a-t) && min(s.x, t.x) <= a.x && a.x <= max(s.x, t.x) && min(s.y, t.y) <= a.y && a.y <= max(s.y, t.y); }
e47cc90694434eb374830f4753c8dc0beddc143d
[ "Markdown", "HTML", "C++" ]
14
Markdown
LinFanChing/book-test
392da3ac674feffa04f3f5fd38292d9775954987
05490964b97bfdecefb2b6bac55270ef0fd7d9c7
refs/heads/main
<repo_name>Nehal1207/GamersBlog<file_sep>/middleware/index.js var game =require("../models/game"); var Comment =require("../models/comment"); var middlewareObj = {}; middlewareObj.checkgameOwnership = function (req, res, next) { if (req.isAuthenticated()) { game.findById(req.params.id, function(err, foundgame) { if (err || !foundgame) { req.flash("error","post not found."); res.redirect("/games"); } else { //does the user own the game? if (foundgame.author.id.equals(req.user._id) || req.user.isAdmin) { next(); } else { req.flash("error","You do not have permission to this post."); res.redirect("back"); } } }) } else { req.flash("error","You need to be logged in to that."); res.redirect("back"); } } middlewareObj.checkCommentOwnership = function (req, res, next) { if (req.isAuthenticated()) { Comment.findById(req.params.comment_id, function(err, foundComment) { if (err || !foundComment) { req.flash("error","Comment not found."); res.redirect("/games"); } else { game.findById(req.params.id, function(err, foundgame) { if (err || !foundgame) { req.flash("error","post not found."); res.redirect("/games"); } else { //does the user own the comment? if (foundComment.author.id.equals(req.user._id) || req.user.isAdmin) { next(); } else { req.flash("error","You do not have permission to this comment."); res.redirect("back"); } } }) } }) } else { req.flash("error","You need to be logged in to do that."); res.redirect("back"); } } //middleware middlewareObj.isLoggedIn = function (req, res, next) { if (req.isAuthenticated()) { return next(); } req.flash("error","You need to be logged in to do that"); res.redirect("/login"); } module.exports = middlewareObj;<file_sep>/routes/games.js var express = require("express"); var router = express.Router(); var game = require("../models/game"); var middleware = require("../middleware") var multer = require('multer'); var storage = multer.diskStorage({ filename: function(req, file, callback) { callback(null, Date.now() + file.originalname); } }); var imageFilter = function (req, file, cb) { if (!file.originalname.match(/\.(jpg|jpeg|png|gif)$/i)) { return cb(new Error('Only image files are allowed!'), false); } cb(null, true); }; var upload = multer({ storage: storage, fileFilter: imageFilter}) var cloudinary = require('cloudinary'); cloudinary.config({ cloud_name: 'cloudinaryneon', api_key: process.env.CLOUDINARY_API_KEY, api_secret: process.env.CLOUDINARY_API_SECRET }); function escapeRegex(text) { return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); }; router.get("/", function(req, res) { if(req.query.search) { const regex = new RegExp(escapeRegex(req.query.search), 'gi'); //Get all games fro the DB game.find({"name": regex}, function(err, allgames) { if (err) { console.log(err); } else { res.render("games/index", { games: allgames }); } }); } else { //Get all games fro the DB game.find({}, function(err, allgames) { if (err) { console.log(err); } else { res.render("games/index", { games: allgames }); } }); } }); router.post("/", middleware.isLoggedIn, upload.single('image'), function(req, res) { cloudinary.uploader.upload(req.file.path, function(result) { req.body.game.image = result.secure_url; req.body.game.author = { id: req.user._id, username: req.user.username } game.create(req.body.game, function(err, game) { if (err || !game) { req.flash('error', err.message); return res.redirect('/games'); } res.redirect('/games/' + game.id); }); }); }); router.get("/new",middleware.isLoggedIn, function(req, res) { res.render("games/new"); }); router.get("/:id", function(req, res) { game.findById(req.params.id).populate("comments").exec(function(err, foundgame) { if (err || !foundgame) { req.flash("error","Something went wrong."); res.redirect("/games"); } else { res.render("games/show", { game: foundgame }); } }); }); router.get("/:id/edit", middleware.checkgameOwnership, function(req, res) { game.findById(req.params.id, function(err, foundgame ) { if (err || !foundgame) { req.flash("error","Something went wrong."); res.redirect("/games"); } else { res.render("games/edit", { game: foundgame }); } }); }); router.put("/:id", middleware.checkgameOwnership, upload.single('image'), function(req, res) { if(req.file){ cloudinary.uploader.upload(req.file.path, function(result) { req.body.game.image = result.secure_url; req.body.game.body = req.sanitize(req.body.game.body); game.findByIdAndUpdate(req.params.id, req.body.game, function(err, updatedgame) { if (err || !updatedgame) { res.redirect("/games"); } else { req.flash("success","post successfully updated."); res.redirect("/games/" + req.params.id); } }); }); } else { req.body.game.body = req.sanitize(req.body.game.body); game.findByIdAndUpdate(req.params.id, req.body.game, function(err, updatedgame) { if (err || !updatedgame) { res.redirect("/games"); } else { req.flash("success","post successfully updated."); res.redirect("/games/" + req.params.id); } }); } }); router.delete("/:id", middleware.checkgameOwnership, function(req, res) { game.findByIdAndRemove(req.params.id, function(err) { if (err) { res.redirect("/games"); } else { req.flash("success","post successfully deleted."); res.redirect("/games"); } }); }); module.exports = router; <file_sep>/routes/comments.js var express = require("express"); var router = express.Router({ mergeParams: true }); var Comment = require("../models/comment"); var game = require("../models/game"); var middleware = require("../middleware") var moment = require("moment") router.get("/new", middleware.isLoggedIn, function (req, res) { game.findById(req.params.id, function(err, game) { if (err || !game) { req.flash("error","Something went wrong."); return res.redirect("/games"); } else { res.render("comments/new", { game: game }); } }); }); router.post("/", middleware.isLoggedIn, function(req, res) { game.findById(req.params.id, function(err, foundgame) { if (err || !foundgame) { req.flash("error","Something went wrong."); return res.redirect("/games"); } else { Comment.create(req.body.comment, function(err, comment) { if (err) { console.log(err); } else { comment.author.id = req.user._id; comment.author.username = req.user.username; comment.author.dateAdded = moment(Date.now()).format("DD/MM/YYYY"); comment.save(); foundgame.comments.push(comment._id); foundgame.save(); req.flash("success","Comment successfully added."); res.redirect('/games/' + foundgame._id); } }); } }); }); //Comment edit route router.get("/:comment_id/edit", middleware.checkCommentOwnership, function (req, res) { game.findById(req.params.id, function(err, foundgame) { if(err || !foundgame){ req.flash("error", "Error has occured") return res.redirect("/games"); } Comment.findById(req.params.comment_id, function (err, foundComment) { if (err) { req.flash("error","Something went wrong."); res.redirect("/games"); } else { res.render("comments/edit", {game_id: req.params.id, comment: foundComment}); } }); }) }); //comment update route router.put("/:comment_id", function(req, res) { //find comment ID in DB Comment.findByIdAndUpdate(req.params.comment_id, req.body.comment, function(err, updatedComment) { if (err) { req.flash("error","Something went wrong."); res.redirect("back"); } else { req.flash("success","Comment successfully updated."); res.redirect("/games/" + req.params.id); } }); }); //comment destroy route router.delete("/:comment_id", middleware.checkCommentOwnership, function(req, res){ //find Comment ID in DB Comment.findByIdAndRemove(req.params.comment_id, function(err) { if (err) { req.flash("error","Something went wrong."); res.redirect("/games"); } else { req.flash("success","Comment deleted."); res.redirect("/games/" + req.params.id); } }); }); module.exports = router;
d7483e1356787b0407d82b95a67673487af565e2
[ "JavaScript" ]
3
JavaScript
Nehal1207/GamersBlog
82f3764321404f7588945df33206c10f7c1c5722
02527cf5c6b6db5ccf3a8297df11f08c1607fd8b
refs/heads/master
<repo_name>dusekdan/GodAll-Spigot<file_sep>/src/main/java/com/danieldusek/godall/Constants.java package com.danieldusek.godall; public class Constants { final public static String ON_TOGGLE = "on"; final public static String OFF_TOGGLE = "off"; final public static String RELOAD = "reload"; final public static String MESSAGE_DISABLED = "God mode disabled."; final public static String MESSAGE_ENABLED = "God mode enabled."; final public static String MESSAGE_USE = "Use /godall on, or /godall off"; final public static String MESSAGE_NO_PERMISSIONS = "You don't have permission to use /godall command."; final public static String RELOAD_USE = "Use /godall reload to reload configuration changes from config."; final public static String RELOAD_NO_PERMISSIONS = "You don't have permission to use /godall reload command."; final public static String RELOAD_PERFORMED = "Successfully reloaded configuration for GodAll plugin."; final public static String USE_PERMISSION_NODE = "godall.use"; } <file_sep>/src/main/java/com/danieldusek/godall/commands/GodAllCommand.java package com.danieldusek.godall.commands; import com.danieldusek.godall.Constants; import com.danieldusek.godall.GodAll; import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; public class GodAllCommand implements CommandExecutor { final private GodAll i; public GodAllCommand(Plugin plugin) { this.i = (GodAll) plugin; } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if (!sender.hasPermission(Constants.USE_PERMISSION_NODE)) { sender.sendMessage(Constants.MESSAGE_NO_PERMISSIONS); return true; } if (args.length != 1) { sender.sendMessage(Constants.MESSAGE_USE); return true; } if (args[0].equalsIgnoreCase(Constants.RELOAD)) { reloadCommand(sender); return true; } for (Player player : Bukkit.getOnlinePlayers()) { if (args[0].equalsIgnoreCase(Constants.ON_TOGGLE)) { this.i.godEnabled = true; player.setInvulnerable(true); player.sendMessage(Constants.MESSAGE_ENABLED); } else if (args[0].equalsIgnoreCase(Constants.OFF_TOGGLE)) { this.i.godEnabled = false; player.setInvulnerable(false); player.sendMessage(Constants.MESSAGE_DISABLED); } else { return false; } } return true; } private void reloadCommand(CommandSender sender) { this.i.reloadConfig(); sender.sendMessage(Constants.RELOAD_PERFORMED); } }
9c169400eedcd29e07b11f8f22989c0dbea50825
[ "Java" ]
2
Java
dusekdan/GodAll-Spigot
2d07878067e3edcc8dda529aad3ffa4e34aff237
c551dae38b3968058dce1b0cef62c78984b3e95f
refs/heads/master
<repo_name>yunnuoyang/hzitsummerexperience<file_sep>/java8/src/main/java/test1/PrintDoubleArray.java package test1; import org.junit.Test; /** * 给定一个空的int类型的二维数组array[n][m]。 * 按下面的填充规则, 请编写一个函数将此二维数组填满并打印出来. * 输入描述: * 输入的包括两个正整数,表示二维数组的大小n,m(1 <= n, m <= 10)。 * 输出描述: * 打印结果,每行行末无空格。 * 示例1 * * 输入 * 复制 * 4 4 * 输出 * 复制 * 1 2 4 7 1+0 1+1 1+2 1+2+4 1,2,3 2*i-1 2,3,4 * 3 5 8 11 2,3,3 3,4,4 * 6 9 12 14 3,3,2 4,4,3 * 10 13 15 16 3,2,1 4,3,2 */ public class PrintDoubleArray { @Test public void test(){ } public int[][] printDoubleArray(int linelenth,int highLenth){ int [][] arr=new int[highLenth][linelenth]; int start=1; for (int i = 0; i <linelenth ; i++) { } return null; } } <file_sep>/ssh/src/com/struts/dao/UserDao.java package com.struts.dao; import com.struts.pojo.Chairman; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; public class UserDao { private SessionFactory sessionFactory; public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } public void save(Chairman chairman){ Session session = sessionFactory.openSession(); Transaction tran = session.beginTransaction(); session.save(chairman); tran.commit(); session.close(); } } <file_sep>/baidudisk/src/main/java/com/disk/intercepter/utils/FileUtils.java package com.disk.intercepter.utils; import java.io.*; import java.security.MessageDigest; import java.text.SimpleDateFormat; import java.util.Date; public class FileUtils { private static SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS"); private static SimpleDateFormat formatDate = new SimpleDateFormat("yyyy年MM月dd日"); public static String getUnqiueByName(String filename){ if(filename==null || filename.trim().length()==0){ return ""; } return format.format(new Date())+filename.substring(filename.lastIndexOf(".")); } public static String loadEmailContent(String fileName) { try { fileName = fileName.startsWith("/")?fileName:"/"+fileName; InputStreamReader isr = new InputStreamReader(MailSend.class.getResourceAsStream(fileName),"utf-8"); BufferedReader br = new BufferedReader(isr); StringBuilder sb = new StringBuilder(); String s; while ((s=br.readLine())!=null) { //通过读取当前的环境变量,得到当前系统的换行符 sb.append(s).append("<br>"); // sb.append(s).append(System.getProperties().getProperty("line.separator")); } br.close(); String content = replace(sb.toString()); System.out.println(content); return content; } catch (IOException e) { e.printStackTrace(); } return ""; } private static String replace(String content){ String date = formatDate.format(new Date()); return content.replace(",date,", date); } /** * 计算文件的MD5 * @param filename * @return * @throws Exception */ private static byte[] createChecksum(String filename) throws Exception { InputStream fis = new FileInputStream(filename); BufferedInputStream bis = new BufferedInputStream(fis); MessageDigest complete = MessageDigest.getInstance("MD5"); byte[] buffer; int size = fis.available(); //如果文件小于20M if(size>=0 && size<20480){ buffer=new byte[size]; fis.read(buffer); // buffer = bis.readAllBytes(); complete.update(buffer);//使用指定的字节数组更新摘要 }else { buffer = new byte[10240]; int numRead; do { numRead = bis.read(buffer); if (numRead > 0) { complete.update(buffer, 0, numRead);//使用指定的字节数组更新摘要 } } while (numRead != -1); } fis.close(); return complete.digest(); } public static String getMD5(File file) throws Exception { return getMD5Checksum(file.getAbsolutePath()); } public static String getMD5Checksum(String filename) throws Exception { byte[] b = createChecksum(filename); String result = ""; for (int i=0; i < b.length; i++) { result += Integer.toString( ( b[i] & 0xff ) + 0x100, 16).substring( 1 ); } return result; } } <file_sep>/spring/src/main/java/com/aop/MyProxy.java package com.aop; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.sql.Date; public class MyProxy implements InvocationHandler { private Object obj; MyProxy(Object obj){ this.obj=obj; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("===售票时间===="+new Date(System.currentTimeMillis())+"======"); proxy=this.obj; method.invoke(proxy,args); return proxy; } public Object getObj(){ return Proxy.newProxyInstance(this.obj.getClass().getClassLoader(),this.obj.getClass().getInterfaces(),this); } } <file_sep>/mybatis01/src/test/java/TestSqlSession.java import com.mybatis.mapper.IStudentMapper; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import java.util.Arrays; import java.util.HashMap; import java.util.Map; public class TestSqlSession { static SqlSessionFactoryBuilder sfb=new SqlSessionFactoryBuilder(); static SqlSessionFactory build = sfb.build(TestSqlSession.class.getClass().getResourceAsStream("/mybatis-config.xml")); static SqlSession sqlSession = build.openSession(); public static void main(String[] args) { // testInitParam(); // testMap(); testSelectObj(); } public static void testSelectObj(){ IStudentMapper mapper = sqlSession.getMapper(IStudentMapper.class); Object[] integer = mapper.selectObj(); System.out.println(Arrays.toString(integer)); } /** * 生成的sql:select count(*) from student where sno=2 */ public static void testMap(){ IStudentMapper mapper = sqlSession.getMapper(IStudentMapper.class); Map map=new HashMap(); map.put("sno",2); Integer integer = mapper.count$(map); System.out.println(integer); } /** * 生成的sql:select count(*) from student where sno=? */ public static void testInitParam(){ IStudentMapper mapper = sqlSession.getMapper(IStudentMapper.class); Integer count = mapper.count2(1); System.out.println(count); } } <file_sep>/spring/src/main/java/com/aop/TryProxy.java package com.aop; import org.junit.Test; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; public class TryProxy implements InvocationHandler { private Object object; @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { method.invoke(proxy, args); return proxy; } public Object getNewInstance(Object object,String methodName,Object... args){ try { return this.invoke(object,object.getClass().getDeclaredMethod(methodName),args); } catch (Throwable throwable) { throwable.printStackTrace(); } return null; } @Test public void test(){ ISaleTicket iSaleTicket=new SaleTicket(); TryProxy tryProxy = new TryProxy(); ISaleTicket sale = (ISaleTicket) getNewInstance(iSaleTicket, "sale", null); sale.sale(); } } <file_sep>/hibernate01/src/main/java/com/hibernate/test/TestEhcache.java package com.hibernate.test; import com.hibernate.pojo.Detail; import com.hibernate.pojo.People; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.query.Query; import org.junit.Test; import java.util.List; public class TestEhcache { @Test public void test1(){ Session session = HibernateUtils.getSession(); People people = session.get(People.class, 38); System.out.println(people.getName()+""+people.getYear()); session.close(); Session session1 = HibernateUtils.getSession(); People people1 = session1.get(People.class, 38); System.out.println(people1.getName()+""+people1.getYear()); session.close(); } @Test public void test2(){ Session session=HibernateUtils.getSession(); Detail detail = session.get(Detail.class, 2); System.out.println(detail.getEmail()+""+detail.getEmail()); session.close(); Session session1=HibernateUtils.getSession(); Detail detail1 = session1.get(Detail.class, 2); System.out.println(detail1.getEmail()+""+detail1.getEmail()); session.close(); } @Test public void testQueryCache(){ Session session=HibernateUtils.getSession(); Query<Detail> query = session.createQuery("from Detail", Detail.class); query.setCacheable(true); query.list() .forEach(detail -> System.out.println(detail.getEmail()+""+detail.getEmail())); session.close(); Session session1=HibernateUtils.getSession(); Query<Detail> query1 = session1.createQuery("from Detail", Detail.class); query1.setCacheable(true); query1.list() .forEach(detail -> System.out.println(detail.getEmail()+""+detail.getEmail())); session1.close(); } } <file_sep>/java8/src/main/java/com/b/linknode/SingleList.java package com.b.linknode; import org.junit.Test; public class SingleList<T> { private SNode head; public void add(T t){ SNode<T> curNode=new SNode<T>(t); if(head==null){ head=curNode; }else { SNode<T> temp=head;//临时存储节点 while(temp.next!=null){ temp=temp.next;//将最后一个节点迭代出来 } temp.next=curNode; } } @Test public void test(){ SingleList<String> list=new SingleList(); list.add("234"); list.add("abc"); list.add("kls"); System.out.println(list); } private class SNode<T>{ SNode next; T value; public SNode(T value) { this.value = value; } } } <file_sep>/spring/src/main/java/com/spring/aop/aspectj/AopService.java package com.spring.aop.aspectj; /** * 测试aop的service */ public class AopService { public void post(String word){ System.out.println("===========AopService==========="); } } <file_sep>/hibernate01/src/main/java/com/hibernate/test/HibernateTest.java package com.hibernate.test; import com.hibernate.pojo.GoodsEntity; import com.hibernate.pojo.People; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.boot.Metadata; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import org.hibernate.tool.hbm2ddl.SchemaExport; import org.hibernate.tool.schema.TargetType; import org.junit.Test; import java.util.EnumSet; import java.util.HashSet; import java.util.Set; public class HibernateTest { public static void main(String[] args) { //5.2以前的使用正向工程 // Configuration cfg = new Configuration().configure(); // SchemaExport export = new SchemaExport(cfg); // export.create(true, true); //5.2加载配置文件正向工程 // ServiceRegistry registry = new StandardServiceRegistryBuilder().configure().build(); // Metadata metadata = new MetadataSources(registry).buildMetadata(); // SchemaExport export = new SchemaExport(); // export.create(EnumSet.of(TargetType.DATABASE),metadata); // getAndLoad(); } @Test public void add(){ Configuration configuration=new Configuration().configure(); SessionFactory sessionFactory = configuration.buildSessionFactory(); Session session = sessionFactory.openSession(); Transaction transaction = session.beginTransaction(); People people = new People(); people.setName("小明"); people.setYear(22); session.save(people); transaction.commit(); } @Test public void del(){ Configuration configuration=new Configuration().configure(); SessionFactory sessionFactory = configuration.buildSessionFactory(); Session session = sessionFactory.openSession(); Transaction transaction = session.beginTransaction(); People people = new People(); session.delete(people); transaction.commit(); session.close(); } @Test public void getAndLoad(){ Configuration configuration=new Configuration().configure(); SessionFactory sessionFactory = configuration.buildSessionFactory(); Session session = sessionFactory.openSession(); Transaction transaction = session.beginTransaction(); GoodsEntity goodsEntity = session.load(GoodsEntity.class, 6l); System.out.println("***************"); System.out.println("===="+goodsEntity.getGoodsName()); session.close(); } @Test public void moneyToOneSave(){ Configuration configuration=new Configuration().configure(); SessionFactory sessionFactory = configuration.buildSessionFactory(); Session session = sessionFactory.openSession(); Transaction transaction = session.beginTransaction(); People people=new People(); people.setName("小王"); people.setYear(20l); GoodsEntity goodsEntity=new GoodsEntity(); goodsEntity.setGoodsName("瓜子"); goodsEntity.setGoodsPrice(33); goodsEntity.setPeople(people); Set<GoodsEntity> entities = people.getGoodsEntities(); entities.add(goodsEntity); people.setGoodsEntities(entities); // session.save(people); session.save(goodsEntity); transaction.commit(); session.close(); } @Test public void oneToMonetSearch(){ Configuration configuration=new Configuration().configure(); SessionFactory sessionFactory = configuration.buildSessionFactory(); Session session = sessionFactory.openSession(); Transaction tran = session.beginTransaction(); // People people = session.load(People.class, 14); // System.out.println("***************"); // System.out.println("===="+people.getName()); // for(GoodsEntity goodsEntity:people.getGoodsEntities()){ // System.out.println(goodsEntity.getGoodsName()); // } GoodsEntity goodsEntity=new GoodsEntity(); goodsEntity.setGoodsName("电冰箱"); goodsEntity.setGoodsPrice(2000); GoodsEntity goodsEntity1=new GoodsEntity(); goodsEntity1.setGoodsName("电视机"); goodsEntity1.setGoodsPrice(2000); People people=new People(); people.setName("奉先"); people.setYear(40l); Set<GoodsEntity> goodsEntities = people.getGoodsEntities(); goodsEntities.add(goodsEntity); goodsEntities.add(goodsEntity1); people.setGoodsEntities(goodsEntities); session.save(people); tran.commit(); session.close(); } } <file_sep>/mybatis01/src/test/java/Cache.java import com.mybatis.mapper.IStudentMapper; import com.mybatis.pojo.Student; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import java.util.List; public class Cache { static SqlSessionFactoryBuilder sfb=new SqlSessionFactoryBuilder(); static SqlSessionFactory build = sfb.build(TestSqlSession2.class.getClass().getResourceAsStream("/mybatis-config.xml")); static SqlSession sqlSession = build.openSession(); // Cache Hit Ratio [com.mybatis.mapper.IStudentMapper]: 0.5 public static void main(String[] args) { t1(); SqlSession sqlSession = build.openSession(); IStudentMapper studentMapper = sqlSession.getMapper(IStudentMapper.class); List<Student> students = studentMapper.querryQritirea(null); students.forEach(s->{ System.out.println(s.getSname()); }); } private static void t1(){ IStudentMapper studentMapper = sqlSession.getMapper(IStudentMapper.class); List<Student> students = studentMapper.querryQritirea(null); students.forEach(s->{ System.out.println(s.getSname()); }); sqlSession.close(); } } <file_sep>/java8/src/main/java/test1/Test1.java package test1; import org.junit.Test; import java.util.ArrayList; import java.util.Stack; public class Test1 { public void test1(){ } /** * 请实现一个函数,将一个字符串中的每个空格替换成“%20”。 * 例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。 */ @Test public void test2(){ StringBuffer str=new StringBuffer(); str.append("a b c"); String a = a(str); System.out.println(a); } public String a(StringBuffer str){ String s1 = str.toString(); //记录串的长度 int length = s1.length(); char[] chars = s1.toCharArray(); StringBuffer sbf=new StringBuffer(); for (int i = 0; i <length ; i++) { String s = String.valueOf(chars[i]); if(s.trim().length()==0){ sbf.append("%20"); continue; } sbf.append(chars[i]); } return sbf.toString(); } /*** * 在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序 * 每一列都按照从上到下递增的顺序排序。 * 请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。 */ @Test public void test3(){ int a = 0; int[][] arr = {{6,1,2},{3,5,4},{9,8,7},{10,11,12}}; boolean b = find(2, arr); System.out.println(b); } public boolean find(int target, int [][] array) { //求出一位数组的长度 int length = array[0].length; //二位数组的长度 int alllen = array.length; //i是外层,j是内层 int temp=0; //将所有的二维数组的值放入一个一维数组 int a[][]=new int[alllen][length]; for (int i = 0; i <alllen ; i++) { //对横行进行排序 sort(array[i],array[i].length); } for (int i = 0; i <alllen-1 ; i++) { int t=0; for (int j = 0; j <length ; j++) { if(array[i][j]>array[i+1][j]){ t=array[i][j]; array[i][j]=array[i+1][j]; array[i+1][j]=t; } } } for (int i = 0; i <alllen ; i++) { for (int j = 0; j <length ; j++) { if(array[i][j]==target){ return true; } } } return false; } /** * 冒泡排序 * @param arr * @param n */ public void sort(int arr[],int n){ for (int i = 0; i < n; ++i) { // 提前退出冒泡循环的标志位,即一次比较中没有交换任何元素,这个数组就已经是有序的了 boolean flag = false; for (int j = 0; j < n - i - 1; ++j) { //此处你可能会疑问的j<n-i-1,因为冒泡是把每轮循环中较大的数飘到后面, // 数组下标又是从0开始的,i下标后面已经排序的个数就得多减1,总结就是i增多少,j的循环位置减多少 if (arr[j] > arr[j + 1]) { //即这两个相邻的数是逆序的,交换 int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; flag = true; } } if (!flag) break;//没有数据交换,数组已经有序,退出排序 } } @Test public void print(){ ListNode listNode1=new ListNode(3); ListNode listNode2 = new ListNode(0); listNode1.next=listNode2; listNode2.next=new ListNode(5); printListFromTailToHead(listNode1); // intListFromTailToHead(listNode1); } /** * 输入一个链表,按链表值从尾到头的顺序返回一个ArrayList * @param listNode * @return */ public ArrayList<Integer> printListFromTailToHead(ListNode listNode) { int[] a=new int[30]; int index=0; ArrayList<Integer> arrayList=null; while(listNode!=null){ a[index]=listNode.val; listNode= listNode.next; index++; } arrayList=new ArrayList(); for (int i = index-1; i >=0 ; i--) { arrayList.add(a[i]); } return arrayList; } class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } } public ArrayList<Integer> intListFromTailToHead(ListNode listNode) { ArrayList<Integer> arrayList=new ArrayList<>(); String[] sbf=new String[1024]; int index=0; while(listNode!=null){ int val = listNode.val; if(val!=0){ sbf[index]=String.valueOf(val); }else if(val==0){ sbf[index]="0"; index++; continue; } listNode= listNode.next; index++; } for (int i = index; i >-0 ; i--) { arrayList.add(Integer.parseInt(sbf[i])); } return arrayList; } public ArrayList<Integer> prtListFromTailToHead(ListNode listNode) { ArrayList<Integer> arrayList = null; Stack<Integer> stack = new Stack(); while (listNode != null) { stack.push(listNode.val); listNode = listNode.next; } arrayList = new ArrayList(); while (!stack.empty()) { arrayList.add(stack.pop()); } return arrayList; } /** * 递归版本 */ ArrayList<Integer> arrayList=new ArrayList<Integer>(); public ArrayList<Integer> rintListFromTailToHead(ListNode listNode) { if(listNode!=null){ this.rintListFromTailToHead(listNode.next); arrayList.add(listNode.val); } return arrayList; } } <file_sep>/mybatis01/src/main/java/com/mybatis/mapper/IStudentMapperDen.java package com.mybatis.mapper; import com.mybatis.pojo.Student; import org.apache.ibatis.annotations.SelectProvider; public interface IStudentMapperDen { @SelectProvider(method = "CritieriaSQL",type = CritieriaSQL.class) Student getStudent(Student student); } <file_sep>/spring/src/main/java/com/spring/aop/aspectj/AdviceAfterReturning.java package com.spring.aop.aspectj; import org.springframework.aop.AfterReturningAdvice; import java.lang.reflect.Method; import java.sql.Date; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.logging.Logger; /** * 后置增强 */ public class AdviceAfterReturning implements AfterReturningAdvice { private Logger logger=Logger.getLogger("AdviceAfterReturning"); private static DateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 hh时mm分ss秒"); @Override public void afterReturning(Object result, Method method, Object[] arg2, Object arg3) throws Throwable { System.out.println("\n后置通知开始:"); logger.info("[后置通知:系统日志][" + sdf.format(new Date(System.currentTimeMillis())) + "]" + "\n类名:"+arg3.getClass() + "\n方法名:"+method.getName() + "\n参数:("+ Arrays.toString(arg2) + "\n方法返回结果:"+result + ")====结束\n"); System.out.println("*************************后置通知结束****************************"); } } <file_sep>/spring/src/main/java/com/spring/aop/BeforeAop.java package com.spring.aop; import org.springframework.aop.BeforeAdvice; import org.springframework.aop.MethodBeforeAdvice; import java.lang.reflect.Method; import java.sql.Date; import java.util.Arrays; import java.util.logging.Logger; public class BeforeAop implements MethodBeforeAdvice { private Logger logger=Logger.getLogger("BeforeAop"); @Override public void before(Method method, Object[] objects, Object o) throws Throwable { System.out.println(method.getName()+"前置增强。。。。。。。。。。。"); logger.info("当前系统时间"+new Date(System.currentTimeMillis())+""+ Arrays.toString(objects)+"所在类"+o.getClass().getName()); } } <file_sep>/spring/src/main/java/com/spring/day1/pojo/Component.java package com.spring.day1.pojo; import java.util.*; /** * 测试spring的集合注入 */ public class Component { private List list; private Set set; private Map map; private Properties properties; String [] array; public void setList(List list) { this.list = list; } public void setSet(Set set) { this.set = set; } public void setMap(Map map) { this.map = map; } public void setProperties(Properties properties) { this.properties = properties; } public void setArray(String[] array) { this.array = array; } @Override public String toString() { return "Component{" + "list=" + list + ", set=" + set + ", map=" + map + ", properties=" + properties + ", array=" + Arrays.toString(array) + '}'; } } <file_sep>/baidudisk/src/main/resources/param.properties init=join @PropertySource("classpath:param.properties")<file_sep>/hibernate01/src/main/java/com/hibernate/pojo/People.java package com.hibernate.pojo; import java.util.HashSet; import java.util.Set; /** * 用于正向工程的表 */ public class People { private int id; private String name; private long year; private Set<GoodsEntity> goodsEntities=new HashSet<>(); public Set<GoodsEntity> getGoodsEntities() { return goodsEntities; } public void setGoodsEntities(Set<GoodsEntity> goodsEntities) { this.goodsEntities = goodsEntities; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public long getYear() { return year; } public void setYear(long year) { this.year = year; } } <file_sep>/spring/src/main/java/com/spring/aop/ThrowsAdvice.java package com.spring.aop; import java.lang.reflect.Method; import java.text.SimpleDateFormat; import java.util.Date; import java.util.logging.Logger; public class ThrowsAdvice implements org.springframework.aop.ThrowsAdvice { private Logger logger=Logger.getLogger("ThrowsAdvice"); public void ThrowsAdvice() { logger.info("ThrowsAdvice在运行..............."+new SimpleDateFormat().format(new Date(System.currentTimeMillis()))); } public void afterThrowing(Method method, Object[] args, Object target, Throwable subclass){ System.err.println("[异常日志]\n 时间:" + new Date() + "\n 业务类:" + target.getClass().getName() + "\n业务方法:"+ method.getName() + "\n 参数:"+ printArray(args) + "\n异常信息:"+ subclass.getMessage() + "\n堆栈信息:" + subclass.getStackTrace()); System.out.println("\n*************************异常通知结束****************************"); } private String printArray(Object[] args){ String s = ""; for(Object o : args){ s += o.toString(); } return s; } } <file_sep>/mybatis01/src/main/java/com/mybatis/mapper/IStudentMapper.java package com.mybatis.mapper; import com.mybatis.pojo.Student; import java.util.List; import java.util.Map; public interface IStudentMapper { public Integer count(); public Integer count2(int param); public Integer count$(Map map); public Object[] selectObj(); int insert(Map map); List<Student> getAssosiation(); List<Student> getLink(); List<Student> querryQritirea(Student stu); } <file_sep>/spring/src/main/java/com/spring/aop/aspectj/Test.java package com.spring.aop.aspectj; import org.springframework.context.support.ClassPathXmlApplicationContext; import java.util.*; public class Test { public static void main(String[] args) { ClassPathXmlApplicationContext context= new ClassPathXmlApplicationContext ("com.spring.aop.aspectj/applicationContext.xml"); AopService service = (AopService) context.getBean("service"); service.post("哈哈哈"); } @org.junit.Test public void test(){ int b='2'; int a=1%2; System.out.println(a+"=="+b); // Vector // ArrayList // LinkedList // List // TreeMap Collection } public Test() { test(); } } <file_sep>/java8/src/main/java/test1/InversOut.java package test1; import org.junit.Test; import java.util.Scanner; import java.util.Stack; /** * 反转输出 */ public class InversOut { public static void main(String[] args) { Scanner sc=new Scanner(System.in); System.out.println("输入数据进行反转"); String data = sc.nextLine().trim(); int a = Integer.parseInt(data); int[] temp=new int[10]; for (int i=0;i<temp.length-1;i++){ if(i==0){ temp[i]= a%10; } a= get(a); temp[i+1]= a%10; } System.out.println("反转输出"); for(int j=0;j<temp.length;j++){ if(temp[j]!=0){ System.out.print(temp[j]); } } } public static int get(int a){ a=a/10; return a; } @Test public void testStack(){ Stack stack=new Stack(); stack.push(1); stack.push(2); stack.push(3); stack.push(4); while (!stack.empty()){ Object pop = stack.pop(); System.out.println(pop); } } } <file_sep>/hibernate01/src/main/java/com/hibernate/test/TestManyToMany.java package com.hibernate.test; import com.hibernate.pojo.Employee; import com.hibernate.pojo.Project; import org.hibernate.Session; import org.hibernate.Transaction; import org.junit.Test; import java.util.Set; public class TestManyToMany { @Test public void save(){ Session session = HibernateUtils.getSession(); Transaction transaction = session.beginTransaction(); Project project=new Project(); project.setPname("雨霏霏"); Employee emp=new Employee(); emp.setEname("赵小六"); Employee emp2=new Employee(); emp2.setEname("灵儿"); Set<Employee> employees = project.getEmployees(); employees.add(emp); employees.add(emp2); project.setEmployees(employees); session.save(project); transaction.commit(); session.close(); } @Test public void get(){ Session session = HibernateUtils.getSession(); Transaction tran = session.beginTransaction(); Employee employee = session.get(Employee.class, 1); Set<Project> projects = employee.getProjects(); for(Project project:projects){ System.out.println(project.getPname()); } tran.commit(); session.close(); } } <file_sep>/java8/src/main/java/com/d/Thread.java package com.d; /** * sleep和wait * 这两个方法来自不同的类分别是Thread和Object * 最主要是sleep方法没有释放锁,而wait方法释放了锁,使得其他线程可以使用同步控制块或者方法(锁代码块和方法锁)。 * wait,notify和notifyAll只能在同步控制方法或者同步控制块里面使用,而sleep可以在任何地方使用(使用范围) * sleep必须捕获异常,而wait,notify和notifyAll不需要捕获异常 */ public class Thread { public static void main(String[] args) { // ThreadDemo t=new ThreadDemo(); // java.lang.Thread thread=new java.lang.Thread(t); // thread.start(); // thread.notify(); java.lang.Thread thread = new java.lang.Thread(new ThreadDemo()); thread.start(); try { thread.sleep(5000); } catch (Exception e) { e.printStackTrace(); } // thread.interrupt(); // new java.lang.Thread(new ThreadDemo()).start(); // Thread.class.notifyAll(); } } class ThreadDemo implements Runnable{ @Override public void run() { synchronized (ThreadDemo.class) { System.out.println("enter thread1..."); System.out.println("thread1 is waiting..."); try { //调用wait()方法,线程会放弃对象锁,进入等待此对象的等待锁定池 ThreadDemo.class.wait(); } catch (Exception e) { e.printStackTrace(); } System.out.println("thread1 is going on ...."); System.out.println("thread1 is over!!!"); } } } <file_sep>/spring/src/main/java/demo01/Printer.java package demo01; /** * 打印机 */ public class Printer { private Ink ink; //墨盒接口 private Paper paper;//纸张接口 public Printer(Ink ink,Paper paper){ this.ink = ink; this.paper = paper; } public Printer(){ // System.out.println("********Printer**********"); } public void work(){ if(ink == null){ System.out.println("请安装墨盒!"); }else{ ink.print(); } if (paper==null){ System.out.println("没有纸张了,请放入纸张!"); }else{ paper.page(); } } public void setInk(Ink ink) { this.ink = ink; } public void setPaper(Paper paper) { this.paper = paper; } } <file_sep>/mybatis01/src/test/java/AliasTest.java import com.mybatis.mapper.ISchoolMapper; import com.mybatis.pojo.School; import com.mybatis.pojo.Student; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import java.util.List; public class AliasTest { static SqlSessionFactoryBuilder sfb=new SqlSessionFactoryBuilder(); static SqlSessionFactory build = sfb.build(TestSqlSession2.class.getClass().getResourceAsStream("/mybatis-config.xml")); static SqlSession sqlSession = build.openSession(); public static void main(String[] args) { ISchoolMapper school = sqlSession.getMapper(ISchoolMapper.class); List<School> schoolByOrder = school.getSchoolByOrder(); List<School> schools = school.find(); schoolByOrder.forEach((s)->{ System.out.println(s.getScid()+s.getScname()); }); } } <file_sep>/baidudisk/src/main/java/com/disk/intercepter/service/IRegister.java package com.disk.intercepter.service; import com.disk.intercepter.pojo.Netuser; public interface IRegister { void saveNetUser(Netuser netuser); boolean checkUser(String username); Netuser isExit(Netuser nu, String loginName); } <file_sep>/java8/src/main/java/com/a/lamda/TestLambda2.java package com.a.lamda; import org.junit.Test; public class TestLambda2 { /** * 在一个二维数组中(每个一维数组的长度相同), * 每一行都按照从左到右递增的顺序排序, * 每一列都按照从上到下递增的顺序排序。 * 请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。 * 321 * 456 * 879 * 123 * 456 * 789 */ @Test public void test1(){ int a[][] ={{3,2,1},{4,5,6},{8,7,9}}; int s=3; // int[][] sort = sort(a); } public static void main(String[] args) { String name = "顺顺"; f1(name); f2(name); } private static void f2(String name) { name = "丰丰"; f1(name); } static void f1(String name){ System.out.println(name); } } <file_sep>/hibernate/src/main/java/com/hibernate/pojo/Emp.java package com.hibernate.pojo; import java.sql.Date; public class Emp { private String empNum; private String eName; private Date startDate; } <file_sep>/hibernate01/src/main/java/com/hibernate/test/XMLQueryTest.java package com.hibernate.test; import com.hibernate.pojo.Detail; import org.hibernate.Session; import org.hibernate.query.Query; import org.junit.Test; public class XMLQueryTest { /** * XML中的sql-query */ @Test public void test1(){ Session session = HibernateUtils.getSession(); Query<Detail> query = session.createNamedQuery("allDetails", Detail.class); query.list() .forEach((d)->{ System.out.println(d.getUsername()+d.getBirthday()); }); } /** * XML中的query */ @Test public void test2(){ Session session = HibernateUtils.getSession(); Query<Detail> query = session.createNamedQuery("allDetails2", Detail.class); query.list() .forEach((d)->{ System.out.println(d.getUsername()+d.getBirthday()); }); } } <file_sep>/hibernate01/src/main/java/com/hibernate/test/CofigurationAttributeTest.java package com.hibernate.test; import com.hibernate.pojo.GoodsEntity; import com.hibernate.pojo.People; import org.hibernate.Session; import org.hibernate.query.Query; import org.junit.Test; import java.util.List; /** * 测试fetch,order-by,fetch-size,等属性的作用 */ public class CofigurationAttributeTest { /** * fetch:在一对多的主表即一的一方进行配置 * 当fetch=join 时,发送内连接查询,查询一的一方的单条数据会产生左连接查询可能会有迪卡尔积的问题,适合数据量小的查询, * select people0_.id as id1_4_0_, people0_.name as name2_4_0_, people0_.year as year3_4_0_, goodsentit1_.pid as pid4_3_1_, goodsentit1_.id as id1_3_1_, goodsentit1_.id as id1_3_2_, * goodsentit1_.goods_name as goods_na2_3_2_, goodsentit1_.goods_price as goods_pr3_3_2_, goodsentit1_.pid as pid4_3_2_ from * people people0_ left outer join goods goodsentit1_ on people0_.id=goodsentit1_.pid where people0_.id=? * 当fetch=select 时,发送两条查询语句,可能会产生n+1问题,数据量大的情况下采用此种查询 * Hibernate: select people0_.id as id1_4_0_, people0_.name as name2_4_0_, people0_.year as year3_4_0_ from people people0_ where people0_.id=? * Hibernate: select goodsentit0_.pid as pid4_3_0_, goodsentit0_.id as id1_3_0_, goodsentit0_.id as id1_3_1_, goodsentit0_.goods_name as goods_na2_3_1_, * goodsentit0_.goods_price as goods_pr3_3_1_, goodsentit0_.pid as pid4_3_1_ from goods goodsentit0_ where goodsentit0_.pid=? * 当fetch=subselect 时,发送两条语句,一条为子查询对一的一方的多条记录查询有效 * */ @Test public void test1(){ Session session = HibernateUtils.getSession(); Query<People> query = session.createQuery(" from People ", People.class); List<People> list = query.list(); list.forEach(people -> System.out.println(people.getName()+"=="+people.getGoodsEntities().size())); } /** * */ @Test public void test2(){ Session session = HibernateUtils.getSession(); People people = session.get(People.class, 38); System.out.println(people.getName()+""+people.getGoodsEntities().size()); } @Test public void test3(){ Session session = HibernateUtils.getSession(); GoodsEntity goodsEntity = session.get(GoodsEntity.class, 92l); System.out.println(goodsEntity.getGoodsName()+""+goodsEntity.getPeople()); } @Test public void test4(){ Session session = HibernateUtils.getSession(); List<GoodsEntity > goodsEntity = session.createQuery("from GoodsEntity ",GoodsEntity.class).list(); goodsEntity.forEach(goodsEntity1 -> System.out.println(goodsEntity1.getGoodsName()+""+goodsEntity1.getPeople().getName())); } } <file_sep>/java8/src/main/java/com/a/lamda/TestLamda.java package com.a.lamda; import org.junit.Test; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.TreeSet; import java.util.function.Consumer; public class TestLamda { @Test public void testCompare(){ Comparator<Integer> com=new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return Integer.compare(o1,o2); } }; TreeSet<Integer> treeSet=new TreeSet<>(com); treeSet.add(3); treeSet.add(8); treeSet.add(133); treeSet.add(5); //按照从小到大进行排序,通过实现了Comparator接口 //输出3,5,8,133 for(Integer i:treeSet){ System.out.println(i); } } @Test public void testLambdaComparator(){ Comparator<Integer> com=(x,y)->Integer.compare(x,y); TreeSet<Integer> treeSet=new TreeSet<>(com); treeSet.add(3); treeSet.add(8); treeSet.add(133); treeSet.add(5); //按照从小到大进行排序,通过实现了Comparator接口 //输出3,5,8,133 for(Integer i:treeSet){ System.out.println(i); } } @Test public void testIndentiti(){ CompareByMe compareByMe= new CompareByMe<Integer,Integer>(){ public boolean test(Integer int1,Integer int2) { return int1>int2; } }; //可以比较大小 int a=8; int b=7; System.out.println(compareByMe.test(a,b)); } @Test public void test(){ List list=new ArrayList(); list.add(2); list.add(24); list.add(23); list.forEach(System.out::println); } /** * Stream API */ @Test public void test1(){ List<Employe> employes=new ArrayList<>(); employes.add(new Employe("张三",88.2)); employes.add(new Employe("li",93.4)); employes.add(new Employe("王五",99.2)); employes.add(new Employe("赵六233421",100.9)); employes.add(new Employe("天气",333.3)); employes.stream() .filter(employe -> employe.getSalary()>90) .filter(employe -> employe.getName().length()>4) .limit(3) .forEach(System.out::println); // employes.stream().map().collect() } @Test public void test2(){ Consumer consumer=(x)-> System.out.println(x); consumer.accept("大家好啊"); } @Test public void test3(){ Comparator<Integer> com=(x,y)->Integer.compare(x,y); int compare = com.compare(3, 2); /*Integer中的比较的源代码 public static int compare(int x, int y) { return (x < y) ? -1 : ((x == y) ? 0 : 1); } */ System.out.println(compare); } @Test public void test4(){ // WebApplicationContext // ApplicationContext Runnable runnable=()->{ System.out.println("执行run方法"); }; Thread thread=new Thread(()->{ System.out.println("执行run方法"); }); thread.start(); } /** * 对一个数进行操作 */ @Test public void test5(){ Integer operater = operater(3, (x) -> x * x); System.out.println(operater); } public Integer operater(Integer a,MyFun myFun){ return myFun.getValue(a); } } <file_sep>/spring/src/main/java/com/aop/ISaleTicket.java package com.aop; public interface ISaleTicket { void sale(); } <file_sep>/mybatis01/src/test/java/AnnoTest.java import com.mybatis.mapper.ISchoolAnnoMapper; import com.mybatis.mapper.IStudentMapper; import com.mybatis.mapper.IStudentMapperDen; import com.mybatis.pojo.School; import com.mybatis.pojo.Student; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import java.util.List; public class AnnoTest { static SqlSessionFactoryBuilder sfb=new SqlSessionFactoryBuilder(); static SqlSessionFactory build = sfb.build(TestSqlSession2.class.getClass().getResourceAsStream("/mybatis-config.xml")); static SqlSession sqlSession = build.openSession(); public static void main(String[] args) { critiera(); } public static void critiera(){ IStudentMapperDen mapper = sqlSession.getMapper(IStudentMapperDen.class); Student student=new Student(); student.setSname("%张%"); Student student1 = mapper.getStudent(student); System.out.println(student1.getSname()+"==="+student1.getSno()); } private void find(){ ISchoolAnnoMapper mapper = sqlSession.getMapper(ISchoolAnnoMapper.class); List<School> school = mapper.getSchool(1); school.forEach(s->{ System.out.println(s.getScname()); }); } } <file_sep>/mybatis01/src/main/java/com/mybatis/handler/MyHandler.java package com.mybatis.handler; import org.apache.ibatis.type.BaseTypeHandler; import org.apache.ibatis.type.JdbcType; import org.apache.log4j.Logger; import java.sql.CallableStatement; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; /** * 自定义的handler进行类型转换 */ public class MyHandler extends BaseTypeHandler<String> { Logger logger=Logger.getLogger(MyHandler.class); @Override public void setNonNullParameter(PreparedStatement preparedStatement, int i, String s, JdbcType jdbcType) throws SQLException { System.out.println("!!!!!!!"+i+"11111"+s); //# The error may involve com.mybatis.mapper.IEmpMapper.MyParamHandler //### The error occurred while setting parameters //### SQL: insert into(id,name,sex) emp values(?,?,?) logger.info("到达了设置参数的方法,快开始吧"); String value; System.out.println(s+"==="+i); if("男".equals(s)){ value="1"; }else{ value="0"; } preparedStatement.setString(3,value); } /** * * @param resultSet 结果集映射 * @param s 获取的列名 * @return * @throws SQLException */ @Override public String getNullableResult(ResultSet resultSet, String s) throws SQLException { System.out.println("=======99>"+s); int anInt = resultSet.getInt(s); return anInt==1?"男":"女"; } @Override public String getNullableResult(ResultSet resultSet, int i) throws SQLException { System.out.println("=============>"+i); return null; } @Override public String getNullableResult(CallableStatement callableStatement, int i) throws SQLException { return null; } } <file_sep>/mybatis01/src/test/java/TestSchool.java import com.mybatis.pojo.School; import com.mybatis.pojo.Student; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class TestSchool { static SqlSessionFactoryBuilder sfb=new SqlSessionFactoryBuilder(); static SqlSessionFactory build = sfb.build(TestSqlSession2.class.getClass().getResourceAsStream("/mybatis-config.xml")); static SqlSession sqlSession = build.openSession(); public static void main(String[] args) { School school=new School(); school.setScid(1); school.setScname("友谊中学"); sqlSession.insert("addSchool",school); Student student=new Student(); student.setSno(3); student.setSname("林秦吉"); student.setScid(school.getScid()); sqlSession.insert("insert",student); sqlSession.commit(); } } <file_sep>/java8/src/main/java/com/e/FlowSort.java package com.e; /** * 冒泡排序 */ public class FlowSort { public static void main(String[] args) { int[] arr ={3,43,63,7,68,7}; for (int i = 0; i <arr.length; i++) { int temp; for (int j = 0; j <i ; j++) { if(arr[i]<arr[j]){ temp=arr[i]; arr[i]=arr[j]; arr[j]=temp; } } } System.out.println(arr); System.out.println(arr); } } <file_sep>/spring/src/main/java/com/aop/SaleTicket.java package com.aop; //被代理对象 public class SaleTicket implements ISaleTicket{ //spring织入点 @Override public void sale(){ System.out.println("=========================售票了============================="); } } <file_sep>/java8/src/main/java/test1/Point.java package test1; public class Point { static int x; int y; } class Test { public static void main(String args[]) { Point p1 = new Point(); Point p2 = new Point(); p1.x = 10; p1.y= 20; System.out.print(p2.x+ ", "); System.out.print(p2.y); } } <file_sep>/baidudisk/src/main/java/com/disk/controller/LoginAction.java package com.disk.controller; import com.disk.intercepter.service.IRegister; import com.disk.intercepter.pojo.Netuser; import com.opensymphony.xwork2.ModelDriven; import org.apache.struts2.ServletActionContext; import org.springframework.beans.factory.annotation.Autowired; import javax.servlet.http.Cookie; public class LoginAction extends BaseController implements ModelDriven<Netuser> { private Netuser nu=new Netuser(); @Autowired private IRegister register; private String loginName; private String rempas; public String dologin(){ Cookie[] cookies = ServletActionContext.getRequest().getCookies(); for(Cookie c:cookies){ //先将sessionId清除 ServletActionContext.getRequest().getSession().invalidate(); System.out.println(c.getName()+"======"); if ("remember".equals(c.getName())){ return SUCCESS; } } Netuser isExit=register.isExit(nu,loginName); if(rempas!=null&&isExit!=null) { //将记住的用户的密码设置进入cookie httpServletResponse.addCookie(new Cookie("remember",isExit.getUsername()+isExit.getPassword())); } if (isExit==null)return ERROR; else return SUCCESS; } public void setRempas(String rempas) { this.rempas = rempas; } public void setLoginName(String loginName) { this.loginName = loginName; } public void setNu(Netuser nu) { this.nu = nu; } @Override public Netuser getModel() { return nu; } } <file_sep>/spring/src/main/java/com/spring/day1/pojo/StaticObject.java package com.spring.day1.pojo; /** * 测试抽象类静态方法 */ public abstract class StaticObject { public static String run(){ System.out.println("====================="); return "跑起来了吧"; } } <file_sep>/spring/src/main/java/com/spring/day1/test/Test.java package com.spring.day1.test; import com.spring.day1.pojo.Component; import com.spring.day1.pojo.LinkComponent; import com.spring.day1.pojo.StaticObject; import demo01.Ink; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Test { @org.junit.Test public void test1(){ //父容器 ClassPathXmlApplicationContext parent=new ClassPathXmlApplicationContext("spring.xml"); //将子容器绑定给父容器 ClassPathXmlApplicationContext child=new ClassPathXmlApplicationContext(new String[]{"spring1.xml"},parent); ApplicationContext parent1 = child.getParent(); System.out.println(parent.hashCode()+"======"+parent1.hashCode()); Ink ink = (Ink) parent1.getBean("ink"); ink.print(); } @org.junit.Test public void test2(){ //父容器 ClassPathXmlApplicationContext parent=new ClassPathXmlApplicationContext("spring.xml"); //将子容器绑定给父容器 ClassPathXmlApplicationContext child=new ClassPathXmlApplicationContext(new String[]{"spring1.xml"},parent); ApplicationContext parent1 = child.getParent(); System.out.println(parent.hashCode()+"======"+parent1.hashCode()); Component component = (Component) child.getBean("component"); System.out.println(component); } @org.junit.Test public void test3(){ //父容器 ClassPathXmlApplicationContext parent=new ClassPathXmlApplicationContext("spring.xml"); //将子容器绑定给父容器 ClassPathXmlApplicationContext child=new ClassPathXmlApplicationContext(new String[]{"spring1.xml"},parent); ApplicationContext parent1 = child.getParent(); LinkComponent linkComponent = (LinkComponent) child.getBean("linkComponent"); System.out.println(linkComponent.getComponent()); } @org.junit.Test public void test4(){ //父容器 ClassPathXmlApplicationContext parent=new ClassPathXmlApplicationContext("spring.xml"); //将子容器绑定给父容器 ClassPathXmlApplicationContext child=new ClassPathXmlApplicationContext(new String[]{"spring1.xml"},parent); ApplicationContext parent1 = child.getParent(); child.getBean("staticObject"); } @org.junit.Test public void test5(){ ClassPathXmlApplicationContext parent=new ClassPathXmlApplicationContext("applicationContext.xml"); } } <file_sep>/hibernate01/Hibernate5笔记.md ### Hibernate5笔记 #### hibernate的三态 hibernate由游离态,持久态,瞬时态。 游离态:session中没有,数据库中有此对象 持久态:session中有,数据库中也有 瞬时态:对象刚刚创建,session中没有,数据库中也没有。 补充(mysql是关系型数据库,存储与硬盘中。读写速度必定低于h2等内存数据库。除了关系型数据库还有nosql数据库,如redis,mongodb,直接存储对象) #### 持久化,序列化 持久化概念是指将内存中的数据以文件的形式存储在文件中。如,一个应用程序中的数据存储在数据库中,excel,txt等文件都可以作为数据的持久化存储文件。 序列化是指将对象以流的方式进行存储、传输。具有序列化id唯一可以进行反序列化。 #### ORM概念 orm是指对象关系映射技术(Object Relation Mapping),并不只是hibernate所具有的特殊功能。是一种泛指的概念。hibernate是全自动的orm框架,类似的半自动化框架还有mybatis。jpa是Java Persistence API的简称中文名Java持久层API,是JDK 5.0注解或XML描述对象-关系表的映射关系,并将运行期的实体对象持久化到数据库中。 ​ PA的总体思想和现有Hibernate、TopLink、JDO等ORM框架大体一致。总的来说,JPA包括以下3方面的技术: **ORM映射元数据** JPA支持XML和[JDK](https://baike.baidu.com/item/JDK)5.0注解两种元数据的形式,元数据描述对象和表之间的映射关系,框架据此将实体[对象持久化](https://baike.baidu.com/item/%E5%AF%B9%E8%B1%A1%E6%8C%81%E4%B9%85%E5%8C%96)到数据库表中; **API** 用来操作实体对象,执行CRUD操作,框架在后台替代我们完成所有的事情,开发者从繁琐的JDBC和SQL代码中解脱出来。 **查询语言** 这是持久化操作中很重要的一个方面,通过[面向对象](https://baike.baidu.com/item/%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1)而非面向数据库的查询语言查询数据,避免程序的SQL语句紧密耦合。 #### EJB概念 EJB是sun的JavaEE服务器端[组件模型](https://baike.baidu.com/item/%E7%BB%84%E4%BB%B6%E6%A8%A1%E5%9E%8B),设计目标与核心应用是部署分布式应用程序。简单来说就是把已经编写好的程序(即:类)打包放在服务器上执行。凭借java跨平台的优势,用EJB技术部署的[分布式系统](https://baike.baidu.com/item/%E5%88%86%E5%B8%83%E5%BC%8F%E7%B3%BB%E7%BB%9F/4905336)可以不限于特定的平台。EJB (Enterprise [JavaBean](https://baike.baidu.com/item/JavaBean))是J2EE(javaEE)的一部分,定义了一个用于开发基于组件的企业多重应用程序的标准。其特点包括[网络服务](https://baike.baidu.com/item/%E7%BD%91%E7%BB%9C%E6%9C%8D%E5%8A%A1/9498645)中心支持和核心开发工具(SDK)。 在J2EE里,Enterprise Java Beans(EJB)称为Java 企业Bean,是Java的核心代码,分别是会话Bean(Session Bean),实体Bean(Entity Bean)和消息驱动Bean(MessageDriven Bean)。在EJB3.0推出以后,实体Bean被单独分了出来,形成了新的规范[JPA](https://baike.baidu.com/item/JPA)。 #### Hibernate的get()与load()的区别 ![img](file:///C:\Users\DELL\AppData\Roaming\Tencent\Users\1355140243\QQ\WinTemp\RichOle\OVU63XT13@BDT{9RJD719NW.png) 当使用get()查询的数据不存在时,会正常执行,展示null值。 ![img](file:///C:\Users\DELL\AppData\Roaming\Tencent\Users\1355140243\QQ\WinTemp\RichOle\V5E_APMRHAATL]VO{Y}$ZYI.png) 当使用load()进行查询的数据不存在时,会抛出异常,因此,不建议使用load方法。 #### lazy的使用 ![a](C:\Users\DELL\Desktop\a.png) 使用get()方法获取数据时,lazy默认的时false,因此在箭头处直接执行sql语句进行查询![b](C:\Users\DELL\Desktop\b.png) 使用load()方法进行获取时,lazy默认为true,会在使用时才执行sql查询,进箭头处才会执行sql。 lazy属性时hibernate的一种优化策略,在必要时会节省数据库连接资源的开销。 lazy有三个属性:true、false、extra 【true】:默认取值,它的意思是只有在调用这个集合获取里面的元素对象时,才发出查询语句,加载其       集合元素的数据 【false】:取消懒加载特性,即在加载对象的同时,就发出第二条查询语句加载其关联集合的数据  【extra】:一种比较聪明的懒加载策略,即调用集合的size/contains等方法的时候,hibernate并不会去加载整个集合的数据,而是发出一条聪明的SQL语句,以便获得需要的值,只有在真正需要用到这些集合元素对象数据的时候,才去发出查询语句加载所有对象的数据。 #### inverse属性 设inverse="true" 时,表示 Set/Collection 关系由另一方来维护,由不包含这个关系的一方来维护这个关系,所以才称为“反转”了,具体体现在sql语句不同,会增加一条update语句,是由对方提供的语句管理 #### 关联关系的几种方式 ##### 1.maney-to-one 我们在多的一方配置单向的<money-to-one> ```java <!--多的一方配置的属性与数据库的外键进行关系映射--> <!--name为实体中的关系,column为数据库中的参考外键--> <many-to-one name="people" column="pid"></many-to-one> ``` 然后再代码出进行保存测试 ```java People people=new People(); people.setName("小王"); people.setYear(20l); GoodsEntity goodsEntity=new GoodsEntity(); goodsEntity.setGoodsName("瓜子"); goodsEntity.setGoodsPrice(33); goodsEntity.setPeople(people); session.save(goodsEntity); transaction.commit(); ``` 按照逻辑应当先保存people,当不先进行people的保存时,运行程序会抛出如下异常 ```java java.lang.IllegalStateException: org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.hibernate.pojo.People Caused by: org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.hibernate.pojo.People at org.hibernate.engine.internal.ForeignKeys.getEntityIdentifierIfNotUnsaved(ForeignKeys.java:350) at org.hibernate.type.EntityType.getIdentifier(EntityType.java:495) at org.hibernate.type.ManyToOneType.isDirty(ManyToOneType.java:332) at org.hibernate.type.ManyToOneType.isDirty(ManyToOneType.java:343) at org.hibernate.type.TypeHelper.findDirty(TypeHelper.java:315) at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1454) ... 31 more ``` 出现此种情况,我们再置文件中写上cascade属性设置为级联便可 ```java <!--多的一方配置的属性与数据库的外键进行关系映射--> <many-to-one name="people" column="pid" cascade="save-update"></many-to-one> ``` 默认会先执行主表的插入操作,然后进行从表的插入操作。 ##### 2.one-to-money 再一的一方中给实体类添加set集合,再一的配置文件中添加如下标签 ```java <set name="goodsEntities"><!-- 实体类中的属性名称--> <key> <column name="pid"></column><!--关联的外键的列名--> </key> <one-to-many class="com.hibernate.pojo.GoodsEntity"/><!--关联的实体类(多的一方)--> </set> ``` ![3](C:\Users\DELL\Desktop\3.png) 看程序再关联查询中的结果,可知,在红线处打印了第二条sql,关联查询时采用的时懒加载。可以在set标签上配置lazy="false",来关闭懒加载的属性。 在执行一对多的一的一方的保存时 ![q1](C:\Users\DELL\Desktop\q1.png) ``` hibernate一共打印了五条数据,先执行主表的插入,然后执行从表的插入,再在从表的外键中建立主从表的关系维护,执行update语句。(此处主表数据一条,从表数据两条) ``` 注:以上均为单向维护。 ##### 3.OneToOne 一对一的关系的映射有两种在数据库级别上边。 1:从表的主键参考主表的主键,主表的主键既做主键又做外键 ```mysql create table user( id int(11) NOT NULL AUTO_INCREMENT, name varchar(20) DEFAULT NULL, accpass varchar(20) DEFAULT NULL, PRIMARY KEY (id) ); create table reader ( `accid` int(11) NOT NULL, `username` varchar(20) DEFAULT NULL, `birthday` date DEFAULT NULL, `email` varchar(50) DEFAULT NULL, PRIMARY KEY (`accid`), CONSTRAINT `detail_ibfk_1` FOREIGN KEY (`accid`) REFERENCES `account` (`id`) ) ``` 2:从表的主键参考主表的外键,主表的外键是一个普通的键 配置文件中主表与从表的配置文件都需要配置 ```chinese <one-to-one name="实体所对应的属性的名称" class="另一张关系表的classpath下的绝对路径"/> ``` 例1:主表配置 ``` <generator class="native"></generator><!--采用数据库的本地的策略--> <one-to-one name="detailByAccid" class="com.hibernate.pojo.Detail"/> ``` 从表配置 ```java <id name="accid"> <column name="accid" sql-type="int(11)"/> <generator class="foreign"><!--外键的配置,此处需要配置关联的属性--> <param name="property">accountByAccid</param> </generator> </id> <one-to-one name="accountByAccid" class="com.hibernate.pojo.Account"/> ``` 以上配置为第一种的一对一配置 例二:主表不变 从表配置 ```java <class name="com.wdzl.pojo.Detail2" table="detail2" schema="hib"> <id name="detid"> <column name="detid" sql-type="int(10)"/> <generator class="native"></generator> </id><!--unique属性确定唯一性,在实体类中不用set集合,直接使用引用对象--> <many-to-one name="account" cascade="all" unique="true" class="com.wdzl.pojo.Account"> <column name="accid" not-null="true"/><!--外键的列名--> </many-to-one> </class> ``` ##### 4.Many-To-Many 在配置many-to-many时,数据库表方面,采取三张表,两张实体表,一张关系表 ```mysql -- 创建员工表 CREATE TABLE employee( eno INT PRIMARY KEY AUTO_INCREMENT, ename VARCHAR(30) ); -- 创建项目表 CREATE TABLE project( pno INT PRIMARY KEY AUTO_INCREMENT, pname VARCHAR(30) ); -- 关系表 CREATE TABLE `ep_relation` ( `pid` int(11) DEFAULT NULL, `eid` int(11) DEFAULT NULL, KEY `FK_ep_relation_e` (`eid`), KEY `FK_ep_relation_p` (`pid`), CONSTRAINT `FK_ep_relation_e` FOREIGN KEY (`eid`) REFERENCES `employee` (`eno`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `FK_ep_relation_p` FOREIGN KEY (`pid`) REFERENCES `project` (`pno`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ``` 而在实体类中我们只创建两个实体类,在类中使用面向对象的思想建立set集合来描述两者之间的关系 如: ``` public class Project { private int pno; private String pname; private Set<Employee> employees=new HashSet<>(); } public class Employee { private int eno; private String ename; private Set<Project> projects=new HashSet<>(); } ``` 在xml的定义中,我们均采用set集合进行many-to-many的标签进行关系的设置 ```java <class name="com.hibernate.pojo.Project" table="project" schema="demo"> <id name="pno"> <column name="pno" sql-type="int(11)"/> <generator class="increment"></generator> </id> <property name="pname"> <column name="pname" sql-type="varchar(30)" length="30" not-null="true"/> </property> <!--当此处的inverse="true"时,则关系由对方进行维护,我们在代码出保存由Project对象建立的关系时,可以从数据库中看到中间表中没有数据之间的关系映射,即缺少与代码中对应的数据之间的关联关系--> <set name="employees" table="ep_relation" cascade="save-update" inverse="true"> <key><!-- 此处的pid为此类与关系表的外键的column值--> <column name="pid"></column> </key> <!-- 此处的eid为对方在关系表中的外键的column值--> <many-to-many column="eid" not-found="ignore" class="com.hibernate.pojo.Employee"></many-to-many> </set> </class> <class name="com.hibernate.pojo.Employee" table="employee" schema="demo"> <id name="eno"> <column name="eno" sql-type="int(11)"/> <generator class="increment"></generator> </id> <property name="ename"> <column name="ename" sql-type="varchar(30)" length="30" not-null="true"/> </property> <set name="projects" table="ep_relation"> <key> <!-- 此处的eid为对方在关系表中的外键的column值--> <column name="eid"></column> </key> <!-- 此处的eid为对方在关系表中的外键的column值--> <many-to-many column="pid" class="com.hibernate.pojo.Project"></many-to-many> </set> </class> ``` 保存的示例代码 ```java @Test public void save(){ Session session = HibernateUtils.getSession(); Transaction transaction = session.beginTransaction(); Project project=new Project(); project.setPname("雨霏霏"); Employee emp=new Employee(); emp.setEname("赵小六"); Employee emp2=new Employee(); emp2.setEname("灵儿"); Set<Employee> employees = project.getEmployees(); employees.add(emp); employees.add(emp2); project.setEmployees(employees); //保存Project对象的所建立起来的关联关系,及数据,在其inverse="true"时,则中间表的关系数据的插入由对方进行维护 session.save(project); transaction.commit(); session.close(); } ``` #### hibernate的hql语句 ```java @Test public void test1(){ Session session = HibernateUtils.getSession(); Query<People> people = session.createQuery("from People ", People.class); people.list() .stream() .filter(people1 -> people1.getName().contains("小")) .limit(3) .forEach((p)->System.out.println(p.getName())); } /** * 命名参数的方式 */ @Test public void test2(){ Session session = HibernateUtils.getSession(); Query<People> people = session.createQuery("from People where id=:a ", People.class) .setParameter("a",15); people.list() .forEach((p)->System.out.println(p.getName())); } /** * Query<Object[]> people中的泛型的变量的类型由参数的个数决定 * 参数为多个,但不是全部属性值,则用Object数组进行接收, * 参数如果是单个则可以使用与之所对应的具体的属性类型进行接收 */ @Test public void test3(){ Session session = HibernateUtils.getSession(); Query<Object[]> people = session.createQuery("select id,name,year as y from People where id=:a ") .setParameter("a",15); List<Object[]> list = people.list(); list.forEach((p)->System.out.println(p[0]+""+p[1]+""+p[2])); } /** * Query中的返回的结果的类型可以是String,Object类型 */ @Test public void test4(){ Session session = HibernateUtils.getSession(); Query<String> people = session.createQuery("select name from People where id=:a ") .setParameter("a",15); List<String> list = people.list(); list.forEach((p)->System.out.println(p)); } /** * 一对一关系中设置lazy 延迟加载失效,一对一关系采用主表(既做主键又作外键)的配置关系 * 在主表中设置constrained=true可以实现延迟加载 */ @Test public void test5(){ Session session = HibernateUtils.getSession(); Query<Account> people = session.createQuery("from Account "); List<Account> list = people.list(); list.forEach((p)->System.out.println(p.getAccpass()+p.getDetailByAccid().getUsername())); } @Test public void test6(){ Session session = HibernateUtils.getSession(); //Asc升序,默认升序 Query<Account> people = session.createQuery("from Account order by id desc"); List<Account> list = people.list(); list.forEach((p)->System.out.println(p.getAccid()+p.getDetailByAccid().getUsername())); } /** * 聚合语句 */ @Test public void test7(){ Session session = HibernateUtils.getSession(); Query<Object[]> objs=session.createQuery("select count(*),max(id),min(id),sum(id),avg(id) from Account"); objs.list() .forEach((p)->System.out.println(p[0]+"总数量 "+p[1]+"最大值"+p[2]+"最小值"+p[3]+"总和"+p[4]+"平均数")); } /** * 分页 :分页查询的公式,当前页数据=(当前页页码-1)*每页总记录数 */ @Test public void test8(){ Session session = HibernateUtils.getSession(); Query<Account> people = session.createQuery("from Account"); int curPage=2;//当前页页码 int maxCount=2;//每页总记录数 //设置每页总记录数 people.setMaxResults(maxCount); //设置从当前数据记录开始计算 people.setFirstResult((curPage-1)*maxCount); List<Account> list = people.list(); list.forEach((p)->System.out.println(p.getAccid()+p.getDetailByAccid().getUsername())); } /** * 子查询 select * from a where a.id in(select id where a) * 组查询group by having * 连接查询 inner join ,left join ,right join */ @Test public void test9(){ Session session = HibernateUtils.getSession(); Query<Object[]> people = session.createQuery( "select p.name,count(g.people.id) from People p left join GoodsEntity g " + "on g.people.id=p.id group by p.id,p.name having count(g.people.id)<3"); CriteriaBuilder builder = session.getCriteriaBuilder(); List<Object[]> list = people.list(); list.forEach((p)->System.out.println(p[0]+""+p[1])); } ``` #### hibernate的QBC查询 版本5.3 ```java /** * QBC之where查询 */ @Test public void test1(){ Session session = HibernateUtils.getSession(); // 获得CriteriaBuilder 用来创建CriteriaQuery CriteriaBuilder builder = session.getCriteriaBuilder(); // 创建CriteriaQuery 参数为返回结果类型 CriteriaQuery<Account> criteria = builder.createQuery(Account.class); // 返会查询表 参数类型为要查询的持久类 Root<Account> root = criteria.from(Account.class); // 设置where条件 criteria.where(builder.equal(root.get("accname"), "3424556")); // 创建query 查询 Query<Account> query = session.createQuery(criteria); // 返回结果 Account account = query.getSingleResult(); System.out.println(account.getAccname()+account.getAccpass()); } /** *查询总数目 */ @Test public void test2(){ Session session = HibernateUtils.getSession(); // 获得CriteriaBuilder 用来创建CriteriaQuery CriteriaBuilder builder = session.getCriteriaBuilder(); // 参数为查询的结果类型 CriteriaQuery<Long> criteria = builder.createQuery(Long.class); // 从什么表查询 Root<Account> root = criteria.from(Account.class); // 就是sql select 之后的语句 criteria.select(builder.count(root)); // 使用query 实现查询 Query<Long> query = session.createQuery(criteria); // 结果集 Long result = query.uniqueResult(); System.out.println(result); } ``` #### hibernate的XML中的sql语句 类似与mybatis的配置 ```java <sql-query name="allDetails"> <return class="com.hibernate.pojo.Detail" alias="detail"></return> select * from detail </sql-query> <query name="allDetails2" > from Detail </query> ``` 执行代码 ```java /** * XML中的sql-query */ @Test public void test1(){ Session session = HibernateUtils.getSession(); Query<Detail> query = session.createNamedQuery("allDetails", Detail.class); query.list() .forEach((d)->{ System.out.println(d.getUsername()+d.getBirthday()); }); } /** * XML中的query */ @Test public void test2(){ Session session = HibernateUtils.getSession(); Query<Detail> query = session.createNamedQuery("allDetails2", Detail.class); query.list() .forEach((d)->{ System.out.println(d.getUsername()+d.getBirthday()); }); } ``` hibernate的属性配置 ```java <!--设置update与insert属性可以在程序修改属性值时受到约束,不会修改相应的配置的属性所对应的列名的值--> <property name="birthday" update="false" insert="false"> <column name="birthday" sql-type="date" not-null="true"/> </property> ``` ##### fetch 当fetch=join 时,发送左连接查询,查询一的一方的单条数据会产生左连接查询可能会有迪卡尔积的问题,适合数据量小的查询,直接在主表进行配置 ```java <set name="goodsEntities" fetch="join" lazy="false" cascade="save-update" > <key> <column name="pid"></column> </key> <one-to-many class="com.hibernate.pojo.GoodsEntity"/> </set> ``` 代码:只有在查询单个主表的对象才会显示出差异,如果查询主对象的集合数据则此配置无效 ```java @Test public void test2(){ Session session = HibernateUtils.getSession(); People people = session.get(People.class, 38); System.out.println(people.getName()+""+people.getGoodsEntities().size()); } ``` console: ```mysql Hibernate: select people0_.id as id1_4_0_, people0_.name as name2_4_0_, people0_.year as year3_4_0_, goodsentit1_.pid as pid4_3_1_, goodsentit1_.id as id1_3_1_, goodsentit1_.id as id1_3_2_, goodsentit1_.goods_name as goods_na2_3_2_, goodsentit1_.goods_price as goods_pr3_3_2_, goodsentit1_.pid as pid4_3_2_ from people people0_ left outer join goods goodsentit1_ on people0_.id=goodsentit1_.pid where people0_.id=? 小王2 ``` 当fetch=select时,发送两条查询语句,可能会产生n+1问题,数据量大的情况下采用此种查询,发送多条sql,单记录与多记录的主表查询效果一样。 如:单记录查询(区别join的单表) ```java <set name="goodsEntities" fetch="select" lazy="false" cascade="save-update" > <key> <column name="pid"></column> </key> <one-to-many class="com.hibernate.pojo.GoodsEntity"/> </set> @Test public void test2(){ Session session = HibernateUtils.getSession(); People people = session.get(People.class, 38); System.out.println(people.getName()+""+people.getGoodsEntities().size()); } ``` console: ```mysql Hibernate: select people0_.id as id1_4_0_, people0_.name as name2_4_0_, people0_.year as year3_4_0_ from people people0_ where people0_.id=? Hibernate: select goodsentit0_.pid as pid4_3_0_, goodsentit0_.id as id1_3_0_, goodsentit0_.id as id1_3_1_, goodsentit0_.goods_name as goods_na2_3_1_, goodsentit0_.goods_price as goods_pr3_3_1_, goodsentit0_.pid as pid4_3_1_ from goods goodsentit0_ where goodsentit0_.pid=? 小王2 ``` 当fetch=subselect时,当fetch=subselect 时,发送两条语句,一条为子查询对一的一方的多条记录查询有效 ```java <set name="goodsEntities" fetch="subselect" lazy="false" cascade="save-update" > <key> <column name="pid"></column> </key> <one-to-many class="com.hibernate.pojo.GoodsEntity"/> </set> @Test public void test1(){ Session session = HibernateUtils.getSession(); Query<People> query = session.createQuery(" from People ", People.class); List<People> list = query.list(); list.forEach(people -> System.out.println(people.getName()+"=="+people.getGoodsEntities().size())); } ``` console: ```mysql Hibernate: select people0_.id as id1_4_, people0_.name as name2_4_, people0_.year as year3_4_ from people people0_ Hibernate: select goodsentit0_.pid as pid4_3_1_, goodsentit0_.id as id1_3_1_, goodsentit0_.id as id1_3_0_, goodsentit0_.goods_name as goods_na2_3_0_, goodsentit0_.goods_price as goods_pr3_3_0_, goodsentit0_.pid as pid4_3_0_ from goods goodsentit0_ where goodsentit0_.pid in ( select people0_.id from people people0_ ) ``` ##### batch-size (可选, 默认为1) 指定通过延迟加载取得集合实例的批处理块大小("batch size")。注:lazy属性默认设置true ```java <!--batch-size (可选, 默认为1) 指定通过延迟加载取得集合实例的批处理块大小("batch size")。 --> <set name="goodsEntities" batch-size="2" lazy="false" cascade="save-update" > <key> <column name="pid"></column> </key> <one-to-many class="com.hibernate.pojo.GoodsEntity"/> </set> ``` sql体现:数据库的数据主表四条不同的数据,将四条数据分为两批数据进行处理,sql改变,提高查询效率 ```mysql Hibernate: select people0_.id as id1_4_, people0_.name as name2_4_, people0_.year as year3_4_ from people people0_ Hibernate: select goodsentit0_.pid as pid4_3_1_, goodsentit0_.id as id1_3_1_, goodsentit0_.id as id1_3_0_, goodsentit0_.goods_name as goods_na2_3_0_, goodsentit0_.goods_price as goods_pr3_3_0_, goodsentit0_.pid as pid4_3_0_ from goods goodsentit0_ where goodsentit0_.pid in ( ?, ? ) 小王==2 张三==2 Hibernate: select goodsentit0_.pid as pid4_3_1_, goodsentit0_.id as id1_3_1_, goodsentit0_.id as id1_3_0_, goodsentit0_.goods_name as goods_na2_3_0_, goodsentit0_.goods_price as goods_pr3_3_0_, goodsentit0_.pid as pid4_3_0_ from goods goodsentit0_ where goodsentit0_.pid in ( ?, ? ) 李四==2 w5==1 ``` 设置为3时 ```mysql Hibernate: select people0_.id as id1_4_, people0_.name as name2_4_, people0_.year as year3_4_ from people people0_ Hibernate: select goodsentit0_.pid as pid4_3_1_, goodsentit0_.id as id1_3_1_, goodsentit0_.id as id1_3_0_, goodsentit0_.goods_name as goods_na2_3_0_, goodsentit0_.goods_price as goods_pr3_3_0_, goodsentit0_.pid as pid4_3_0_ from goods goodsentit0_ where goodsentit0_.pid in ( ?, ?, ? ) 小王==2 张三==2 李四==2 Hibernate: select goodsentit0_.pid as pid4_3_1_, goodsentit0_.id as id1_3_1_, goodsentit0_.id as id1_3_0_, goodsentit0_.goods_name as goods_na2_3_0_, goodsentit0_.goods_price as goods_pr3_3_0_, goodsentit0_.pid as pid4_3_0_ from goods goodsentit0_ where goodsentit0_.pid=? w5==1 ``` 参考资料 ```java many to many 序号 属性 说明 1 name 属性名 2 column (可选): 外间字段名。它也可以通过嵌套的元素指定。 3 class (可选 - 默认是通过反射得到属性类型): 关联的类的名字。 4 cascade (级联) (可选): 指明哪些操作会从父对象级联到关联的对象。 5 fetch (可选 - 默认为  select ): 在外连接抓取(outer-join fetching)和序列选择抓取(sequential select fetching)两者中选择其一。 6 update, insert (可选 - defaults to  true ) 指定对应的字段是否包含在用于UPDATE   和/或  INSERT   的SQL语句中。如果二者都是false ,则这是一个纯粹的 “外源性(derived)”关联,它的值是通过映射到同一个(或多个)字段的某些其他属性得到 或者通过trigger(触发器)、或其他程序。 7 property-ref (可选) 指定关联类的一个属性,这个属性将会和本外键相对应。 如果没有指定,会使用对方关联类的主键。 8 access (可选 - 默认是  property ): Hibernate用来访问属性的策略。 9 unique (可选): 使用DDL为外键字段生成一个唯一约束。此外, 这也可以用作property-ref 的目标属性。这使关联同时具有 一对一的效果。 10 not-null (可选): 使用DDL为外键字段生成一个非空约束。 11 optimistic-lock (可选 - 默认为  true ): 指定这个属性在做更新时是否需要获得乐观锁定(optimistic lock)。 换句话说,它决定这个属性发生脏数据时版本(version)的值是否增长。 12 lazy (可选 - 默认为  proxy ): 默认情况下,单点关联是经过代理的。lazy="true" 指定此属性应该在实例变量第一次被访问时应该延迟抓取(fetche lazily)(需要运行时字节码的增强)。lazy="false" 指定此关联总是被预先抓取。 13 not-found (可选 - 默认为  exception ): 指定外键引用的数据不存在时如何处理:  ignore 会将数据不存在作为关联到一个空对象(null)处理。 14 entity-name (optional): 被关联的类的实体名。 ``` ``` set节点有以下属性(摘自Hibernate文档): 序号 属性 说明 1 name 集合属性的名称 2 table (可选,默认为属性的名称)这个集合表的名称(不能在一对多的关联关系中使用) 3 schema (可选) 表的schema的名称, 他将覆盖在根元素中定义的schema 4 lazy (可选,默认为false) lazy(可选--默认为false) 允许延迟加载(lazy initialization )(不能在数组中使用) 5 inverse (可选,默认为false) 标记这个集合作为双向关联关系中的方向一端。 6 cascade (可选,默认为none) 让操作级联到子实体all: 所有情况下均进行关联操作,即save-update和delete。 none: 所有情况下均不进行关联操作。这是默认值。  save-update: 在执行save/update/saveOrUpdate时进行关联操作。  delete: 在执行delete 时进行关联操作。 7 sort (可选)指定集合的排序顺序, 其可以为自然的(natural)或者给定一个用来比较的类。 8 order-by (可选, 仅用于jdk1.4) 指定表的字段(一个或几个)再加上asc或者desc(可选), 定义Map,Set和Bag的迭代顺序  9 where (可选) 指定任意的SQL where条件, 该条件将在重新载入或者删除这个集合时使用(当集合中的数据仅仅是所有可用数据的一个子集时这个条件非常有用)  10 outer-join (可选)指定这个集合,只要可能,应该通过外连接(outer join)取得。在每一个SQL语句中, 只能有一个集合可以被通过外连接抓取(译者注: 这里提到的SQL语句是取得集合所属类的数据的Select语句)  11 batch-size (可选, 默认为1) 指定通过延迟加载取得集合实例的批处理块大小("batch size")。  12 access (可选-默认为属性property):Hibernate取得属性值时使用的策略 ``` #### Session一级缓存测试 ```java public static void main(String[] args) { test3(); } public static void test3(){ Session session = HibernateUtils.getSession(); People people = session.get(People.class,3); Transaction tran = session.beginTransaction(); people.setName("QQQQQXQ"); session.flush();//默认会提交事务,将持久态的对象持久化到数据库中 // tran.commit(); session.close(); } public static void test2(){ Session session = HibernateUtils.getSession(); System.out.println(session.hashCode()); People people = new People(); people.setId(3); System.out.println(">>>>>---1--"+student1.getSname()); session.refresh(student1);//和数据库端同步 System.out.println(">>>>>---2--"+student1.getSname()); session.close(); } /** * 一级缓存 Session级别的缓存 * 验证方式:是否发起SQL查询 */ public static void test1(){ Session session = HibernateUtils.getSession(); System.out.println(session.hashCode()); People people = session.get(People.class,3); System.out.println("********************"); //从session缓存中移除对象 //session.evict(student1); //清空缓存 session.clear(); People people2 = session.get(People.class,3); System.out.println(people.hashCode()+"==="+people2.hashCode()); session.close(); } ``` #### 关于Hibernate的查询语句与mybatis的感受 hibernate由于时全自动化的orm框架,所以在查询时为了避免字段的重复,默认给每一个字段提供了一个别名,页有效的避免了与数据库的关键字相同的查询错误。而mybatis由于是属于半自动化的框架,在提供灵活性的sql语句查询时,不可避免地会遇到hibernate相同的问题,提供的结果集映射的别名配置,框架更加灵活,相较于hibernate。orm框架所有的查询都是在查询的结果集上进行进一层的封装,因此,别名机制是非常有利于大量数据的查询的区分的。(ps:现在才感受到各级别软件的设计之美,赞) 文章代码地址已上传gitub:https://github.com/yunnuoyang/hzitsummerexperience.git其中的hibernate01的module中有部分测试代码<file_sep>/spring/src/main/java/com/spring/aop/aspectj/LogAdvice.java package com.spring.aop.aspectj; import org.aspectj.lang.JoinPoint; import java.util.Arrays; //切面类 public class LogAdvice { //自定义增强的方法内容 public void myBefore(JoinPoint point){ //获取方法名代理对象的方法名 String methodName = point.getSignature().getName(); Object[] params = point.getArgs(); //类的全路径名 String clsName = point.getTarget().getClass().getName(); // String kind = point.getKind(); System.out.println(methodName+"******前置通知********|"+ Arrays.toString(params)+""+kind+"|=="+clsName); } public void myAfter(){ System.out.println("*********最终通知*******"); } public void myAfterReturn(){ System.out.println("*********后置通知*******"); } }
cc04d4a057f081ab8e1347d2206aaacbcc255194
[ "Markdown", "Java", "INI" ]
44
Java
yunnuoyang/hzitsummerexperience
dfa97c57b448293b93c4a2812b974a3c2976550b
06efb8857bb6820f6756136374a1d93976f05beb
refs/heads/main
<file_sep># Movie-Search-App A movie search application built with springboot for searching movies of your choice <file_sep>package com.moviesreachwithmongdb.repository; import com.moviesreachwithmongdb.model.Movie; import org.springframework.data.mongodb.repository.MongoRepository; public interface MovieRepository extends MongoRepository<Movie,String> { } <file_sep>package com.moviesreachwithmongdb.controller; import com.moviesreachwithmongdb.model.Movie; import com.moviesreachwithmongdb.repository.MovieRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.Optional; @RestController public class MovieController { @Autowired private MovieRepository movieRepo; @RequestMapping(method = RequestMethod.POST, value = "/movie") //Post /Movie public ResponseEntity<String> createMovie(@RequestBody Movie movie) { try { movieRepo.save(movie); return new ResponseEntity("Successfully added movie" + movie.getTitle(), HttpStatus.OK); } catch (Exception e) { return new ResponseEntity(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); } } // GET /movie @RequestMapping(method = RequestMethod.GET, value = "/movie") public ResponseEntity getAllMovies() { List<Movie> movies = movieRepo.findAll(); if (movies.size() > 0) { return new ResponseEntity(movies, HttpStatus.OK); } else { return new ResponseEntity("No movies found", HttpStatus.NOT_FOUND); } } // Delete /movie/{/id} @RequestMapping(method = RequestMethod.DELETE, value = "/movie/{id}") public ResponseEntity deleteMovieById(@PathVariable("id") String id) { try { movieRepo.deleteById(id); return new ResponseEntity("Successfully deleted movie with id " + id, HttpStatus.OK); } catch (Exception e) { return new ResponseEntity(e.getMessage(), HttpStatus.NOT_FOUND); } } //PUT /movie/{/id} @RequestMapping(method = RequestMethod.PUT, value = "/movie/{id}") public ResponseEntity updateById(@PathVariable("id") String id, @RequestBody Movie newMovie) { Optional<Movie> movieOptional = movieRepo.findById(id); if (movieOptional.isPresent()) { Movie movieToSave = movieOptional.get(); movieToSave.setTitle(newMovie.getTitle()); movieToSave.setRating(newMovie.getRating()); movieToSave.setGenre(newMovie.getGenre()); movieRepo.save(movieToSave); return new ResponseEntity("Update Movie with id" + id + "found", HttpStatus.NOT_FOUND); } else { return new ResponseEntity("No Movie with id"+id+" found",HttpStatus.NOT_FOUND); } } }
9c0634ae2a9e95b4fa2f307bf02031d8534db74b
[ "Markdown", "Java" ]
3
Markdown
Peterbamidele/Movie-Search-App
33214e1b24d18c99e00afe621ad682d9fb322785
1136803bee2759fd34ba57a0b85ed5ca5b5c2c00
refs/heads/master
<file_sep>from flask import Flask, send_file from src.predict import predict from tensorflow.keras.models import load_model app = Flask(__name__) @app.route("/") def hello(): return "Working!" @app.route("/getGraph", methods=['GET']) def get_graph(): model = load_model('./models/model.h5') predict('./data/bitcoin.new.csv', model) return send_file('images/prediction.png', mimetype='image/png') if __name__ == "__main__": app.run(host="0.0.0.0", debug=True)<file_sep>import requests import pytz import sys import os import csv import pandas as pd from datetime import datetime, timedelta from dateutil.relativedelta import relativedelta from time import sleep from random import randint URL = "https://production.api.coindesk.com/v2/price/values/" COIN = "BTC" API_TIMEZONE = pytz.timezone("Europe/Madrid") CODE = f"{COIN}_USD" DATA_FOLDER = "data" DATA_FILE = "bitcoin.csv" DATA_PATH = os.path.join(DATA_FOLDER, DATA_FILE) DEFAULT_START_DATE = datetime.now(tz=API_TIMEZONE) - relativedelta(month=1) DEFAULT_END_DATE = datetime.now(tz=API_TIMEZONE) def wait(): sleep_seconds = randint(5,7) sleep(sleep_seconds) def write_dataframe_to_csv(dataframe, path=DATA_PATH): index_col = "Date" dataframe = dataframe.drop_duplicates(index_col).sort_values(by=[index_col]) return dataframe.to_csv(path, sep=',', line_terminator='\n', index=False) def read_dataframe_from_csv(path=DATA_PATH): return pd.read_csv(path, sep=',') def dates_query_params(start_date, end_date): return f"start_date={start_date}&end_date={end_date}" def fetch_hourly_between_dates(start_date=DEFAULT_START_DATE, end_date=DEFAULT_END_DATE): try: start_date = start_date.strftime("%Y-%m-%dT%H:%m") end_date = end_date.strftime("%Y-%m-%dT%H:%m") date_param = dates_query_params(start_date, end_date) fetch_url = f"{URL}{COIN}?{date_param}" print(fetch_url) response = requests.get(fetch_url) data = response.json().get("data") return data except: print("Cannot fetch more data") return def format_timestamp(timestamp): datetime_wo_timezone = datetime.fromtimestamp(timestamp//1000.0) datetime_localized = API_TIMEZONE.localize(datetime_wo_timezone) return datetime_localized.strftime("%Y-%m-%d %H:%M") def parse_response_data(entries, **kwargs): if not entries: raise ValueError("No entries provided") entries = [(format_timestamp(ts), price) for ts, price, *r in entries] return entries def run_between_dates(start_date, end_date): raw_data = fetch_hourly_between_dates(start_date, end_date) if raw_data: parsed_data = parse_response_data(**raw_data) return parsed_data # return list of lists else: return [] def run_monthly(end_date): #print((end_date - relativedelta(months=1), end_date)) return run_between_dates(end_date - relativedelta(months=1), end_date) def run_for_last_n_months(n_months=1): data = [] for n in range(n_months): data.extend(run_monthly( DEFAULT_END_DATE - relativedelta(months=n) )) wait() return data def populate(): n_months = 24 #n_months = 3 records = run_for_last_n_months(n_months) dataframe = pd.DataFrame.from_records(records, columns=['Date', 'Close']) write_dataframe_to_csv(dataframe) def check_data(): df = read_dataframe_from_csv() for index in range(len(df)): try: start = pd.to_datetime(df['Date'][index]) end = pd.to_datetime(df['Date'][index+1]) diff_seconds = (end - start).total_seconds() diff_expected = 3600.0 #if diff_seconds != diff_expected: if diff_seconds < diff_expected - 100 or diff_seconds > diff_expected + 100: print(f"Error diffing datetime <{diff_seconds}> between {index}-{index+1}") except KeyError: return except Exception as e: raise e def update(): # read latest_data df = read_dataframe_from_csv() # latest_date = pd.to_datetime(df["datetime"].iloc[-1]).to_pydatetime() # get latest_date # get time_diff # (if time_diff > 1 month) # n_months between latest_date and now # fetch latest_n_months # else fetch between dates(latest_date, now) records = run_monthly(DEFAULT_END_DATE) dataframe = df.append(pd.DataFrame.from_records(records, columns=['Date', 'Close'])) print(dataframe.tail()) write_dataframe_to_csv(dataframe) def print_help(): print(f"Usage: {sys.argv[0]} <command>") print("Commands: \n\t populate: populate data \n\t update: fetch latest data \n\t check: check current data for failing rows") if __name__ == "__main__": try: cmd = sys.argv[1] except: print_help() exit(1) if cmd == "populate": populate() if cmd == "update": update() if cmd == "check": check_data() <file_sep>Flask basic server ### Run in local 1. Install pipenv * sudo apt-get update * sudo apt-get install pipenv 2. Run: * pipenv shell * pipenv install 3. Run: * pipenv run python3 init.py ### Run with Docker 1. Build image: `docker build -t api-flask .` 2. Run container: `docker run -p 5000:5000 api-flask` * With volume: `docker run -p 5000:5000 -v "$(pwd):/app" api-flask` ### Dataset generation __The csv has a header row__, be careful - `src/coindesk.py populate` to populate data csv - `src/coindesk.py update` to update with latest data - `src/coindesk.py check` to check diff between dates * Alternative dataset with script: - `src/bitflyer.py` to populate data csv ## Train model from scratch `pipenv shell` Open the Python terminal and run: ``` from model import get_model from train import train model = get_model() train(csv_path='./data/bitcoin.new.csv', model=model, num_epochs=50) model.save('./models/model.h5') ``` <file_sep>import csv import datetime import os import requests import time print("Starting") start = 1577437200000 end = int(round(time.time() * 1000)) product_code = 'BTC_USD' output = f'data/bitcoin.csv' url = f"https://bitflyer.com/api/trade/chartdata?product_code={product_code}&start={start}&end={end}" r = requests.get(url) print(f"got response: {r.status_code} from {url}") data = r.json() if not os.path.exists('output'): os.makedirs('my_folder') wtr = csv.writer(open(output, 'w'), delimiter=',', lineterminator='\n') for row in data: date = datetime.datetime.fromtimestamp(row[0]/1000.0) date = date.strftime("%Y-%m-%d %H:%M") wtr.writerow([date, product_code, row[1]]) print(f"finished, check file: {output}") <file_sep>from keras.models import Sequential from keras.optimizers import Adam from keras.layers import Dense, LSTM, LeakyReLU, Dropout def get_model(num_units: int = 64, learning_rate: float = 1e-4, activation_function: str = 'sigmoid'): adam = Adam(lr=learning_rate) loss_function = 'mean_absolute_error' regressor = Sequential() # First LSTM layer with Dropout regularisation regressor.add(LSTM(units=50, return_sequences=True, input_shape=(None,1))) regressor.add(Dropout(0.2)) # Second LSTM layer regressor.add(LSTM(units=50, return_sequences=True)) regressor.add(Dropout(0.2)) # Third LSTM layer regressor.add(LSTM(units=50, return_sequences=True)) regressor.add(Dropout(0.5)) # Fourth LSTM layer regressor.add(LSTM(units=50)) regressor.add(Dropout(0.5)) # The output layer regressor.add(Dense(units=1)) # Compiling the RNN regressor.compile(optimizer=adam, loss=loss_function) return regressor<file_sep>FROM python:3.7 WORKDIR /app COPY . . RUN pip install pipenv RUN pipenv lock --requirements > requirements.txt RUN pip install -r requirements.txt EXPOSE 5000 CMD ["python", "init.py"] <file_sep>import numpy as np import pandas as pd from sklearn.preprocessing import MinMaxScaler from src.utils import univariate_data def train( csv_path: str, model, batch_size: int = 10, num_epochs: int = 5, past_history: int = 72, future_target: int = 0, train_split_ratio: float = 1.0, validation_split_ratio: float = 0.0 ): data = pd.read_csv(csv_path, names=['Date', 'Close']) data = data.sort_values('Date') price = data[['Close']] # Normalize data min_max_scaler = MinMaxScaler() norm_data = min_max_scaler.fit_transform(price.values) # Data split train_split = int(len(norm_data) * train_split_ratio) x_train, y_train = univariate_data(norm_data, 0, train_split, past_history, future_target) x_test, y_test = univariate_data(norm_data, train_split, None, past_history, future_target) history = model.fit( x_train, y_train, validation_split=validation_split_ratio, batch_size=batch_size, epochs=num_epochs, shuffle=False ) loss = history.history['loss'] if validation_split_ratio > 0: val_loss = history.history['val_loss'] return loss, val_loss return loss, 0 <file_sep>import os import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from sklearn.preprocessing import MinMaxScaler from src.utils import univariate_data, get_test_data def predict( csv_path: str, model, past_history: int = 72, future_target: int = 0, num_hours_past: int = 120 ): data = pd.read_csv(csv_path, names=['Date', 'Close']) data = data.sort_values('Date') price = data[['Close']] # Normalize data min_max_scaler = MinMaxScaler() norm_data = min_max_scaler.fit_transform(price.values) _, y_test = univariate_data(norm_data, int(len(norm_data) - num_hours_past), None, past_history, future_target) x_test = get_test_data(norm_data, int(len(norm_data) - num_hours_past), past_history) original = pd.DataFrame(min_max_scaler.inverse_transform(y_test)) predictions = pd.DataFrame(min_max_scaler.inverse_transform(model.predict(x_test))) plt.clf() ax = sns.lineplot(x=original.index, y=original[0], label="Real Data", color='royalblue') ax = sns.lineplot(x=predictions.index, y=predictions[0], label="Prediction", color='tomato') ax.set_title('Bitcoin price', size = 14, fontweight='bold') ax.set_xlabel("Hours", size = 14) ax.set_ylabel("Cost (USD)", size = 14) ax.set_xticklabels('', size=10) #ax.get_figure().savefig('../images/prediction.png') plt.savefig(os.getcwd() + '/images/prediction.png')
d65158cae0077c30343c8194296aff66299e4b91
[ "Markdown", "Python", "Dockerfile" ]
8
Python
Matacristos/api-flask
43346d19f8553a93876f983ebcca882e08d8b49a
3fee48bb792f08339c2358c67b0880424ec92ccd
refs/heads/master
<repo_name>erikkukamezou/kadai7-25-2<file_sep>/config/unicorn.rb worker_processes Integer(ENV["WEB_CONCURRENCY"] || 3) timeout 15 preload_app true worker_processes 4 listen 'unix:///tmp/nginx.socket', backlog: 1024 before_fork do |server,worker| FileUtils.touch('/tmp/app-initialized') end
e694dd20ca0514daa44b7b452619aff69fc73180
[ "Ruby" ]
1
Ruby
erikkukamezou/kadai7-25-2
ffb1e362fecd73740267927336a8d3503854ec22
0035915021f7aa865194d8b1b7b74c9509226aba
refs/heads/master
<file_sep>class NumberCleaner def self.clean(number) number.gsub(/\D+/, '') end end<file_sep>class LuhnValidator def initialize(number) @number = number end def valid? number_sum % 10 == 0 end private def number_sum @number.split('').reverse.map.each_with_index do |number, i| ((i + 1).even? ? (number.to_i * 2) : number).to_s.split('') end.flatten.map(&:to_i).reduce(:+) end end<file_sep>require 'luhn_credit_card/pretty_printer' class TextFilePrinter def self.parse(file_path) File.readlines(file_path).map do |number| PrettyPrinter.print( LuhnCreditCard.new(number) ) end.join("\n") end end<file_sep>lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) Gem::Specification.new do |spec| spec.name = "luhn_credit_card" spec.version = '0.0.2' spec.authors = ["<NAME>"] spec.email = ["<EMAIL>"] spec.summary = %q{Credit card validations using Luhn Algorithm.} spec.description = %q{It's a simple tool that provides helper methods for credit card number validations using Luhn Algorithm.} spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0") spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.require_paths = ["lib"] spec.add_development_dependency "bundler", "~> 1.7" spec.add_development_dependency 'rspec', '~> 3.1', '>= 3.1.0' spec.add_development_dependency 'simplecov', '~> 0.9' end <file_sep>class PrettyPrinter def self.print(card) "#{card.type}: #{card.number} (#{card.status})" end end<file_sep>luhn_credit_card ===== ### Usage ``` gem install luhn_credit_card ``` #### As a single number validator: ```ruby credit_card = LuhnCreditCard.new('4111111111111111') credit_card.type # => 'VISA' credit_card.status # => :valid credit_card.valid? # => true ``` #### As a text file with numbers parser: ``` 4111111111111111 4111111111111 4012888888881881 378282246310005 6011111111111117 5105105105105100 5105 1051 0510 5106 9111111111111111 ``` ```ruby LuhnCreditCard.pretty_print_from_file(file_path) # => "VISA: 4111111111111111 (valid) VISA: 4111111111111 (invalid) VISA: 4012888888881881 (valid) AMEX: 378282246310005 (valid) Discover: 6011111111111117 (valid) MasterCard: 5105105105105100 (valid) MasterCard: 5105105105105106 (invalid) Unknown: 9111111111111111 (invalid)" ``` ### Development ``` gem install bundler bundle install rspec spec ``` <file_sep>require 'luhn_credit_card/number_cleaner' require 'luhn_credit_card/text_file_printer' require 'luhn_credit_card/type_finder' require 'luhn_credit_card/luhn_validator' class LuhnCreditCard attr_reader :number def self.pretty_print_from_file(file_path) begin TextFilePrinter.parse(file_path) rescue => e # Log the error nil end end def initialize(number) @number = NumberCleaner.clean(number) end def type TypeFinder.for(number) end def valid? LuhnValidator.new(number).valid? end def status valid? ? :valid : :invalid end end<file_sep>class TypeFinder CHARACTERISTICS = { 'AMEX' => { begins_with: ['34', '37'], length: [15] }, 'Discover' => { begins_with: ['6011'], length: [16] }, 'MasterCard' => { begins_with: ('51'..'55').to_a, length: [16] }, 'VISA' => { begins_with: ['4'], length: [13, 16] } } def self.for(number) CHARACTERISTICS.detect do |card, settings| return card if settings[:begins_with].detect { |n_start| number.start_with? n_start } && settings[:length].include?(number.size) end 'Unknown' end end<file_sep>require 'simplecov' SimpleCov.start require 'rspec' require 'luhn_credit_card' require 'luhn_credit_card/text_file_printer'<file_sep>require 'spec_helper' describe LuhnCreditCard do context 'initial attributes' do describe '#number' do context 'when spaced number' do let(:credit_card) { LuhnCreditCard.new('3782 8224 6310 005') } it 'returns plain number' do expect(credit_card.number).to eq '378282246310005' end end context 'when number ends with \n' do let(:credit_card) { LuhnCreditCard.new('378282246310005\n') } it 'returns plain number' do expect(credit_card.number).to eq '378282246310005' end end context 'when spaced number and ends with \n' do let(:credit_card) { LuhnCreditCard.new('3782 8224 6310 005\n') } it 'returns plain number' do expect(credit_card.number).to eq '378282246310005' end end end end describe '#valid?' do context 'AMEX' do it 'when valid' do credit_card = LuhnCreditCard.new('3782 8224 6310 005') expect(credit_card.valid?).to eq true end it 'when invalid' do credit_card = LuhnCreditCard.new('3782 8224 6310 0051') expect(credit_card.valid?).to eq false end end context 'VISA' do it 'when valid' do credit_card = LuhnCreditCard.new('4111111111111111') expect(credit_card.valid?).to eq true end it 'when invalid' do credit_card = LuhnCreditCard.new('4111111111111') expect(credit_card.valid?).to eq false end end context 'MasterCard' do it 'when valid' do credit_card = LuhnCreditCard.new('5105105105105100') expect(credit_card.valid?).to eq true end it 'when invalid' do credit_card = LuhnCreditCard.new('5105105105105106') expect(credit_card.valid?).to eq false end end context 'Discover' do it 'when valid' do credit_card = LuhnCreditCard.new('6011111111111117') expect(credit_card.valid?).to eq true end it 'when invalid' do credit_card = LuhnCreditCard.new('6011 1111 1111 1127') expect(credit_card.valid?).to eq false end end end describe '#status' do let(:number) { 'whatever 123' } let(:credit_card) { LuhnCreditCard.new(number) } it 'when true' do allow(credit_card).to receive(:valid?).and_return(true) expect(credit_card.status).to eq :valid end it 'when false' do allow(credit_card).to receive(:valid?).and_return(false) expect(credit_card.status).to eq :invalid end end describe '#type' do it 'when AMEX' do credit_card = LuhnCreditCard.new('378282246310005') expect(credit_card.type).to eq 'AMEX' end it 'when Discover' do credit_card = LuhnCreditCard.new('6011111111111117') expect(credit_card.type).to eq 'Discover' end it 'when MasterCard' do credit_card = LuhnCreditCard.new('5105 1051 0510 5106') expect(credit_card.type).to eq 'MasterCard' end it 'when VISA' do credit_card = LuhnCreditCard.new('4012888888881881') expect(credit_card.type).to eq 'VISA' end it 'when Unknown' do credit_card = LuhnCreditCard.new('9111111111111111') expect(credit_card.type).to eq 'Unknown' end end describe '.pretty_print_from_file(path)' do context 'when path is provided' do let(:file_path) do File.join(File.dirname(__FILE__), '..', 'support', 'credit_cards.txt') end it 'returns formated string with validation info' do expect(LuhnCreditCard.pretty_print_from_file(file_path)).to eq( "VISA: 4111111111111111 (valid) VISA: 4111111111111 (invalid) VISA: 4012888888881881 (valid) AMEX: 378282246310005 (valid) Discover: 6011111111111117 (valid) MasterCard: 5105105105105100 (valid) MasterCard: 5105105105105106 (invalid) Unknown: 9111111111111111 (invalid)" ) end end context 'when path is not provided' do it 'returns nil' do expect(LuhnCreditCard.pretty_print_from_file(nil)).to be_nil end end context 'when path from wrong format txt file is provided' do let(:file_path) do File.join(File.dirname(__FILE__), '..', 'support', 'crazy_file.txt') end it 'returns nil' do expect(LuhnCreditCard.pretty_print_from_file(file_path)).to be_nil end end end end
65b5ed7f739e295b6de6732b351208ea78abd60f
[ "Markdown", "Ruby" ]
10
Ruby
kln/luhn_credit_card
de862e53afea654efe134d4e9383531fdb976333
b1ab849adbee1acd0e8934007894c5ebc177776a
refs/heads/master
<repo_name>zvadym/vue-chat<file_sep>/src/store/modules/auth/mutations.js export default { setAccessToken(state, token) { state.jwtAccess = token }, setRefreshToken(state, token) { state.jwtRefresh = token }, clearAuthCredentials(state) { state.jwtAccess = null state.jwtRefresh = null }, updateTimeoutId(state, timeoutId) { state.timeoutId = timeoutId }, setAuthUser(state, uid) { state.authUserId = uid } } <file_sep>/src/store/modules/socket/index.js import Vue from 'vue' import WS from '@/services/websocket/index' export default { namespaced: false, state: { isConnected: false, message: '', reconnectError: false }, mutations: { SOCKET_ONOPEN(state, event) { if (!state.isConnected) { Vue.prototype.$socket = event.currentTarget state.isConnected = true } }, SOCKET_ONCLOSE(state) { Vue.prototype.$socket = null state.isConnected = false }, SOCKET_ONERROR(state, event) { console.error(state, event) }, SOCKET_ONMESSAGE(state, message) { // default handler called for all methods // Notice: All events handled by `passToStoreHandler` state.message = message }, SOCKET_RECONNECT(state, count) { // mutations for reconnect methods console.info(state, count) }, SOCKET_RECONNECT_ERROR(state) { state.reconnectError = true } }, actions: { socketConnect({ rootGetters }) { WS.connect(rootGetters['auth/jwtAccess']) }, socketDisconnect() { WS.disconnect() }, socketOnEvent({ dispatch }, event) { // It works like if it set `VueNativeSock.format=json` // but in this way it's possible to control things // and, as it is done below, add prefix to action name if (event.isTrusted && event.data) { const data = JSON.parse(event.data) if (data.action) { let action = 'socket__' + data.action if (data.namespace) { action = data.namespace + '/' + action } dispatch(action, data.data, { root: true }) } } }, socketConnectToRoom(context, roomId) { WS.connectToRoom(roomId) }, socketConnectToMember(context, memberId) { WS.connectToMember(memberId) } } } <file_sep>/src/services/websocket/index.js import Vue from 'vue' const vm = new Vue() export default { connect(token) { vm.$connect(process.env.VUE_APP_WEBSOCKET_BASE_URL + '?token=' + token) }, disconnect() { vm.$disconnect() }, connectToRoom(id) { vm.$socket.send( JSON.stringify({ type: 'room-join', id }) ) }, connectToMember(id) { vm.$socket.send( JSON.stringify({ type: 'member-join', id }) ) } } <file_sep>/src/store/modules/messenger/mutations.js export default { // // **** Rooms // addRoom(state, data) { state.rooms.push(data) }, updateRoom(state, data) { state.rooms = [ ...state.rooms.filter(element => element.id !== data.id), data ] }, setActiveRoom(state, id) { state.activeRoomId = id }, // // **** Messages // addMessage(state, data) { state.messages.push(data) }, updateMessage(state, data) { state.messages = [ ...state.messages.filter(element => element.id !== data.id), data ] } } <file_sep>/src/store/modules/users/actions.api.js import api from '@/services/api/index' export default { apiGetUsers({ dispatch }) { api.getAllUsers().then(data => { let promises = [] data.forEach(item => promises.push(dispatch('addUser', { data: item }))) return Promise.all(promises) }) }, apiGetUser({ commit, dispatch, getters }, userId) { if (!getters['getById'](userId) && !getters['isLoading'](userId)) { console.log('apiGetUser', userId) commit('addToLoadingQueue', userId) return api.getUserData(userId).then(payload => { commit('removeFromLoadingQueue', payload.id) return dispatch('addUser', { data: payload }) }) } }, apiTouchUser() { api.updateMyStatus() } } <file_sep>/src/store/index.js import Vue from 'vue' import Vuex from 'vuex' import { createStore } from 'vuex-extensions' import auth from './modules/auth/index' import messenger from './modules/messenger/index' import socket from './modules/socket/index' import users from './modules/users/index' Vue.use(Vuex) export default createStore(Vuex.Store, { strict: true, modules: { auth, messenger, socket, users }, state: {}, mutations: {}, actions: {} }) <file_sep>/src/store/modules/messenger/getters.js import _ from 'lodash' export default { rooms: state => state.rooms, roomsOrdered: state => _.orderBy(state.rooms, ['updatedAt'], ['desc']), getRoomById: state => cid => state.rooms.find(c => c.id === +cid), getRoomByTitle: state => title => state.rooms.find(c => c.title === title), activeRoom: state => state.rooms.find(i => i.id === state.activeRoomId), roomMessages: state => rid => _.orderBy( state.messages.filter(m => m.roomId === rid), ['createdAt'], ['asc'] ), getMessageById: state => mid => state.messages.find(c => c.id === +mid) } <file_sep>/src/store/modules/messenger/actions.js import roomActions from './actions.room' import messageActions from './actions.message' import socketActions from './actions.socket' export default { ...roomActions, ...messageActions, ...socketActions } <file_sep>/README.md # Vue messenger It's my side project written for practice. It's a simple slack-like messenger with features like public/private channels and notifications. ![Vue-messenger](https://raw.githubusercontent.com/zvadym/messenger-frontend/master/public/img/screen.png) ## Details - **Vue + Vuex** - base - **JSON Web Tokens** - used for authorization (see my [vue-jwt proof of concept](https://github.com/zvadym/vue-jwt-client) repo) - **Vuetify** - used as UI framework - **Django REST framework** - used for API - **Django Channels2** - used for websocket messaging <file_sep>/src/store/modules/auth/index.js import actions from './actions' import getters from './getters' import mutations from './mutations' export default { namespaced: true, state: { authUserId: null, jwtAccess: null, jwtRefresh: null, timeoutId: null }, getters, actions, mutations } <file_sep>/src/store/modules/users/mutations.js export default { addToLoadingQueue(state, uid) { state.usersLoading.push(uid) }, removeFromLoadingQueue(state, uid) { state.usersLoading.splice(state.usersLoading.indexOf(uid), 1) }, addUser(state, user) { state.users.push(user) }, updateUser(state, user) { state.users = [ ...state.users.filter(element => element.id !== user.id), user ] } } <file_sep>/src/store/modules/users/actions.socket.js import { dataToModel } from './actions' import bus from '@/bus' export default { socket__updateUser({ commit }, payload) { commit('updateUser', dataToModel(payload)) }, socket__createUser({ dispatch }, payload) { bus.$emit( 'flash', 'A new member is joined - ' + dataToModel(payload).fullName, 'info' ) return dispatch('addUser', { data: payload }) } } <file_sep>/src/store/modules/auth/actions.js import jwtDecode from 'jwt-decode' import bus from '@/bus' import api from '@/services/api/index' export default { login({ dispatch }, { email, password }) { return api .login({ email, password }) .then(({ accessToken, refreshToken }) => { window.localStorage.setItem('auth_refresh_token', refreshToken) return dispatch('updateRefreshToken', refreshToken).then(() => dispatch('updateAccessToken', accessToken) ) }) .catch(error => { throw error // (!) Also see axios config for basic error handling }) }, logout({ commit, state }) { return api.logout({ refreshToken: state.jwtRefresh }).then(() => { commit('clearAuthCredentials') window.localStorage.removeItem('auth_refresh_token') return true }) }, refreshAccessToken({ dispatch, state }) { return api .refresh({ refreshToken: state.jwtRefresh }) .then(response => { bus.$emit('flash', 'Access token is updated') return dispatch('updateAccessToken', response.data.access) }) .catch(() => { throw new Error('Bad refresh token') }) }, verify({ state }) { return api.verify({ refreshToken: state.jwtRefresh }) }, updateAccessToken({ commit, dispatch }, token) { commit('setAccessToken', token) // Set current AuthUser return dispatch('setAuthUser', { id: jwtDecode(token).user_id }).then(() => // Refresh "access" token when it expires dispatch('setRefreshTimer', new Date(jwtDecode(token).exp * 1000)).then( () => // Open socket dispatch('socketConnect', null, { root: true }) ) ) }, updateRefreshToken({ commit }, token) { commit('setRefreshToken', token) return token }, setRefreshTimer({ state, commit, dispatch }, expirationTime) { clearTimeout(state.timeoutId) const timeoutId = setTimeout(() => { bus.$emit('flash', 'Access token is expired') dispatch('refreshAccessToken') }, expirationTime - new Date()) return commit('updateTimeoutId', timeoutId) }, setAuthUser({ commit }, { id }) { commit('setAuthUser', id) }, tryAutoLogin({ commit, dispatch }) { const refreshToken = window.localStorage.getItem('auth_refresh_token') if (!refreshToken) { return } const expirationDate = new Date(jwtDecode(refreshToken).exp * 1000) if (new Date() >= expirationDate) { bus.$emit('flash', 'Autologin is failed. Tokes is expired.', 'warning') window.localStorage.removeItem('auth_refresh_token') commit('clearAuthCredentials') return } return dispatch('updateRefreshToken', refreshToken) .then(() => dispatch('refreshAccessToken')) .then(() => bus.$emit('flash', 'Autologin => success', 'success')) .catch(error => bus.$emit('flash', `Autologin failded - ${error.message}`, 'warning') ) } } <file_sep>/src/services/api/auth.js import axios from '@/axios' export default { login({ email, password }) { return axios .post(process.env.VUE_APP_API_LOGIN_URL, { username: email, password: <PASSWORD> }) .then(response => { return { accessToken: response.data.access, refreshToken: response.data.refresh } }) }, logout({ refreshToken }) { return axios.post(process.env.VUE_APP_API_LOGOUT_URL, { refresh: refreshToken }) }, refresh({ refreshToken }) { return axios.post(process.env.VUE_APP_API_REFRESH_URL, { refresh: refreshToken }) }, verify({ refreshToken }) { return axios.post(process.env.VUE_APP_API_VERIFY_URL, { token: refreshToken }) } } <file_sep>/src/store/modules/messenger/actions.socket.js import bus from '@/bus' import { dataToModel } from './actions.room' export default { socket__addMessage({ dispatch }, payload) { dispatch('addMessage', { data: payload }) }, socket__updateRoom({ commit }, payload) { commit('updateRoom', dataToModel(payload)) }, socket__addRoom({ dispatch, getters }, payload) { if (!getters.getRoomById(payload.id)) { dispatch('addRoom', { data: payload }).then(room => { bus.$emit( 'flash', `New room "${room.title}" is created by ${room.author.fullName}`, 'info' ) }) } }, socket__addNotification({ dispatch }, payload) { dispatch('addMessage', { data: payload, isNotification: true }) } } <file_sep>/tests/unit/LoginView.spec.js import Vue from "vue"; import Vuex from "vuex"; import Vuetify from "vuetify"; import { mount, createLocalVue } from "@vue/test-utils"; import { createStore } from "vuex-extensions"; import LoginView from "@/views/LoginView.vue"; const localVue = createLocalVue(); localVue.use(Vuex); Vue.use(Vuetify); const createConfig = (data = {}) => { const store = createStore(Vuex.Store, { strict: true, state: {}, modules: { auth: { namespaced: true, actions: { tryAutoLogin() { return true; } }, getters: { isAuthenticated() { return false; } } } } }); return { mocks: {}, sync: false, store, localVue, vuetify: new Vuetify(), ...data }; }; describe("LoginView.vue", () => { it("validate valid form", async () => { const wrapper = mount(LoginView, createConfig()); wrapper.vm.credentials.password = "<PASSWORD>"; wrapper.vm.credentials.email = "<EMAIL>"; await wrapper.vm.$nextTick(); wrapper.vm.$refs.form.validate(); expect(wrapper.vm.$refs.form.value).toBe(true); }); it("validate invalid form", async () => { const wrapper = mount(LoginView, createConfig()); wrapper.vm.credentials.password = "<PASSWORD>"; wrapper.vm.credentials.email = "wrong_email"; await wrapper.vm.$nextTick(); wrapper.vm.$refs.form.validate(); expect(wrapper.vm.$refs.form.value).toBe(false); }); }); <file_sep>/src/store/modules/users/getters.js export default { getById: state => id => state.users.find(item => item.id === id), getAuthUser: (state, getters, rootState) => rootState.auth.authUserId && getters.getById(rootState.auth.authUserId), isLoading: state => id => state.usersLoading.find(item => item === id) } <file_sep>/src/services/api/index.js import authApi from './auth' import roomApi from './rooms' import userApi from './users' export default { ...authApi, ...roomApi, ...userApi } <file_sep>/src/store/modules/users/models.js import store from '@/store' import BaseModel from '@/store/models' export class UserModel extends BaseModel { fields() { return [ 'id', 'fistName', 'lastName', 'email', 'avatar', 'lastActionAt', 'initials' ] } defaults() { return { lastActionAt: Date.now() } } get_initials_value(field, modelData) { return `${modelData['firstName'][0]}${modelData['lastName'][0]}`.toUpperCase() } get_lastActionAt_value(field, modelData) { const val = modelData[field] if (!val) { return null } return new Date(val) } get fullName() { return this.lastName } static getById(id) { return new UserModel(store.getters['users/getById'](id) || {}) } }
556c2b4d633257e7e1b89328260a6da8ad184dbb
[ "JavaScript", "Markdown" ]
19
JavaScript
zvadym/vue-chat
2ecea77c29098463cdd20565f04766941c040454
4b8b1750585f8377cc47807b3c727c244d9939b9
refs/heads/master
<file_sep><?php require '../vendor/autoload.php'; use VytautasUoga\Task\FormValidator; use VytautasUoga\Task\Form; //check if supports javascript for ajax form handling session_start(); $_SESSION['js'] = true; if ($_SESSION['js'] == true && isset($_POST['name'])) { $validation = new FormValidator($_POST); $errors = $validation->validateForm(); if(empty($errors)) { $form = new Form($_POST); $data = $form->insertFormData(); echo $data; } else { $error['error'] = $errors; echo json_encode($error); } } <file_sep># chat change database credentials `/src/DatabaseConnection.php` <file_sep><?php namespace VytautasUoga\Task; class FormValidator { private $data; private $errors = []; private static $fields = ['name', 'last_name', 'email', 'birthdate', 'message']; public function __construct($post_data) { $this->data = $post_data; } public function validateForm() { $this->validateName(); $this->validateLastname(); $this->validateEmail(); $this->validateBirth(); $this->validateMessage(); return $this->errors; } private function validateName() { $val = trim($this->data['name']); if(empty($val)) { $this->addError('name', 'įveskite vardą'); } else { if(!preg_match('/^[a-zA-Z0-9]{3,15}$/', $val)) { $this->addError('name','vardą turi sudaryti 3-15 raidės arba skaičiai'); } } } private function validateLastname() { $val = trim($this->data['last_name']); if(empty($val)) { $this->addError('last_name', 'įveskite pavardę'); } else { if(!preg_match('/^[a-zA-Z0-9]{3,15}$/', $val)) { $this->addError('last_name','pavardę turi sudaryti 3-15 raidės arba skaičiai'); } } } private function validateEmail() { $val = trim($this->data['email']); if(!empty($val) && !filter_var($val, FILTER_VALIDATE_EMAIL)) { $this->addError('email', 'neteisingai įvestas el.pašto adresas'); } } private function validateBirth() { $val = trim($this->data['birthdate']); if(empty($val)) { $this->addError('birthdate', 'įveskite savo gimimo datą'); } } private function validateMessage() { $val = $this->data['message']; if(empty($val)) { $this->addError('message', 'žinutė negali būti tuščia'); } else { if(!preg_match('/^[a-zA-Z0-9 .:()?!.,]{2,255}$/', $val)) { $this->addError('message','žinutę turi sudaryti 2-255 simboliai'); } } } private function addError($key, $val) { $this->errors[$key] = $val; } }<file_sep><?php namespace VytautasUoga\Task; class User extends DatabaseConnection { public function insertUser(string $name, string $last_name, string $birth, string $email) { $mysqli = $this->connect(); $exists = $this->checkUserExists($name, $last_name, $birth); if (!$exists) { $stmt = $mysqli->prepare("INSERT INTO users (name, last_name, birth, email) VALUES (?, ?, ?, ?)"); $stmt->bind_param('ssss', $name, $last_name, $birth, $email); if ($stmt->execute()) { return true; } else { return false; } } else { return $exists; // user id } } private function checkUserExists(string $name, string $last_name, string $birth) { $mysqli = $this->connect(); $stmt = $mysqli->prepare("SELECT id FROM users WHERE name = ? AND last_name = ? AND birth = ?"); $stmt->bind_param('sss', $name, $last_name, $birth); $stmt->execute(); $result = $stmt->get_result(); if ($result->num_rows === 0) { return false; } else { while($row = $result->fetch_assoc()) { $id = $row['id']; } return $id; } } public function getUserAge(string $user_birth) { $user_birth = strtotime($user_birth); $current_date = strtotime(date('Y-m-d')); $age = -1; while ($user_birth < $current_date) { $age++; $user_birth = strtotime("+1 year", $user_birth); } return $age; } public function getUser(int $user_id) { $sql = "SELECT * FROM users WHERE id = ".$user_id; $result = $this->connect()->query($sql); $user = $result->fetch_assoc(); return $user; } public function getLastUserId() { $last_id = "SELECT id FROM users ORDER BY id DESC LIMIT 1"; $result = $this->connect()->query($last_id); $row = $result->fetch_assoc(); $last_id = $row['id']; return $last_id; } }<file_sep><?php namespace VytautasUoga\Task; class Message extends DatabaseConnection { const MESSAGES_PER_PAGE = 5; protected function getAllMessages() { $sql = "SELECT * FROM messages ORDER BY id DESC LIMIT 30"; $result = $this->connect()->query($sql); $numRows = $result->num_rows; if ($numRows > 0) { while ($row = $result->fetch_assoc()) { $data[] = $row; } return $data; } } public function insertMessage(int $user_id, string $message) { $mysqli = $this->connect(); $stmt = $mysqli->prepare("INSERT INTO messages (user_id, message) VALUES (?, ?)"); $stmt->bind_param('is', $user_id, $message); if ($stmt->execute()) { return true; } else { return false; } } public function getNumberOfPages() { $datas = $this->getAllMessages(); $datas = count($datas); $number_of_pages = ceil($datas/self::MESSAGES_PER_PAGE); return $number_of_pages; } public function getPageMessages(int $current_page) { $mysqli = $this->connect(); // $current_page = $mysqli->real_escape_string($current_page); $page_first_message = ($current_page-1)*5; $sql = "SELECT * FROM messages ORDER BY id DESC LIMIT ". $page_first_message .",5"; $result = $mysqli->query($sql); $numRows = $result->num_rows; if ($numRows > 0) { while ($row = $result->fetch_assoc()) { $messages[] = $row; } return $messages; } } }<file_sep><?php use VytautasUoga\Task\User; use VytautasUoga\Task\Message; namespace VytautasUoga\Task; class Form { private $data; public function __construct($post_data) { $this->data = $post_data; } public function insertFormData() { $name = trim($this->data['name']); $last_name = trim($this->data['last_name']); $birth = trim($this->data['birthdate']); $message = trim($this->data['message']); $email = trim($this->data['email']); // insert user data $user = new User(); $success = $user->insertUser($name, $last_name, $birth, $email); if ($success) { // check if user already exists if (is_numeric($success)) { $user_id = $success; } else { $user_id = $user->getLastUserId(); } $age = $user->getUserAge($birth); $this->data['age'] = $age; // insert user message $messages = new Message(); $success = $messages->insertMessage($user_id, $message); if (!$success) { echo "Nepavyko išsaugoti žinutės"; die(); } } else { echo "Nepavyko išsaugoti jūsų duomenų"; die(); } return json_encode($this->data); } } <file_sep><?php namespace VytautasUoga\Task; use mysqli; class DatabaseConnection { private $server_name; private $user_name; private $password; private $db_name; protected function connect() { $this->server_name = "localhost"; $this->user_name = "debian-sys-maint"; $this->password = "<PASSWORD>"; $this->db_name = "task"; $mysqli = new mysqli($this->server_name, $this->user_name, $this->password, $this->db_name); $mysqli->set_charset("utf8mb4"); if ($mysqli->connect_error) { die("Connection failed: " . $mysqli->connect_error); } return $mysqli; } }<file_sep><?php require '../vendor/autoload.php'; use VytautasUoga\Task\User; use VytautasUoga\Task\Message; // ajax pagination if (isset($_GET["page1"])) { $current_page = $_GET["page1"]; $messages_obj = new Message(); $page_messages = $messages_obj->getPageMessages($current_page); foreach ($page_messages as $message) : $users = new User(); $user = $users->getUser($message['user_id']); ?> <li> <span><?= $message['date_add']; ?></span> <?php if(!empty($user['email'])) : ?> <a href="mailto:<?= $user['email']; ?>"><?= $user['name']; ?></a>, <?php else: echo $user['name'].','; endif; ?> <?= $users->getUserAge($user['birth']); ?> m.<br/> <?= $message['message']; ?> </li> <?php endforeach; }<file_sep> <?php require __DIR__ . '/vendor/autoload.php'; use VytautasUoga\Task\User; use VytautasUoga\Task\Message; use VytautasUoga\Task\Form; use VytautasUoga\Task\FormValidator; // check and insert form data if(isset($_POST['submit'])) { $validation = new FormValidator($_POST); $errors = $validation->validateForm(); if(empty($errors)) { $form = new Form($_POST); $form->insertFormData(); } } // php pagination, detect page if(!isset($_GET['page'])) { $current_page = 1; } else { $current_page = $_GET['page']; } ?> <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Žinutės</title> <link rel="stylesheet" media="screen" type="text/css" href="css/screen.css" /> </head> <body> <div id="wrapper"> <h1>Jūsų žinutės</h1> <!-- form --> <form action="index.php" method="post" id="form"> <p <?= (isset($errors['name'])) ? 'class="err"' : '' ?>> <label for="name">Vardas *</label><br/> <?= (isset($errors['name'])) ? $errors['name'].'<br/>' : '<span class="error"></span><br/>'; ?> <input id="name" type="text" name="name" value="<?= htmlspecialchars($_POST['name']) ?? '' ?>" /> </p> <p <?= (isset($errors['last_name'])) ? 'class="err"' : '' ?>> <label for="last_name">Pavardė *</label><br/> <?= (isset($errors['last_name'])) ? $errors['last_name'].'<br/>' : '<span class="error"></span><br/>' ?> <input id="last_name" type="text" name="last_name" value="<?= htmlspecialchars($_POST['last_name']) ?? '' ?>" /> </p> <p <?= (isset($errors['birthdate'])) ? 'class="err"' : '' ?>> <label for="birthdate">Gimimo data *</label><br/> <?= (isset($errors['birthdate'])) ? $errors['birthdate'].'<br/>' : '<span class="error"></span><br/>' ?> <input id="birthdate" type="date" name="birthdate" min="1900-01-01" max="<?= date_create('now')->modify('-1 day')->format('Y-m-d');?>" value="<?= htmlspecialchars($_POST['birthdate']) ?? '' ?>" /> </p> <p <?= (isset($errors['email'])) ? 'class="err"' : '' ?>> <label for="email">El.pašto adresas</label><br/> <?= (isset($errors['email'])) ? $errors['email'].'<br/>' : '<span class="error"></span><br/>' ?> <input id="email" type="text" name="email" value="<?= htmlspecialchars($_POST['email']) ?? '' ?>" /> </p> <p <?= (isset($errors['message'])) ? 'class="err"' : '' ?>> <label for="message">Jūsų žinutė *</label><br/> <?= (isset($errors['message'])) ? $errors['message'].'<br/>' : '<span class="error"></span><br/>' ?> <textarea id="message" name="message" value="<?= htmlspecialchars($_POST['message']) ?? '' ?>"></textarea> </p> <p> <span>* - privalomi laukai</span> <input type="submit" value="Skelbti" name="submit" /> <img id="loader" style="display: none;" src="img/ajax-loader.gif" alt="" /> </p> </form> <!-- messages container --> <?php $messages_obj = new Message(); $total_pages = $messages_obj->getNumberOfPages(); $page_messages = $messages_obj->getPageMessages($current_page); ?> <ul id="messages-container"> <?php if (count($page_messages) > 0) : foreach ($page_messages as $message) : $users = new User(); $user = $users->getUser($message['user_id']); ?> <li> <span><?= $message['date_add']; ?></span> <?php if(!empty($user['email'])) : ?> <a href="mailto:<?= $user['email']; ?>"><?= $user['name']; ?></a>, <?php else: echo $user['name'].','; endif; ?> <?= $users->getUserAge($user['birth']); ?> m.<br/> <?= $message['message']; ?> </li> <?php endforeach; ?> <?php else : ?> <li style="text-align: center;">Žinučių nėra!</li> <?php endif; ?> </ul> <!-- pages numbers --> <div style="text-align: center;"> <?php for ($page=1; $page <= $total_pages; $page++) : ?> <a href="index.php?page=<?= $page ?>" class="page-link <?= ($page == $current_page) ? 'active' : '' ?>" data-id="<?= $page ?>" > <?= $page ?> </a> <?php endfor; ?> </div> </div> <script type="text/javascript" src="js/jquery-3.4.1.min.js"></script> <script type="text/javascript" src="js/main.js"></script> </body> </html> <file_sep>$(document).ready(function() { $("input[type='submit']").click(function(e){ $.ajax({ type: "POST", url: 'src/FormHandler.php', data: $( "#form" ).serialize(), dataType: "json", beforeSend: function() { $('#loader').show(); $("input[type='submit']").hide(); $("input, textarea").attr('readonly', true); // setting first page and getting page messages before new message inserted $.ajax({ url: "src/AjaxPagination.php", type: "GET", data: { page1 : 1 }, cache: false, success: function(dataResult){ $("#messages-container").html(dataResult); } }); }, complete: function(){ $('#loader').hide(); $("input[type='submit']").show(); $("input, textarea").attr('readonly', false); $("#form textarea").val(''); }, success: function(data) { // check form errors if(data.error) { $('#form').find('.error').css('display', 'none'); $('#form').children().removeClass('err'); $.each(data.error, function(index, value) { var input = $('#form').find('#'+index); input.parent().addClass('err'); input.parent().find('.error').html(value).css('display', 'block'); }); } else { var date_add = formatDate(); var email = data.email; var messageHtml = '<li><span>'+date_add+'</span>'; if (email.length > 4) { messageHtml += '<a href="mailto:'+email+'">'+data.name+', </a>'; } else { messageHtml += data.name+', '; } messageHtml += data.age+' m.<br/>'+ data.message+'</li>'; var messages_count = $('#messages-container li').length; console.log(messages_count); if (messages_count > 4) { $('#messages-container').children().last().remove(); } $('#messages-container').prepend(messageHtml).html(); $('.page-link').removeClass("active"); $('.page-link').first().addClass("active"); $('#form').find('.error').css('display', 'none'); $('#form').children().removeClass('err'); } }, error: function(error) { alert(error.responseText); } }); e.preventDefault(); }); // messages pages navigation $(".page-link").click(function(e){ var id = $(this).attr("data-id"); $.ajax({ url: "src/AjaxPagination.php", type: "GET", data: { page1 : id }, cache: false, success: function(dataResult){ $("#messages-container").html(dataResult); }, error: function(error) { alert('Error_ajax_page'); } }); e.preventDefault(); $(this).parent().find(".active").removeClass("active"); $(this).addClass("active"); }); function formatDate() { var currentdate = new Date($.now()); var month = (currentdate.getMonth()+1); var day = currentdate.getDate(); var hour = currentdate.getHours(); var min = currentdate.getMinutes(); var second = currentdate.getSeconds(); if (day < 10) { day = "0" + day; } if (month < 10) { month = "0" + month; } if (hour < 10) { hour = "0" + hour; } if (min < 10) { min = "0" + min; } if (second < 10) { second = "0" + second; } var date = currentdate.getFullYear()+"-"+month+"-"+day+" "+hour+":"+min+":"+second; return date; } });
bbec2c80debadb734d01e4bd3d10459eb583f451
[ "Markdown", "JavaScript", "PHP" ]
10
PHP
coolas7/chat
231092d9fa7c1b919aeee444c659f20b9e9e9304
95c52c583455ada9cd9ae2cd19ad5502bce4bfb7
refs/heads/master
<repo_name>AnttiSlunga/rpsls-engine<file_sep>/src/main/java/com/engine/rpsls/warriors/Rock.java package com.engine.rpsls.warriors; import com.api.rpsls.Warrior; import java.util.Arrays; import java.util.List; public class Rock extends Warrior{ public Rock() { this.setName("Rock"); } @Override public List<String> wins() { return Arrays.asList("Scissors", "Lizard"); } @Override public List<String> loses() { return Arrays.asList("Paper", "Spock"); } } <file_sep>/src/main/java/com/engine/rpsls/GameEngineImpl.java package com.engine.rpsls; import com.api.rpsls.FightResult; import com.api.rpsls.GameEngine; import com.api.rpsls.Warrior; import com.engine.rpsls.warriors.*; import org.springframework.stereotype.Component; import java.util.HashMap; import java.util.Map; @Component public class GameEngineImpl implements GameEngine { public FightResult fight(Warrior warrior1, Warrior warrior2) { return warrior1.fight(warrior2); } public Map<String, Warrior> getWarriors() { Map<String, Warrior> warriors = new HashMap<String, Warrior>(); warriors.put("lizard", new Lizard()); warriors.put("paper", new Paper()); warriors.put("rock", new Rock()); warriors.put("scissors", new Scissors()); warriors.put("spock", new Spock()); return warriors; } public Warrior getWarriorByName(String name) { return getWarriors().get(name); } } <file_sep>/README.md # rpsls-engine
f985466f8d69eb800ed3bac8a5d156c5d2d43387
[ "Markdown", "Java" ]
3
Java
AnttiSlunga/rpsls-engine
e6129726f50648d3a7d9213af5a7bbaf1d079014
34c3966753e7508fd96fa5c25d1bc68364b83610
refs/heads/master
<file_sep>package de.trion.sample.webframe; import de.trion.sample.util.SampleWebserver; import java.awt.Desktop; import java.net.URI; /** * Sample to demonstrate running the web application as standalone */ public class WebStandalone { public static void main(String[] args) throws Exception { SampleWebserver.serve(); if(Desktop.isDesktopSupported()) { Desktop.getDesktop().browse(new URI("http://localhost:8081/sample.html")); } } } <file_sep><div class="jumbotron"> <h1>About</h1> <p>This application was created to demonstrate integration of desktop Swing applications with browser based applications.</p> <p>If you have questions or feedback for this sample, please drop us a line: <a href="https://www.trion.de/#pk_campaign=jwebbridge">trion.de</a> or create a PR on github.</p> </div><file_sep># Sample for Java Desktop integration This project is to illustrate the concept of web and desktop integration, for example for migrating rich desktop applications to the web. After cloning you can run it using ``` cd JavaFXWebView mvn clean install java -jar target/java-web-bridge-1.0.0.CI-SNAPSHOT.jar ``` A more complex example is in the EnterpriseSample folder. You can run it using ``` cd EnterpriseSample mvn clean install java -jar target/enterprise-java-web-bridge-1.0.0.CI-SNAPSHOT.jar ``` <file_sep>// sample business logic, for demonstration purposes kept in one file var app = angular.module('sampleApp', ['ngRoute']); app.config(['$routeProvider', function ($routeProvider) { $routeProvider. when('/about', { templateUrl: 'view-about.html', activeTab: 'about' }). when('/home', { templateUrl: 'view-home.html', activeTab: 'home' }). when('/contracts', { templateUrl: 'view-contracts.html', activeTab: 'contracts' }). when('/invoices', { templateUrl: 'view-invoices.html', activeTab: 'invoices' }). otherwise({ redirectTo: '/home' }); }]); app.run(['$rootScope', '$route', function ($rootScope, $route) { $rootScope.isTabActive = function (tabName) { if (!$route.current) { return false; } return $route.current.activeTab === tabName; }; }]); app.factory('InvoiceService', function () { var api = { getInvoices: function () { var invoices = []; var invoice = {number: "acme-2", date: "2015-11-01", companyId: 1, paid: false }; invoices.push(invoice); invoice = {number: "acme-1", date: "2015-10-21", companyId: 1, paid: true }; invoices.push(invoice); invoice = {number: "acme-1", date: "2015-10-21", companyId: 1, paid: true }; invoices.push(invoice); invoice = {number: "wonder-1", date: "2015-11-11", companyId: 2, paid: false }; invoices.push(invoice); return invoices; } }; if (window.appFrame) { api.getInvoices = function () { var data = window.appFrame.getInvoices(); return JSON.parse(data); }; } return api; }); app.factory('ContractService', function ($http, $q) { var contracts; return { getContracts: function () { var deferred = $q.defer(); if(!contracts) { $http.get("/api/contracts").then(function successCallback(data){ contracts = data; deferred.resolve(data); }); } else { deferred.resolve(contracts); } return deferred.promise; } }; }); app.factory('StatusService', function ($http) { var api = { statusUpdate: function(status) { } }; if (window.appFrame) { api.statusUpdate = function(status) { window.appFrame.updateStatus(status); }; } return api; }); app.factory('MailService', function ($http) { var api = { sendMail: function (contract) { $("#mailReceiver").text(contract.name + ", " + contract.company); $("#mailDialog").modal('show'); } }; if (window.appFrame) { api.sendMail = function (contract) { window.appFrame.sendMail(contract); }; } return api; }); app.controller("ContractCtrl", function($scope, MailService, StatusService, ContractService) { ContractService.getContracts().then(function(result) { $scope.contracts = result.data; }); $scope.sendMail = function (contract) { MailService.sendMail(contract); }; $scope.disable = function (contract) { contract.active = false; StatusService.statusUpdate("Disabled partner " + contract.name); }; $scope.enable = function (contract) { contract.active = true; StatusService.statusUpdate("Enabled partner " + contract.name); }; }); app.controller("InvoiceCtrl", function($scope, InvoiceService, ContractService) { ContractService.getContracts().then(function(result) { $scope.contracts = result.data; }); $scope.findCompanyById = function (id) { if (!$scope.contracts) { return {}; } for(var i = 0; i < $scope.contracts.length; i++) { var item = $scope.contracts[i]; if (item.companyId == id) { return item; } } return {}; }; $scope.invoices = InvoiceService.getInvoices(); });
b407c7cbda756452e6fedcedae277fc40a99f67c
[ "Markdown", "Java", "JavaScript", "HTML" ]
4
Java
stefanbecke/java-web-bridge
a991f72c791071b27dc84f311273ad2defc88fe9
caba6d094bd1b80ab1ceeca849dbe2b65f92d58e
refs/heads/master
<file_sep>/* JSPWiki - a JSP-based WikiWiki clone. Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); fyou may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* Class: Dialog.Chars The Dialog.Chars is a Dialog object, to support selection of special characters. Arguments: options - optional, see options below Options: others - see Dialog options Inherits from: [Dialog] */ Dialog.Chars = new Class({ Extends: Dialog.Selection, options: { //onAction: function(value){}, items: '.body td', chars: [ 'nbsp|iexcl|cent|pound|curren|yen|brvbar|sect|uml|copy|ordf', 'laquo|not|reg|macr|deg|plusmn|sup2|sup3|acute|micro|para', 'middot|cedil|sup1|ordm|raquo|frac14|frac12|frac34|iquest|times|divide', 'Agrave|Aacute|Acirc|Atilde|Auml|Aring|AElig|Ccedil|Egrave|Eacute|Ecirc', 'Euml|Igrave|Iacute|Icirc|Iuml|ETH|Ntilde|Ograve|Oacute|Ocirc|Otilde', 'Ouml|Oslash|Ugrave|Uacute|Ucirc|Uuml|Yacute|THORN|szlig|agrave|aacute', 'acirc|atilde|auml|aring|aelig|ccedil|egrave|eacute|ecirc|euml|igrave', 'iacute|icirc|iuml|eth|ntilde|ograve|oacute|ocirc|otilde|ouml|oslash', 'ugrave|uacute|ucirc|uuml|thorn|yuml|OElig|oelig|Scaron|scaron|Yuml', 'ndash|mdash|lsquo|rsquo|ldquo|rdquo|dagger|Dagger|bull|hellip|permil', 'euro|trade|larr|uarr|rarr|darr|harr|crarr|loz|diams|infin' ] }, initialize:function(options){ this.setClass('.chars',options); //options.cssClass = '.chars'+(options.cssClass||'') this.parent(options); }, setBody: function(){ /* inspired by smarkup */ var content = this.options.chars.map(function(line){ return '<tr>' + line.split('|').map(function(c){ return '<td title="&amp;'+ c + ';">&'+ c + ';</td>'; }).join('') + '</tr>'; }); return this.parent( 'table'.slick({ html: '<tbody>'+content.join('')+'</tbody>' }) ); } }); <file_sep>/* JSPWiki - a JSP-based WikiWiki clone. Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); fyou may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* Dynamic Style: Tips Add Tip behavior to a set of DOM Elements Bootstrap (start code) //tip anchors <element> Caption <body> ...body... </body> </element> //layout of the tip, with absolute position div.tooltip(.active)(.top|.left|.right|.bottom) div.tooltip-inner <body> ... </body> div.tooltip-arrow (end) */ var Tips = function Tips(elements,options){ var tt = 'div.tooltip', TheTip = [tt,[tt+'-inner'/*,tt+'-arrow'*/]].slick().inject(document.body), inner = TheTip.getFirst(); $$(elements).addEvents({ mousemove: function(e){ TheTip.setStyles({ top:e.page.y +10, left:e.page.x + 10 }); }, mouseenter: function(e){ inner.adopt( this.getFirst() ) ; TheTip.addClass('in'); //.fade('in'); }, mouseleave: function(e){ TheTip.removeClass('in'); //.fade('out'); this.adopt( inner.getFirst() ); } }); } /*TIP position logic position: function(event){ var windowPadding={x:0, y:0}; var size = window.getSize(), scroll = window.getScroll(), tip = {x: this.tip.offsetWidth, y: this.tip.offsetHeight}, props = {x: 'left', y: 'top'}, bounds = {y: false, x2: false, y2: false, x: false}, obj = {}; for (var z in props){ obj[props[z]] = event.page[z] + this.options.offset[z]; if (obj[props[z]] < 0) bounds[z] = true; if ((obj[props[z]] + tip[z] - scroll[z]) > size[z] - windowPadding[z]){ obj[props[z]] = event.page[z] - this.options.offset[z] - tip[z]; bounds[z+'2'] = true; } } this.tip.setStyles(obj); }, */ <file_sep>/* JSPWiki - a JSP-based WikiWiki clone. Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); fyou may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* Function: naturalSort Sorts the elements of an array, using a more 'natural' algoritm. Maintains a cache of the prepared sortable array. Example: [0, 1, "017", 6, , 21 ].naturalSort(); //[0, 1, 6, "017", 21] [[6,"chap 1-14"],["05","chap 1-4"]].naturalSort(1); //[["05","chap 1-4"],[6,"chap 1-14"]] rows.naturalSort( 3 ); */ /*jshint forin:false, noarg:true, noempty:true, undef:true, unused:true, plusplus:false, immed:false, browser:true, mootools:true */ !function(){ /* Function: makeSortable Parse the column and guess its data-type. Then convert all values according to that data-type. Cache the sortable values in rows[0-n].cache. Empty rows will sort based on the title attribute of the cells. Supported data-types: numeric - numeric value, with . as decimal separator date - dates as supported by javascript Date.parse See https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date/parse ip4 - ip addresses (like 172.16.58.3) euro - currency values (like £10.4, $50, €0.5) kmgt - storage values (like 2 MB, 4GB, 1.2kb, 8Tb) Arguments: rows - array of rows each pointing to a DOM tr element rows[i].data caches the converted data. column - index (0..n) of the processed column Returns: comparison function which can be used to sort the table */ function makeSortable(thisArray, column){ var num=[], dmy=[], kmgt=[], nat=[], val, i, len = thisArray.length, isNode, //split string in sequences of digits reNAT = /([-+]?\d+)|(\D+)/g, KMGTre = /(:?[\d.,]+)\s*([kmgt])b/, //eg 2 MB, 4GB, 1.2kb, 8Tb KMGTmul = { k:1, m:1e3, g:1e6, t:1e9 }, KMGTparse = function( val ){ return KMGTre.test( val.toLowerCase() ) ? val.toFloat() * KMGTmul[ RegExp.$2 ] : NaN; }; for( i=0; i<len; i++ ){ //1. Retrieve the value to be sorted: native js value, or dom elements val = thisArray[i]; isNode = val && val.nodeType; //if 'column' => retrieve the nth DOM-element or the nth Array-item if( !isNaN(column) ) val = ( isNode ? val.getChildren() : val )[column]; //retrieve the value and convert to string val = (''+(isNode ? val.get('text') || val.get('title') : val)).trim(); //2. Convert and store in type specific arrays (num,dmy,kmgt,nat) //CHECKME: some corner cases: numbers with leading zero's, confusing date string if( /(?:^0\d+)|(?:^[^\+\-\d]+\d+$)/.test(val) ){ num=dmy=0; } if( num && isNaN( num[i] = +val ) ) num=0; if( nat && !( nat[i] = val.match(reNAT) ) ) nat=0; //Only strings with non-numeric values if( dmy && ( num || isNaN( dmy[i] = Date.parse(val) ) ) ) dmy=0; if( kmgt && isNaN( kmgt[i] = KMGTparse(val) ) ) kmgt=0; } console.log("[",kmgt?"kmgt":dmy?"dmy":num?"num":nat?"nat":'no conversion',"] "); //console.log(nat); //console.log(kmgt||dmy||num||nat||thisArray); return kmgt || dmy || num || nat || thisArray; } /* Function: naturalCmp Comparison function for sorting "natural sortable" arrays. The entries of sortable arrays consists of tupples: ( .[1] is the sortable value, .[0] is the original value ) The sortable value is either a scalar or an array. */ function naturalCmp(a,b){ var aa, bb, i=0, t; // retrieve the sortable values: scalars or tokenized arrays a = a[1]; b = b[1]; // scalars, always same types - integer, float, date, string if( typeof a !='object' ) return (a<b) ? -1 : (a>b) ? 1 : 0; //if( !a.length ) return a.localeCompare(b); while( (aa = a[i]) ){ if( !( bb = b[i++] ) ) return 1; //fixme t = aa - bb; //auto-conversion to numbers, if possible if( t ) return t; //otherwise fall-through to string comparison if( aa !== bb ) return (aa > bb) ? 1 : -1; //if( aa !== bb ) return aa.localeCompare(bb); } return b[i] ? -1 : 0; } Array.implement('naturalSort',function(column, force){ var thisArray = this, sortable, i, len = thisArray.length, cache = 'cache'; console.log('naturalSort',column,force) //1. read sortable cache or make a new sortable array if( isNaN(column) ){ // 1D array : [ .. ] sortable = thisArray[cache] || []; if( column/*==force*/ || !sortable.length/*==0*/ ){ sortable = thisArray[cache] = makeSortable(thisArray); } } else { // 2D array : [[..],[..],..] sortable = thisArray[0][cache] || []; if( !sortable.length ) for(i=0; i<len; i++) thisArray[i][cache] = []; //init row caches if( force || (sortable[column]==undefined) ){ sortable = makeSortable(thisArray, column); for(i=0; i<len; i++) thisArray[i][cache][column] = sortable[i]; //cache sortable values } else { for(i=0; i<len; i++) sortable[i]=thisArray[i][cache][column]; //retrieve cached column } } console.log(this.cache); //2. Do the actual sorting for( i=0; i<len; i++) sortable[i] = [ thisArray[i], sortable[i] ]; sortable.sort( naturalCmp ); for( i=0; i<len; i++) thisArray[i] = sortable[i][0]; return thisArray; }); }(); <file_sep>/*! JSPWiki - a JSP-based WikiWiki clone. Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); fyou may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* */ /* DirectSnippet definitions for JSPWiki, aka ''smartpairs''. These snippets are directly expanded on keypress. */ Wiki.DirectSnips = { '"' : '"', '(' : ')', '[' : ']', '{' : '}', '%%' : ' /%', "'" : { snippet:"'", scope:{ "[{":"}]" //plugin parameters } } }; /* Function: tabSnippets Definitions for the JSPWiki editor commands. Following commands are predefined by the snipe editor: - find : toggles the find and replace dialog - sections : toggle sections dropdown dialog, which allows to switch between certain sections of the document or the whole document - undo : undo last command, set the editor to the previous stable state - redo : revert last undo command A command consists of triggers, attributes, snippets, events and dialogs. Triggers : ======== click events, suggestion dialogs, TAB-completion and Ctrl-keys. Click events are attached to DOM elements with a .cmd css-class. If the DOM element also contains a .pop css-class, a dialog will be opened. TAB-completion can be turned on/off via the 'tabcompletion' flag. The 'keyup' event can trigger a suggestion dialog: - the suggest(txta,caret) function validates the suggestion context It returns true/false and can modify the snippet with - snip.start : begin offset of the matched prefix - snip.match : matched prefix (string) - snip.tail: (optional) replaceable tail Attributes : ========== - initialize: function(cmd, snip) called once at initialization - key: shortcut key (ctrl-key) - scope: set to TRUE when the cmd is valid - nscope: set to TRUE when the cmd is not valid - cmdId: wysiwyg mode only (commandIdentifier) Snippet : ======= The snippet contains the inserted or replaced text. - static snippet: "some string" - snippet with parameters in {} brackets: "some {dialog1} string" A {.} will be replaced by the selected text. A {dialog-1} opens a dialog, and inserts the returned info (eg color, selection...) - dynamic snippet: javascript function. Example: snippet: function(){ this.dialogs.exec( dialog-name, ... onChange: function(value){ } ) } Event : ===== Fires an event back to the invoking Object (Wiki.Edit in our case) Example: smartpairs: { event: 'config' } Dialogs : ======= (btw -- you do use unique names, do you?) - <dialog-name>: [ Dialog.SubClass, {dialog-parameters, event-handlers} ] - <dialog-name>: "dialog initialization string" This is a short notation for Dialog.Selection, or.. [Selection, "put here your dialog initialization string"] The Dialog Classes are subclass of Dialog. (eg. Dialog.Selection) Examples: acl: { nscope: { "[{" : "}]" }, snippet: "[\\{ ALLOW {permission} {principal(s)} }]" permission: "view|edit|delete", "principals(s)": [Dialog.Selection, { onOpen: function(){ this.setBody( AJAX-request list of principals ); } ] } link: { suggest: function(){ //match [, but not [[ or [{ //defines .start, .selection, .trail ?? } snippet: "{wikiLink}", //or snippet: function(){ this.dialogs.exec('wikiLink'); }, wikiLink: [Dialog.Link, { onOpen: function(){ AJAX-retrieval of link suggestions } }] } color: { nscope: {"%%(":")"}, action: "%%(color:#000000; background:#ffffff;) {.} \%", } colorsuggestion: { scope: {"%%(":")"}, suggest: function(){ //match #cccccc } snippet: "{color}", color: [ dialog.Color, { //parms }] } */ Wiki.Snips = { find: { key: "f" //predefined find dialog triggered via Ctrl-f or a toolbar 'find' button }, //sections: //predefined section dialog triggered via a toolbar 'sections' button //TODO: turn it into a suggestion menu for header lines undo: { //event: "undo", //predefined snipe event action: function(){ this.undoredo.onUndo(); }, key: "z" }, redo: { //event: "redo", //predefined snipe event action: function(){ this.undoredo.onRedo(); }, key: "y" }, smartpairs: { event: 'config' }, livepreview: { event: 'config' }, autosuggest: { event: 'config' }, tabcompletion: { event: 'config' }, previewcolumn: { event: 'config' }, br: { key: "shift+enter", snippet: "\\\\\n" }, hr: "\n----\n", h: { xxxsuggest: function(txta,caret){ var c,result=txta.slice(0,caret.start).match( /(?:^|[\n\r])(!{1,3}[^\n\r]*)$/ ); if( result ){ c = result[1]; result = { start: caret.start - c.length, match: c + txta.slice(caret.start).match( /[^\n\r]*/ )||'' //entire line }; } return result; }, h: [Dialog.Selection, { onOpen: function(){ var value = (this.getValue().replace(/^!+\s?/,'')||'Title'), //remove !markup val = value.trim().trunc(20), k = ['!!! '+value,'!! '+value,'! '+value], v = ['<h2>'+val+'</h2>','<h3>'+val+'</h3>','<h4>'+val+'</h4>']; this.setBody( v.associate( k ) ); } }] }, font: { nScope: { "%%(":")", "font-family:":";" }, /* suggest: function(txta,caret){ //match /%%(:?.*)font-family:([^;\)]+)/ },*/ snippet: "%%(font-family:{font};) {.}/% ", font: [Dialog.Font, {}] }, color: { nscope: { '%%(': ')' }, snippet: "%%(color:{#000000}; background:{#ffffff};) {.} ", suggest: function(txta, caret){ //match "#cccccc;" pattern var c,d, result = txta.slice(0,caret.end).match( /#[0-9a-f]{0,6}$/i ); if( result ){ c = result[0]; d = txta.slice( caret.end ).match( /^[0-9a-f]+/i )||''; result = { start: caret.end - c.length, //position of # char match: (c+d).slice(0,7) }; } return result; }, color: [ Dialog.Color, { //colorImage:'./test-dialog-assets/circle-256.png' }] }, symbol: { synonym:"chars" }, chars: { nScope: { "%%(":")" }, snippet: "{&entity;}", suggest: function(txta, caret){ //match &xxx; var c,result = txta.slice(0,caret.end).match( /&[\da-zA-Z]*;?$/ ); if( result ){ c = result[0]; result = { start: caret.end - c.length, match: c, tail: txta.slice( caret.end ).match( /^[\da-zA-Z]*;?/ )||'' } } return result; }, chars: [Dialog.Chars, {caption:"Special Chars".localize()}] }, style: { synonym:"css"}, css: { nScope: { "%%(":")" }, snippet: "%%{css} {.} /% ", suggest: function(txta, caret){ //match %%(.w+) var c, result = txta.slice(0,caret.end).match(/%%[\da-zA-Z(\-\_:#;)]*$/); if(result){ c = result[0].slice(2); //drop the %% prefix result = { start: caret.end - c.length, match: c + txta.slice( caret.end ).match( /^[\da-zA-Z(:#;)]*/ )||'' }; } return result; }, css: { "(css:value;)":"any css definitions", "text-success":"text-success", "text-information":"text-information", "text-warning":"text-warning", "text-error":"text-error", success:"success", information:"information", warning:"warning", error:"error", commentbox:"commentbox", quote:"quoted paragraph", sub:"sub-script<span class='sub'>2</span>", sup:"super-script<span class='sup'>2</span>", strike:"<span class='strike'>strikethrough</span>", pretify:"prettify code block", reflection:"image reflection" //xflow:"wide content with scroll bars" } }, //simple tab completion commands sub: "%%sub {subscript text}/% ", sup: "%%sup {superscript text}/% ", strike: "%%strike {strikethrough text}/% ", xflow: "\n%%xflow\n{wide content}\n/%\n ", quote: "\n%%quote \n{quoted text}\n/%\n", dl: "\n;{term}:{definition-text} ", pre: "\n\\{\\{\\{\n{some preformatted block}\n}}}\n", code: "\n%%prettify \n\\{\\{\\{\n{/* some code block */}\n}}}\n/%\n", mono: "\\{\\{{monospaced text}}} ", link: { key:'l', commandIdentifier:'createlink', suggest: function(txta, caret){ //match [link] or [link, do not match [{, [[ //match '[' + 'any char except \n, [, { or ]' at end of the string var result = txta.getFromStart().match( /\[([^\[\{\]\n\r]*)$/ ), link; if( result ){ link = result[1].split('|').getLast(); //exclude "text|" prefix result = { start: caret.start - link.length , //if no input yet, then get list attachments of this wikipage match: link, tail: txta.slice( caret.start ).search( /[\n\r\]]/ ) }; } return result; }, //snippet: "[{display text}|{pagename or url}|{attributes}] ", snippet: "[{link}] ", //attributes: "accesskey='X'|title='description'|target='_blank' // 'accesskey', 'charset', 'class', 'hreflang', 'id', 'lang', 'dir', // 'rel', 'rev', 'style', 'tabindex', 'target', 'title', 'type' // display-text // wiki-page or url -- allow to validate the url ; preview the page/url // title: descriptive text //- target: _blank --new-- window yes or no //link: [ Dialog.Link, { ... link: [ Dialog.Selection, { onOpen: function(dialog){ //console.log("****"+dialog.getValue()+"****", Wiki.PageName) var dialog = this, key = dialog.getValue(); if( !key || (key.trim()=='')) key = Wiki.PageName + '/'; //console.log('json lookup for '+key); Wiki.jsonrpc('search.getSuggestions', [key,30], function(result,exception){ if( result.list && result.list[0] /*length!=0*/ ){ dialog.setBody( result.list ); } else { dialog.hide(); } }); } }] }, bold: { key:'b', snippet:"__{bold text}__ " }, italic: { key:'i', snippet: "''{italic text}'' " }, allow: { synonym: "acl" }, acl: { snippet: "\n[\\{ALLOW {permission} {principal(,principal)} \\}]\n", permission: "view|edit|modify|comment|rename|upload|delete", //permission:[Dialog.Selection, {body:"view|edit|modify|comment|rename|upload|delete"}] "principal(,principal)": function(){ return "Anonymous|Asserted|Authenticated|All"; //FIXME: retrieve list of available wiki user groups through ajax call } }, img: { snippet:"\n[\\{Image src='{img.jpg}' width='{400px}' height='{300px}' align='{text-align}' style='{css-style}' class='{css-class}' }]\n ", 'text-align':'left|center|right' }, plugin: { snippet: "\n[\\{{plugin}}]\n", suggest: function(txta, xcaret){ //match [{ }, plugin: { "TableOfContents title='Page contents' numbered='true' prefix='Chap. '":"Table Of Contents (toc)", "If name='value' page='pagename' exists='true' contains='regexp'\n\nbody\n":"Test a page variable", "SET alias='{pagename}'":"Make a Page Alias", "SET name='value'":"Set a page variable", "$varname":"Get a page variable", "InsertPage page='pagename'":"Insert Page", "CurrentTimePlugin format='yyyy mmm-dd'":"Current Time", "Search query='Janne' max='10'":"Search query", "ReferredPagesPlugin page='pagename' type='local|external|attachment' depth='1..8' include='regexp' exclude='regexp'":"Incoming Links (aka referred pages)", "ReferringPagesPlugin page='pagename' separator=',' include='regexp' exclude='regexp'":"Outgoing Links (aka referring pages)", "WeblogPlugin page='pagename' startDate='300604' days='30' maxEntries='30' allowComments='false'":"Display weblog posts", "WeblogEntryPlugin":"New weblog entry" } }, tab: { nScope: { "%%(":")", "%%tabbedSection":"/%" }, snippet:"%%tabbedSection \n%%tab-{tabTitle1}\n{tab content 1}\n/%\n%%tab-{tabTitle2}\n{tab content 2}\n/%\n/%\n " }, toc: { nScope: { "[{":"}]" }, snippet:"\n[\\{TableOfContents }]\n" }, table: "\n||heading-1||heading-2\n| cell11 | cell12\n| cell21 | cell22\n", me: { alias: 'sign'}, sign: function(){ var name = Wiki.UserName || 'UserName'; return "\\\\\n--" + name + ", "+ new Date().toISOString() + "\\\\\n"; }, date: function(k) { return new Date().toISOString()+' '; //return "[{Date value='" + d.toISOString() + "' }]" //return "[{Date " + d.toISOString() + " }]" }, abra: { suggest:"abra", snippet:"cadabra" }, abrar: { suggest:"abrar", snippet:"acurix" }, lorem: "This is is just some sample. Don’t even bother reading it; you will just waste your time. Why do you keep reading? Do I have to use Lorem Ipsum to stop you? OK, here goes: Lorem ipsum dolor sit amet, consectetur adipi sicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Still reading? Gosh, you’re impossible. I’ll stop here to spare you.", Lorem: { synonym: "lorem" } } <file_sep>/* JSPWiki - a JSP-based WikiWiki clone. Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); fyou may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* Class: TableX.Zebra Simple class to add odd/even coloring to tables. When the first color == 'table' or '' the predefined css class ''.odd'' is used to color the alternative rows. Usage: > new TableX.Zebra( table-element, {colors:['eee','fff']}); > new TableX.Zebra( table-element, {colors:['red']}); */ TableX.Zebra = function(table, options){ function stripe(){ this.rows.filter( Element.isVisible ).each( function(row,j){ j &= 1; //0,1,0,1... if( isArr ){ row.setStyle('background-color', colors[j]||''); } else { row.ifClass(j, 'odd', ''); } }); }; var colors = options.colors, isArr = colors[0]; if ( isArr ){ colors = colors.map( function(c){ return new Color(c); }); } //console.log("ZEBRA ",options.colors, colors[0],colors[1]); stripe.call( new TableX(table, { onRefresh:stripe }) ); } <file_sep>/* JSPWiki - a JSP-based WikiWiki clone. Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); fyou may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* Dynamic Styles Uses global var 'Wiki', and a number of Classes. */ !function( wiki ){ var hints, TheSlimbox, T = TableX; /* Style: %%graphBar .. /% */ wiki.add('div[class^=graphBars]', GraphBar ) //FIXME -- OBSOLETE ?? top level TAB of the page .add('.page > .tabmenu a:not([href])', Tab ) /* Style: %%tabbedSection .. /% , %%tabs .. /%, %%pills .. /% */ .add('.tabbedSection,.tabs', Tab ) .add('.pills', Tab, { nav:'ul.nav.nav-pills' } ) /* Style: Accordion > %%accordion .. /% > %%leftAccordion .. /% > %%rightAccordion .. /% > %%tabbedAccordion .. /% */ .add('[class^=accordion]', Accordion) .add('[class^=leftAccordion]', Accordion, { type:'pills', position:'pull-left' }) .add('[class^=rightAccordion]', Accordion, { type:'pills', position:'pull-right' }) .add('.tabbedAccordion', Accordion, { type:'tabs' }) .add('.pillsAccordion', Accordion, { type:'pills' }) /* Style: %%category .. /% */ .add( '.category a.wikipage', function(element) { new Wiki.Category(element, Wiki.toPageName(element.href), Wiki.XHRCategories); }) /* BOOTSTRAP Style: %%alert .. /% */ .add('.alert', function(element){ element.addClass('alert-warning alert-dismissable').grab( 'button.close[type="button"][html="&times;"]'.slick() .addEvent('click',function(){ element.dispose(); }), 'top' ); }) /* BOOTSTRAP Style %%quote .. /% */ .add('.quote', function(element){ 'blockquote'.slick().wraps( 'p'.slick().wraps(element)); }) /* Plugin: Viewer > %%viewer [link to youtube, vimeo, some-wiki-page, http://some-external-site ..] /% > [description | url to youtube... | class='viewer'] */ .add('a.viewer, div.viewer a', function( a ){ Viewer.preload(a.href, { width:800, height:600 }, function( element ){ var next = a.getNext(); if( next && next.match('img.outlink') ) next.dispose(); element.addClass('viewport').replaces(a); }); }); /* Plugin: Viewer.Slimbox Injects slimbox button, after each link inside the %%slimbox container. The slimbox button opens a modal overlay box with a rich media viewer. When the %%slimbox container contains multiple links, 'next' and 'previous' buttons are added to navigate between all media. Example: > %%slimbox [any supported link] /% > [link-description | link-url | class='slimbox'] DOM structure: JSPWiki support attachment links (with paperclip), inline images and external links. Notice how inline images are converted to attachement links. (start code) div.slimbox a.attachment[href="url.(png|bmp|tiff|jpg|jpeg|gif)"] Image link a.infolink[href="url] img[src=attachment_small.png] (small jspwiki paperclip) img.inline[src="url2"] a.external[href="url3"] External link img.outlink[src=out.png] (end) becomes (start code) div.slimbox a.attachment[href="url1"] Image link a.slimboxbtn[href="url1"][title=Image link] &raquo; a.infolink[href="url] img[src=attachment_small.png] (small paperclip) a.attachment[href="url2"] url2 a.slimboxbtn[href="url2"][title=url2] &raquo; a.external[href="url3"] External link a.slimboxbtn[href="url3"][title=External link] img.outlink[src=out.png] (end) Example of the short notation with the .slimbox class > a.slimbox[href="url"] Link becomes > a.slimbox[href="url"] Link */ //helper function function filterJSPWikiLinks(element){ return element.match('a') ? [element] : element.getElements( element.match('.slimbox-attachments') ? 'a[href].attachment' : // img:not([src$=/attachment_small.png]):not(.outlink) // a[href].attachment, // a[href].external,a[href].wikipage 'img:not([src$=/attachment_small.png]):not(.outlink),a[href].attachment,a[href].external,a[href].wikipage' ); } wiki.once('body', function( elements ){ //create singleton TheSlimbox TheSlimbox = new Viewer.Slimbox({ hints: { //use defaults as much as possible btn: 'slimbox.btn'.localize(), caption: 'slimbox.caption'.localize() } }); }) // [ link-description | link-url | class='slimbox-link' ] // replaces the link by a slimbox-link .add('a.slimbox-link', function( element ){ TheSlimbox.watch([element]); }) .add('.slimbox-attachments,*[class~=slimbox],*[class~=lightbox]', function( element ){ var arr = filterJSPWikiLinks(element); TheSlimbox.watch(arr, 'button.slimbox-btn'); //jspwiki -- replace inline images by attachment links $$(arr).filter('img[src]').each(function( element ){ 'a.attachment'.slick({ href:element.src, html:element.title||element.alt }).replaces( element ); }); /*FFS: replacing img[src], should also add the info paperclip .grab( [ 'a.infolink',{href:element.src},[ 'img[alt="(info)"]',{src:".../attachment_small.png"} ] ].slick() ) */ }) /* Plugin: Viewer.Carousel (embed auto-rotating media viewer into a wiki page) > %%carousel [link-1] [link-2] .. [link-n]/% => carousel viewer next,previous > %%carousel-auto [link-1] [link-2] .. [link-n]/% => with auto-rotation */ .add( '.carousel', function( element ){ new Viewer.Carousel( filterJSPWikiLinks( element ), { container: element, }); }); /* Plugin: Collapsible.Box, Collapsible.List Create collabsible boxes and (un)ordered lists. The collapse status (open/close) is persisted in a cookie. Depends on: Wiki, Cookie, Cookie.Flag, Collapsible, Collapsible.Box, Collapsible.List > %%collapse > %%collapsebox > %%collapsebox-closed */ //helper function function collapseFn(element, cookie){ var TCollapsible = Collapsible, clazz = element.className, list = "collapse", box = list+"box"; cookie = new Cookie.Flags( 'JSPWikiCollapse' + (cookie || wiki.PageName), { path:wiki.BasePath, duration:20 } ); if( clazz == list ){ new TCollapsible.List(element,{ cookie:cookie }); } else if( clazz.indexOf(box)==0 ){ new TCollapsible.Box(element,{ cookie:cookie, collapsed:clazz.indexOf(box+'-closed')==0 }); } } wiki .add('.page div[class^=collapse]',collapseFn ) .add('.sidebar div[class^=collapse]',collapseFn, 'Sidebar') /* Style: Comment Box Wiki Markup: (start code) %%commentbox .. /% %%commentbox-Caption .... /% %%commentbox !Caption .. /% (end) */ .add('div[class^=commentbox]', CommentBox, { prefix:'commentbox' } ) /* Style: Columns > %%columns(-width) .. /% */ .add( 'div[class*=columns]', Columns, { prefix:'columns' } ) /* Dynamic Style: Code-Prettifier JSPWiki wrapper around http://google-code-prettify.googlecode.com/svn/trunk/README.html TODO: add option to overrule the choice of language: > "bsh", "c", "cc", "cpp", "cs", "csh", "cyc", "cv", "htm", "html", >    "java", "js", "m", "mxml", "perl", "pl", "pm", "py", "rb", "sh", >    "xhtml", "xml", "xsl" Example: > %%prettify {{{ > some code snippet here ... > }}} /% */ .add('div.prettify pre, div.prettify code', function(element){ element.addClass('prettyprint'); //brute-force line-number injection 'pre.prettylines'.slick({ html: element.innerHTML.trim().split('\n').map(function(line,i){ return i+1 }).join('\n') }).inject(element,'before'); }) .once('.prettyprint', prettyPrint) //after element.prettyPrint decoration, prettify them /* Style: Reflection for images > %%reflection-30-50 //size of reflection images is 30% height by 50% wide */ .add('[class^=reflection]', function(element){ var args = "reflection".sliceArgs( element ); if( args ) element.getElements('img').reflect({ height:args[0]/100, width:args[1]/100 }); }) /* Dynamic Style: %%sortable, %%table-filter, %%zebra > %%zebra ... /% => default odd row colors (light grey) > %%zebra-table ... /% => default odd row colors (light grey) > %%zebra-eee ... /% => odd rows get backgroundcolor #eee > %%zebra-pink ... /% => odd rows get backgroundcolor red > %%zebra-eee-red ... /% => odd rows: #eee, even rows: red */ .add('.sortable table', T.Sort, {hints: Object.map({ sort: "sort.click", atoz: "sort.ascending", ztoa: "sort.descending" },String.localize) }) .add('.table-filter table', T.Filter, { hint:"filter.hint".localize() }) /* .add('.table-filter table', function(element){ new T_TableX.Filter(element,{ /--list:['one$','James'],--/ hint:hints.filter}); }) */ .add('.zebra,div[class*=zebra]', function(element){ var args = 'zebra'.sliceArgs(element); element.getElements('table').each(function(table){ new T.Zebra(table, { colors:args }); }); }) /* TODO Combined table styling %%table-striped-bordered-hover-condensed-filter-sort-<color> %%sortable .. /% %%table-filter .. /% %%zebra-table .. /% FFS %%table-scrollable (keep head fixed, max height for the table) .add('div[class^=table-]',function(element){ var args = 'table'.sliceArgs(element), arg, tables = element.getElements('table'), hints = Object.map({ sort: "sort.click", atoz: "sort.ascending", ztoa: "sort.descending", filter: "filter.hint" },String.localize); while(args[0]){ arg = shift(args); if( arg.test('striped|bordered|hover|condensed'){ tables.addClass('table-'+arg); } else if( arg == 'filter' ){ tables.each( function(t){ new T.Filter(t, {hint:hints.filter}); }); } else if( arg == 'sort' ){ tables.each( function(t){ new T.Sort(t, {hints:hints}); }); } } }) */ /* Add BOOTSTRAP Styles Scrollable area's - pre (%%scrollable {{{ ... }}}) */ .add('div.scrollable > pre', function(element){ element.addClass('pre-scrollable'); //decorate pre elements with bootstrap class }) /* Add BOOTSTRAP Font Icon style Convert .icon-<icon-name> into appropriate class-name depending on the font family Glyphicon : .glyphicon.glyphicon-<icon-name> Font-Awesome: .fa.fa-<icon-name> FontJspwiki (via icomoon) : .icon-<icon-name> */ .add('[class^=icon-]', function(element){ //element.className='glyphicon glyph'+element.className; //element.className = 'fa fa-'+element.className.slice(5); }) /* Add BOOTSTRAP */ .add('[class^=list]', function(element){ var args = "list".sliceArgs(element), lists = element.getElements("ul|ol"); args.each( function( arg ){ if( arg.test('unstyled|hover|group|nostyle') ){ lists.addClass( 'list-'+arg ); } if( arg.test('group') ){ lists.each( function(item){ item.getElements('li').addClass('list-group-item'); }); } }); }) /* Labels Support %%label, %%label-default, %%label-primary, %%label-info, %%label-success; %%label-warning, %%label-danger */ .add('*[class^=label]',function(element){ element.addClass( 'label'.fetchContext(element) ); }) /* Plugin: Tips Add mouse-hover Tips to your pages. Depends on Mootools Tips plugin. Wiki-markup: > %%tip ... /% > %%tip-Caption ... /% DOM Structure: (start code) //before div.tip-TipCaption ...tip-body... //after a.tooltip-anchor Tip Caption div.tip-TipCaption ...tip-body... (end) */ .once('*[class^=tip]', function(tips){ var caption, more = 'tip.default.title'.localize(); tips = tips.map( function(tip){ caption = (tip.className.split('-')[1]||more).deCamelize(); return 'a.tip-link'.slick({ text: caption }).wraps(tip); }); Tips( tips ); //activate tips behavior }); }( Wiki ); <file_sep>/*! JSPWiki - a JSP-based WikiWiki clone. Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); fyou may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* Class: UndoRedo The UndoRedo class implements a simple undo/redo stack to save and restore the state of an 'undo-able' object. The object needs to provide a {{getState()}} and a {{putState(obj)}} methods. Whenever the object changes, it should call the UndoRedo onChange() handler. Optionally, event-handlers can be attached for undo() and redo() functions. Arguments: obj - the undo-able object options - optional, see options below Options: maxundo - integer , maximal size of the undo and redo stack (default 20) redo - (optional) DOM element, will get a click handler to the redo() function undo - (optional) DOM element, will get a click handler to the undo() function Example: (start code) var undoredo = new UndoRedo(this, { redoElement:'redoID', undoElement:'undoID' }); //when a change occurs on the calling object which needs to be persisted undoredo.onChange( ); (end) */ var UndoRedo = new Class({ Implements: Options, options: { //redo : redo button selector //undo : undo button selector maxundo:40 }, initialize: function(obj, options){ var self = this, btn = this.btn = { redo:options.redo, undo:options.undo }; self.setOptions(options); self.obj = obj; self.redo = []; self.undo = []; self.btnStyle(); }, /* Function: onChange Call the onChange function to persist the current state of the undo-able object. The UndoRedo class will call the {{obj.getState()}} to retrieve the state info. Arguments: state - (optional) state object to be persisted. If not present, the state will be retrieved via a call to the {{obj.getState()}} function. */ onChange: function(state){ var self = this; self.undo.push( state || self.obj.getState() ); self.redo = []; if(self.undo[self.options.maxundo]){ self.undo.shift(); } self.btnStyle(); }, /* Function: onUndo Click event-handler to recall the state of the object */ onUndo: function(e){ var self = this; if(e){ e.stop(); } //if(self.undo.length > 0){ if(self.undo[0] /*length>0*/){ self.redo.push( self.obj.getState() ); self.obj.putState( self.undo.pop() ); } self.btnStyle(); }, /* Function: onRedo Click event-handler to recall the state of the object after a previous undo action. The state will be reset by means of the {{obj.putState()}} method */ onRedo: function(e){ var self = this; if(e){ e.stop(); } //if(self.redo.length > 0){ if(self.redo[0] /*.length > 0*/){ self.undo.push( self.obj.getState() ); self.obj.putState( self.redo.pop() ); } self.btnStyle(); }, /* Function: btnStyle Helper function to change the css style of the undo/redo buttons. */ btnStyle: function(){ var self = this, btn = self.btn; if(btn.undo){ btn.undo.ifClass( !self.undo[0] /*length==0*/, 'disabled'); } if(btn.redo){ btn.redo.ifClass( !self.redo[0] /*length==0*/, 'disabled'); } } }); <file_sep>/* JSPWiki - a JSP-based WikiWiki clone. Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); fyou may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* Moo-extend: String-extensions Element: ifClass(), addHover(),onHover(), hoverUpdate(), getDefaultValue(), observe() */ Element.implement({ /* Function: ifClass Convenience function. Add or remove a css class from an element depending on a conditional flag. Arguments: flag : (boolean) T_Class : (string) css class name, add on true, remove on false F_Class : (string) css class name, remove on true, add on false Returns: (element) - This Element Examples: > $('page').ifClass( i>5, 'hideMe' ); */ ifClass : function(flag, T_Class, F_Class){ return this.addClass(flag?T_Class:F_Class).removeClass(flag?F_Class:T_Class); }, /* Function: wrapChildren This method moves this Element around its children elements. The Element is moved to the position of the passed element and becomes the parent. All child-nodes are moved to the new element. Arguments: el - DOM element. Returns: (element) This Element. DOM Structure: (start code) //before div#firstElement <children> //javaScript var secondElement = 'div#secondElement'.slick(); secondElement.wrapChildren($('myFirstElement')); //after div#firstElement div#secondElement <children> (end) */ wrapChildren : function(el){ while( el.firstChild ){ this.appendChild( el.firstChild ); } el.appendChild( this ) ; return this; }, /* Function: addHover Shortcut function to add 'hover' css class to an element. This allows to support :hover effects on all elements, also in IE. Arguments clazz - (optional) hover class-name, default is {{hover}} Returns: (element) - This Element Examples: > $('thisElement').addHover(); */ addHover: function( clazz ){ clazz = clazz || 'hover'; return this.addEvents({ mouseenter: function(){ this.addClass(clazz); }, mouseleave: function(){ this.removeClass(clazz); } }); }, /* Function: onHover Convert element into a hover menu. Arguments: toggle - (string,optional) A CSS selector to match the hoverable toggle element Example > $('li.dropdown-menu').onHover('ul'); */ onHover: function( toggle, onOpen ){ var element = this; if( toggle = element.getParent(toggle) ){ element.fade('hide'); toggle.addEvents({ mouseenter: function(){ element.fade(0.9); toggle.addClass('open'); if(onOpen) onOpen(); }, mouseleave: function(){ element.fade(0); toggle.removeClass('open'); } }); } return element; }, /* Function: onToggle Set/reset '.active' class, based on 'data-toggle' attribute. Arguments: toggle - A CSS selector of one or more clickable toggle button A special selector "buttons" is available for style toggling of a group of checkboxes or radio-buttons. (ref. Bootstrap) active - CSS classname to toggle this element (default .active ) Example (start code) wiki.add('div[data-toggle]', function(element){ element.onToggle( element.get('data-toggle') ); }) (end) DOM Structure (start code) //normal toggle case div[data-toggle="button#somebutton"](.active) That .. button#somebutton Click here to toggle that //special toggle case with "buttons" selector div.btn-group[data-toggle="buttons"] label.btn.btn-default(.active) input[type="radio"][name="aRadio"] checked='checked' value="One" /> label.btn.btn-default(.active) input[type="radio"][name="aRadio"] value="Two" /> (end) */ onToggle: function( toggle, active ){ var element = this; if( toggle == "buttons" ){ (toggle = function(e){ //FIXME: differentiate between radioboxes and checkboxes !! element.getElements(".active").removeClass("active"); element.getElements(":checked !").addClass("active"); })(); element.addEvent('click', toggle); } else { //if(!document.getElements(toggle)[0]){ console.log("toggle error:",toggle); } document.getElements(toggle).addEvent('click', function(event){ event.stop(); element.toggleClass( active || 'active'); }); } return element; }, /* Function: getDefaultValue Returns the default value of a form element. Inspired by get('value') of mootools, v1.1 Note: Checkboxes will return true/false depending on the default checked status. ( input.checked to read actual value ) The value returned in a POST will be input.get('value') and is depending on the value set by the 'value' attribute (optional) Returns: (value) - the default value of the element; or false if not applicable. Examples: > $('thisElement').getDefaultValue(); */ getDefaultValue: function(){ var self = this, type = self.get('type'), values = []; switch( self.get('tag') ){ case 'select': Array.from(this.options).each( function(option){ if (option.defaultSelected){ values.push(option.value||option.text); } }); return (self.multiple) ? values : values[0]; case 'input': if( type == 'checkbox' ){ //checkbox.get-value = returns 'on' on some browsers, T/F on others return ('input[type=checkbox]'+(self.defaultChecked?":checked":"")).slick().get('value'); } if( !'radio|hidden|text|password'.test(type) ){ break; } case 'textarea': return self.defaultValue; default: return false; } }, /* Function: groupChildren(start, grab) groups lists of children, which are delimited by certain DOM elements. Arguments - start : (string) css selector to match delimiting DOM elements - grab : (string) css selector, grabs a subset of dom elements and replaces the start element - replacesFn: (callback function) called at the point of replacing the start-element with the grab-element DOM Structure: (start code) //before groupChildren(start,grab) start b b start b //after groupChildren(start,grab) grab [data-inherit="{text:.<start.text>.,id:.<start.id>.}"] b b grab [data-inherit="{text:.<start.text>.,id:.<start.id>.}"] b Example: > el.groupChildren(/hr/i,'div.col'); > el.groupChildren(/h[1-6]/i,'div.col'); > el.groupChildren( container.getTag(), 'div'); */ groupChildren:function(start, grab, replacesFn){ var next, group = grab.slick().inject(this,'top'), firstGroupDone = false; //need at least one start element to get going if( this.getElement(start) ){ while( next = group.nextSibling ){ if( ( next.nodeType!=3 ) && next.match(start) ){ //start a new group if( firstGroupDone ){ group = grab.slick(); } //make a new group if( replacesFn ) replacesFn(group, next); group.replaces( next ); //destroys the matched start element firstGroupDone = true; } else { group.appendChild( next ); //grap all other elements in the group } } } return this; }, /* Function: observe Observe a dom element for changes, and trigger a callback function. Arguments: fn - callback function options - (object) options.event - (string) event-type to observe, default = 'keyup' options.delay - (number) timeout in ms, default = 300ms Example: > $(formInput).observe(function(){ > alert('my value changed to '+this.get('value') ); > }); */ observe: function(callback, options){ var element = this, value = element.get('value'), event = (options && options.event) || 'keyup', delay = (options && options.delay) || 300, timer = null; return element.set({autocomplete:'off'}).addEvent(event, function(){ var v = element.get('value'); if( v != value ){ value = v; //console.log('observer ',v); clearTimeout( timer ); timer = callback.delay(delay, element); } }); } }); <file_sep>/* JSPWiki - a JSP-based WikiWiki clone. Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); fyou may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* Class: Behavior Behavior is a way to initiate certain UI components for elements on the page by a given selector. The callback is only called once of each element. Inspired by: https://github.com/arian/elements-util/blob/master/lib/behavior.js Extended for jspwiki. Example: var behavior = new Behavior() // define a new slider behavior, which initiates a slider class. behavior.add('.slider', function(element){ new Slider(element) }) //this function is invoked once, with all Elements passed as argument behavior.once('.slider', function(elements){ new Slider(elements) }) ... window.addEvent('domready', function(){ behavior.update() }); */ var Behavior = new Class({ initialize: function(){ this.behaviors = []; }, add: function(selector, behavior, options, once){ this.behaviors.push({s: selector, b: behavior, o: options, once:once}); return this; }, once: function(selector, behavior, options){ return this.add(selector, behavior, options, true); }, update: function(){ //console.log(this.behaviors); var cache = "_bhvr", updated, type, nodes; this.behaviors.each( function( behavior ){ nodes = $$(behavior.s); type = typeOf(behavior.b); //console.log("BEHAVIOR ", behavior.once?"ONCE ":"", nodes.length, behavior.s, typeOf(behavior.b) ); if( behavior.once && nodes[0] ){ if( type == 'class'){ new behavior.b(nodes, behavior.o); } else if( type == 'function'){ behavior.b(nodes, behavior.o); } } else { nodes.each( function(node){ updated = node[cache] || (node[cache] = []); if ( updated.indexOf(behavior) == -1 ){ //if( type == 'string' ) node[behavior.b](behavior.o); if( type == 'class'){ new behavior.b(node, behavior.o); } else if( type == 'function'){ behavior.b.call(node, node, behavior.o); } updated.push( behavior ); } }); } }) return this; } }); <file_sep>/*! JSPWiki - a JSP-based WikiWiki clone. Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); fyou may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* Class: Snipe The Snipe class decorates a TEXTAREA object with extra capabilities such as section editing, tab-completion, auto-indentation, smart typing pairs, suggestion popups, toolbars, undo and redo functionality, advanced find & replace capabilities etc. The snip-editor can be configured with a set of snippet commands. See [getSnippet] for more info on how to define snippets. Credit: Snipe (short for Snip-Editor) was inspired by postEditor (by <NAME> aka IceBeat, http://icebeat.bitacoras.com ) and ''textMate'' (http://macromates.com/). It has been written to fit as wiki markup editor for the JSPWIKI project. Arguments: el - textarea element options - optional, see below Options: tab - (string) number of spaces used to insert/remove a tab in the textarea; default is 4 snippets - (snippet-object) set of snippets, which will be expanded when clicking a button or pressing the TAB key. See [getSnippet], [tabSnippet] tabcompletion - (boolean, default false) when set to true, the tabSnippet keywords will be expanded when pressing the TAB key. See also [tabSnippet] directsnips - (snippet-object) set of snippets which are directly expanded on key-down. See [getSnippet], [directSnippet] smartpairs - (boolean, default false) when set to true, the direct snip (aka smart pairs) will be expanded on keypress. See also [directSnippet] buttons - (array of Elements), each button elemnet will bind its click-event with [onButtonClick}. When the click event fires, the {{rel}} attribute or the text of the element will be used as snippet keyword. See also [tabSnippet]. dialogs - set of dialogs, consisting of either a Dialog object, or a set of {dialog-options} for the predefined dialogs suchs as Font, Color and Special. See property [initializeDialogs] and [openDialog] findForm - (object) list of form-controls. See [onFindAndReplace] handler. next - (Element), when pressing Shift-Enter, the textarea will ''blur'' and this ''next'' element will ge the focus. This compensates the overwritting default TAB handling of the browser. onresize - (function, optional), when present, a textarea resize bar with css class {{resize-bar}} is added after the textarea, allowing to resize the heigth of the textarea. This onresize callback function is called whenever the height of the textarea is changed. Dependencies: [Textarea] [UndoRedo] [Snipe.Commands] Example: (start code) new Snipe( "mainTextarea", { snippets: { bold:"**{bold text}**", italic:"''{italic text}''" }, tabcompletion:true, directsnips: { '(':')', '[' : ']' }, buttons: $$('a.tool'), next:'nextInputField' }); (end) */ var Snipe = new Class({ Implements: [Options, Events], Binds: ['sync','shortcut','keystroke','suggest'], options: { tab: " ", //default tab = 4 spaces //autosuggest:false, //tabcompletion:false, //autocompletion:false, snippets: {}, directsnips: {}, //container: null, //DOM element, container for toolbar buttons sectionCursor: 'all', sectionParser: function(){ return {}; } }, initialize: function(el, options){ options = this.setOptions(options).options; var self = this, /* The textarea is cloned into a mainarea and workarea. The workarea is visible and used for the actual editing. It contains either the full document or a particular section. The mainarea is hidden and contains always the full document. On submit, the mainarea is send back to the server. */ main = self.mainarea = $(el), work = main.clone().erase('name') //.clone(true,false), dont copy ID and name .inject( main.hide(), 'before' ), container = options.container || work.form; // Augment the textarea element with extra capabilities // Make sure the content of the mainarea is always in sync with the workarea textarea = self.textarea = new Textarea( work ); self.undoredo = new UndoRedo( self, { undo:container.getElement('[data-cmd=undo]'), redo:container.getElement('[data-cmd=redo]') }); //The Commands class processes all commands // entered via tab-completion, button clicks, dialogs or suggestion dialogs. // Valid commands are given back to the Snipe editor via the onAction event. self.commands = new Snipe.Commands( container, { onOpen: function(/*cmd, eventHdl*/){ /*work.focus();*/ }, onClose: function(){ work.focus(); }, onAction: function(cmd){ self.action(cmd, Array.slice(arguments,1) ); }, //predefined dialogs dialogs: { find: [ Dialog.Find, { //dialog: container.getElement('.dialog.find'), data: { //feed the find dialog with searchable content: selection or all get: function(){ var s = textarea.getSelection(); return (s=='') ? work.value : s; }, set: function(v){ var s = textarea.getSelectionRange(); self.undoredo.onChange(); s.thin ? work.value = v : textarea.setSelection(v); } } }] } }); self.initSnippets( options.snippets ); self.clearContext(); work.addEvents({ keydown: self.keystroke, keypress: self.keystroke, //fixme: any click outside the suggestion block should clear the active snip -- blur ? //blur: self.clearContext.bind(self), //(and hide any open dialogs) keyup: self.suggest, click: self.suggest, change: function(parm){ self.fireEvent('change',parm); } }); //catch shortcut keys when focus on toolbar or textarea container.addEvent('keypress', self.shortcut); }, /* Function: initSnippets Initialize the snippets and collect all shortcut keys and suggestion snips */ initSnippets: function( snips ){ var self = this, cmd, snip, key, dialogs = {}, ismac = Browser.Platform.mac, //navigator.userAgent.indexOf('Mac OS X')!=-1 shortcut = (ismac ? 'meta+' : 'control+'); self.keys = {}; self.suggestions = {}; for( cmd in snips ){ snip = snips[cmd]; if( typeOf(snip)=='string' ){ snip = {snippet:snip}; } Function.from( snip.initialize )(cmd, snip); if( key = snip.key ){ if( key.indexOf('+')<0 ){ key = shortcut+key; } self.keys[key.toLowerCase()] = cmd; } if( typeOf(snip.suggest)=='function' ){ self.suggestions[cmd] = snip; } //check for default snip dialogs -- they have the same name as the command //EG: find:{find:[Dialog.Find,{options}] } if( snip[cmd] ){ dialogs[cmd] = snip[cmd]; } } //initialize all detected dialogs console.log("snip dialogs",Object.keys(dialogs).length); self.commands.addDialogs(dialogs, self.textarea); }, /* Function: toElement Retrieve textarea DOM element; Example: > var snipe = new Snipe('textarea-element'); > $('textarea-element') == snipe.toElement(); > $('textarea-element') == $(snipe); */ toElement: function(){ return $(this.textarea); }, /* Function: get Retrieve some of the public properties of the snip-editor. Arguments: item - textarea|snippets|tabcompletion|directsnips|smartpairs|autosuggest */ get: function(item){ return( /mainarea|textarea/.test(item) ? this[item] : /snippets|directsnips|autosuggest|tabcompletion|smartpairs/.test(item) ? this.options[item] : null ); }, /* Function: set Set/Reset some of the public options of the snip-editor. Arguments: item - snippets|tabcompletion|directsnips|smartpairs|autosuggest value - new value Returns this Snipe object */ set: function(item, value){ if( /snippets|directsnips|autosuggest|tabcompletion|smartpairs/.test(item) ){ this.options[item] = value; } return this; }, /* Function: shortcut. Handle shortcut keys: Ctrl+shortcut key. This is a "Keypress" event handler connected to the container element of the snip editor. Note: Safari seems to choke on Cmd+b and Cmd+i. All other Cmd+keys are fine. !? It seems in those cases, the event is fired on document level only. */ shortcut: function(e){ var key = (e.shift ? 'shift+':'') + (e.control ? 'control+':'') + (e.meta ? 'meta+':'') + (e.alt ? 'alt+':'') + e.key, keycmd = this.keys[key]; //console.log(key); if ( keycmd ){ console.log(this.keys,'shortcut',key,keycmd); e.stop(); this.commands.action( keycmd ); } }, /* Function: keystroke This is a cross-browser keystroke handler for keyPress and keyDown events on the textarea. Note: The KeyPress is used to accept regular character keys. The KeyDown event captures all special keys, such as Enter, Del, Backspace, Esc, ... To work around some browser incompatibilities, a hack with the {{event.which}} attribute is used to grab the actual special chars. Ref. keyboard event paper by <NAME>, http://unixpapa.com/js/key.html Todo: check on Opera Arguments: e - (event) keypress or keydown event. */ keystroke: function(e){ //console.log(e.key, e.code + " keystroke "+e.shift+" "+e.type+"+meta="+e.meta+" +ctrl="+e.control ); if( e.type=='keydown' ){ //Exit if this is a normal key; process special chars with the keydown event if( e.key.length==1 ) return; } else { // e.type=='keypress' //CHECKME //Only process regular character keys via keypress event //Note: cross-browser hack with 'which' attribute for special chars if( !e.event.which /*which==0*/ ){ return; } //CHECKME: Reset faulty 'special char' treatment by mootools //console.log( e.key, String.fromCharCode(e.code).toLowerCase()); e.key = String.fromCharCode(e.code).toLowerCase(); } var self = this, txta = self.textarea, el = $(txta), key = e.key, caret = txta.getSelectionRange(), scroll = el.getScroll(); el.focus(); if( /up|down|esc/.test(key) ){ self.clearContext(); } else if( /tab|enter|delete|backspace/.test(key) ){ self[key](e, txta, caret); } else { self.directSnippet(e, txta, caret); } el.scrollTo(scroll); }, /* Function: enter When the Enter key is pressed, the next line will be ''auto-indented'' or space-aligned with the previous line. Except if the Enter was pressed on an empty line. Arguments: e - event txta - Textarea object caret - caret object, indicating the start/end of the textarea selection */ enter: function(e, txta, caret) { //if( this.hasContext() ){ //fixme //how to 'continue previous snippet ?? //eg '\n* {unordered list item}' followed by TAB or ENTER //snippet should always start with \n; //snippet should have a 'continue on enter' flag ? //} this.clearContext(); if( caret.thin ){ var prevline = txta.getFromStart().split(/\r?\n/).pop(), indent = prevline.match( /^\s+/ ); if( indent && (indent != prevline) ){ e.stop(); txta.insertAfter( '\n' + indent[0] ); } } }, /* Function: backspace Remove single-character directsnips such as {{ (), [], {} }} Arguments: e - event txta - Textarea object caret - caret object, indicating the start/end of the textarea selection */ backspace: function(e, txta, caret) { if( caret.thin && (caret.start > 0) ){ var key = txta.getValue().charAt(caret.start-1), snip = this.getSnippet( this.options.directsnips, key ); if( snip && (snip.snippet == txta.getValue().charAt(caret.start)) ){ /* remove the closing pair character */ txta.setSelectionRange( caret.start, caret.start+1 ) .setSelection(''); } } }, /* Function: delete Removes the next TAB (4spaces) if matched Arguments: e - event txta - Textarea object caret - caret object, indicating the start/end of the textarea selection */ "delete": function(e, txta, caret) { var tab = this.options.tab; if( caret.thin && !txta.getTillEnd().indexOf(tab) /*index==0*/ ){ e.stop(); txta.setSelectionRange(caret.start, caret.start + tab.length) .setSelection(''); } }, /* Function: tab Perform tab-completion function. Pressing a tab can lead to : - expansion of a snippet command cmd and selection of the first parameter - selection of the next snippet parameter (if active snippet) - otherwise, expansion to set of spaces (4) Arguments: e - event txta - Textarea object caret - caret object, indicating the start/end of the textarea selection */ tab: function(e, txta, caret){ var self = this, snips = self.options.snippets, fromStart = txta.getFromStart(), len = fromStart.length, cmd, cmdlen; // ok = false; e.stop(); if( self.options.tabcompletion ){ if( self.hasContext() ){ return self.nextAction(txta, caret); } if( caret.thin ){ //lookup the command backwards from the text preceeding the caret for( cmd in snips ){ cmdlen = cmd.length; if( (len >= cmdlen) && (cmd == fromStart.slice( - cmdlen )) ){ //first remove the command txta.setSelectionRange(caret.start - cmdlen, caret.start) .setSelection(''); return self.commands.action( cmd ); } } } } //if you are still here, convert the tab into spaces self.convertTabToSpaces(e, txta, caret); }, /* Function: convertTabToSpaces Convert tabs to spaces. When no snippets are detected, the default treatment of the TAB key is to insert a number of spaces. Indentation is also applied in case of multi-line selections. Arguments: e - event txta - Textarea object caret - caret object, indicating the start/end of the textarea selection */ convertTabToSpaces: function(e, txta, caret){ var tab = this.options.tab, selection = txta.getSelection(), fromStart = txta.getFromStart(); isCaretAtStart = txta.isCaretAtStartOfLine(); //handle multi-line selection if( selection.indexOf('\n') > -1 ){ if( isCaretAtStart ){ selection = '\n' + selection; } if( e.shift ){ //shift-tab: remove leading tab space-block selection = selection.replace(RegExp('\n'+tab,'g'),'\n'); } else { //tab: auto-indent by inserting a tab space-block selection = selection.replace(/\n/g,'\n'+tab); } txta.setSelection( isCaretAtStart ? selection.slice(1) : selection ); } else { if( e.shift ){ //shift-tab: remove 'backward' tab space-block if( fromStart.test( tab + '$' ) ){ txta.setSelectionRange( caret.start - tab.length, caret.start ) .setSelection(''); } } else { //tab: insert a tab space-block txta.setSelection( tab ) .setSelectionRange( caret.start + tab.length ); } } }, /* Function: setContext Store the active snip. (state) EG, subsequent handling of dialogs. As long as a snippet is active, the textarea gets the css class {{.activeSnip}}. Arguments: snip - snippet object to make active */ hasContext: function(){ return !!this.context.snip; }, setContext: function( snip, suggest ){ this.context = {snip:snip, suggest:suggest}; $(this).addClass('activeSnip'); }, /* Function: clearContext Clear the context object, and remove the css class from the textarea. Also make sure that no dialogs are left open. */ clearContext: function(){ this.context = {}; this.commands.close(); $(this).removeClass('activeSnip').focus(); }, /* Function: getSnippet Retrieve and validate the snippet. Returns false when the snippet is not found or not in scope. About snippets: In the simplest case, you can use snippets to insert plain text that you do not want to type again and again. The snippet is expanded when hitting the Tab key: the ''snippet'' is replaced by ''snippet expansion text''. (start code) var tabSnippets = { <snippet1> : <snippet expansion text>, <snippet2> : <snippet expansion text> } (end) See also [DirectSnippets]. For example, following snippet will expand the ''toc'' text into the TableOfContents wiki plugin call. Don't forget to escape '{' and '}' with a backslash, because they have a special meaning. (see below) Use the '\n' charater to define multi-line snippets. Start the snippet with '\n' to make sure the snippet starts on a new line. (start code) "toc": "\n[\{TableOfContents \}]\n" (end) After tab-completion, the caret is placed just after the expanded snippet. Snippet parameters: If you want, you can put ''{parameters}'' inside the snippet. Pressing the tab will jump to the next parameter. If you are ok with the default value, just tab over it. If not, start typing to overwrite it. (start code) "bold": "__{some bold text}__" (end) You can have multiple ''{parameters}'' too. Pressing more tabs will get you there. (start code) "link": "[{link text}|{pagename}]" (end) Extended snippet syntax: So far we discussed the simple snippet syntax. In order to unlock more advanced snippet features, you'll need to use the extended snippet syntax. (start code) "toc": { snippet : "\n[\{TableOfContents \}]\n" } (end) which is actually the same as (start code) "toc": "\n[\{TableOfContents \}]\n" (end) Snippet synonyms: Instead of defining the snippet text, you can also refer to another snippet. This allows you to create synonyms. (start code) "allow": { synonym: "acl" } (end) Dynamic snippets: Next to static snippet texts, you can also dynamically generate the snippet text through a javascript function. For example, you could use ajax calls to populate the snippet on the fly. The function should return either the string (simple snippet syntax) or a snippet object. (eg return {{ { snippet:"..." } }} ) (start code) "date": function(e, textarea){ return new Date().toLocaleString(); } (end) or (start code) "date": function(e, textarea){ var d = new Date().toLocaleString(); return { 'snippet': d }; } (end) Snippet scope: See [inScope] to see how to restrict the scope of a snippet. Parameter dialog boxes: To help the entry of parameters, you can specify a predefined set of choices for a ''{parameter}'', as a string (with | separator), js array or js object. A parameter dialog box will be displayed to provide easy selection of one of the choices. See [Dialog.Selection]. Example of parameter suggestion-list: (start code) "acl": { snippet: "[\{ALLOW {permission} {principal(,principal)} \}]", permission: "view|edit|modify|comment|rename|upload|delete", "principal(,principal)": "Anonymous|Asserted|Authenticated|All" } } "acl": { snippet: "[\{ALLOW {permission} {principal(,principal)} \}]", permission: [view,edit,modify] } } "acl": { snippet: "[\{ALLOW {permission} {principal(,principal)} \}]", permission: {'Only read access':'view','Read and write access':'edit','R/W, rename, delete access':'modify' } } } (end) Arguments: snips - snippet collection object for lookup of the key key - snippet key. If not present, retreive the key from the textarea just to the left of the caret. (i.e. tab-completion) Returns: Return a snippet object or false. (start code) returned_object = false || { key: "snippet-key", snippet: " snippet-string ", text: " converted snippet-string, no-parameter braces, auto-indented ", parms: [parm1, parm2, "last-snippet-string" ] } (end) */ getSnippet: function( snips, cmd ){ var self = this, txta = self.textarea, fromStart = txta.getFromStart(), snip = snips[cmd], tab = this.options.tab, parms = [], s,last; if( snip && snip.synonym ){ snip = snips[snip.synonym]; } snip = Function.from(snip)(self, [cmd]); if( typeOf(snip) == 'string' ){ snip = { snippet:snip }; } if( !snip || !self.inScope(snip, fromStart) ){ return false; } s = snip.snippet || ''; //parse snippet and build the parms[] array with all {parameters} s = s.replace( /\\?\{([^{}]+)\}/g, function(match, name){ if( match.charAt(0) == '\\' ){ return match.slice(1); } parms.push(name); return name; }).replace( /\\\{/g, '{' ); //and finally, replace the escaped '\{' by real '{' chars //also push the last piece of the snippet onto the parms[] array last = parms.getLast(); if(last){ parms.push( s.slice(s.lastIndexOf(last) + last.length) ); } //collapse \n of previous line if the snippet starts with \n if( s.test(/^\n/) && ( fromStart.test( /(^|[\n\r]\s*)$/ ) ) ) { s = s.slice(1); //console.log("remove leading \\n"); } //collapse \n of subsequent line when the snippet ends with a \n if( s.test(/\n$/) && ( txta.getTillEnd().test( /^\s*[\n\r]/ ) ) ) { s = s.slice(0,-1); //console.log("remove trailing \\n"); } //auto-indent the snippet's internal newlines \n var prevline = fromStart.split(/\r?\n/).pop(), indent = prevline.match(/^\s+/); if( indent ){ s = s.replace( /\n/g, '\n' + indent[0] ); } //complete the snip object snip.text = s; snip.parms = parms; return snip; }, /* Function: inScope Sometimes it is useful to restrict the scope of a snippet, and only allow the snippet expansion in specific parts of the text. The scope parameter allows you to do that by defining start and end delimiting strings. For example, the following "fn" snippet will only expands when it appears inside the scope of a script tag. (start code) "fn": { snippet: "function( {args} )\{ \n {body}\n\}\n", scope: {"<script":"</script"} //should be inside this bracket } (end) The opposite is possible too. Use the 'nScope' or not-in-scope parameter to make sure the snippet is only inserted when not in scope. (start code) "special": { snippet: "{special}", nScope: { "%%(":")" } //should not be inside this bracket }, (end) Arguments: snip - Snippet Object text - (string) used to check for open scope items Returns: True when the snippet is in scope, false otherwise. */ inScope: function(snip, text){ var pattern, pos, scope=snip.scope, nscope=snip.nscope; if( scope ){ if( typeOf(scope)=='function' ){ return scope( this.textarea ); } else { for( pattern in scope ){ pos = text.lastIndexOf(pattern); if( (pos > -1) && (text.indexOf( scope[pattern], pos ) == -1) ){ return 1 /*true*/; } } return false; } } if( nscope ){ for( pattern in nscope ){ pos = text.lastIndexOf(pattern); if( (pos > -1) && (text.indexOf( nscope[pattern], pos ) == -1) ){ return !1 /*false*/; } } } return 1 /*true*/; }, /* Function: directSnippet Direct snippet are invoked immediately when the key is pressed as opposed to a [tabSnippet] which are expanded after pressing the Tab key. Direct snippets are typically used for smart typing pairs, such as {{ (), [] or {}. }} Direct snippets can also be defined through javascript functions or restricted to a certain scope. (ref. [getSnippet], [inScope] ) First, the snippet is retrieved based on the entered character. Then, the opening- and closing- chars are inserted around the selection. Arguments: e - event txta - Textarea object caret - caret object, indicating the start/end of the textarea selection Example: (start code) directSnippets: { '"' : '"', '(' : ')', '{' : '}', "<" : ">", "'" : { snippet:"'", scope:{ "<javascript":"</javascript", "<code":"</code", "<html":"</html" } } } (end) */ directSnippet: function(e, txta, caret){ var self = this, options = self.options, snip = self.getSnippet( options.directsnips, e.key ); if( snip && options.smartpairs ){ e.stop(); txta.setSelection( e.key, txta.getSelection(), snip.snippet ) .setSelectionRange( caret.start+1, caret.end+1 ); } }, /* Function: action This function executes the proper action. The command can be given throug TAB-completion or by pressing a button. It looks up the snippet and inserts its value in the textarea. When text was selected prior to the click event, the selection will be injected in one of the snippet {parameter}. Additionally, when the snippet only contains one {parameter}, the snippet will toggle: i.e. remove the snippet when already present, otherwise insert the snippet. TODO: Prior to the insertion of the snippet, the caret will be moved to the beginning of the line. Prior to the insertion of the snippet, the caret will be moved to the beginning of the next line. Arguments: e - (event) keypress or keydown event. */ action: function( cmd, args ){ var self = this, txta = self.textarea, caret = txta.getSelectionRange(), snip = self.context.snip || self.getSnippet(self.options.snippets, cmd), s; //console.log("Action: "+cmd+" ("+args+") text=["+snip.text+"] parms=["+snip.parms+"] "+!!snip); if( snip ){ s = snip.text; if( snip.action ){ //eg undo, redo return snip.action.call(self, cmd, snip, args ); } self.undoredo.onChange(); if( snip.event ){ return self.fireEvent(snip.event, [cmd, args]); } $(txta).focus(); if( self.options.autosuggest && self.context.suggest ){ return self.suggestAction( cmd, args ); } if( !caret.thin && (snip.parms.length==2) ){ s = self.toggleSnip(txta, snip, caret); //console.log("toggle snippet: "+s+" parms:"+snip.parms); } //inject args into the snippet parms if( args ){ args.each( function(arg){ if(snip.parms.length > 1){ s = s.replace( snip.parms.shift(), arg ); } }); //console.log("inject args: "+s+" "+snip.parms); } //inject selected text into first snippet parm if( !caret.thin && (snip.parms[1] /*length>1*/) ){ s = s.replace( snip.parms.shift(), txta.getSelection() ); //console.log("inject selection: "+s+" "+snip.parms); } //now insert the snippet text txta.setSelection( s ); if( !snip.parms.length/*length==0*/ ){ //when no selection, move caret after the inserted snippet, //otherwise leave the selection unchanged if( caret.thin ){ txta.setSelectionRange( caret.start + s.length ); } //console.log("action:: should we clear this ? " + self.hasContext() ); self.clearContext(); } else { //this snippet has one or more parameters //store the active snip and process the next {parameter} //checkme !! if( !self.hasContext() ){ self.setContext( snip ); } caret = txta.getSelectionRange(); //update new caret self.nextAction(txta, caret); } } }, /* Function: toggleSnip Toggle the prefix and suffix of a snippet. Eg. toggle between {{__text__}} and {{text}}. The selection will be matched against the snippet. Precondition: - the selection is not empty (caret.thin = false) - the snippet has exatly one {parameter} Arguments: txta - Textarea object snip - Snippet object caret - Caret object {start, end, thin} Returns: - (string) replacement string for the selection. By default, returns snip.text - the snip.parms will be set to [] is toggle was executed successfully Eventually the selection will be extended if the prefix and suffix were just outside the selection. */ toggleSnip: function(txta, snip, caret){ var s = snip.text, //get the first and last textual parts of the snippet arr = s.trim().split( snip.parms[0] ), fst = arr[0], lst = arr[1], re = new RegExp( '^\\s*' + fst.trim().escapeRegExp() + '\\s*(.*)\\s*' + lst.trim().escapeRegExp() + '\\s*$' ); if( (fst+lst)!='' ){ s = txta.getSelection(); snip.parms = []; // if pfx & sfx (with optional whitespace) are matched: remove them if( s.test(re) ){ s = s.replace( re, '$1' ); // if pfx/sfx are matched just outside the selection: extend selection } else if( txta.getFromStart().test(fst+'$') && txta.getTillEnd().test('^'+lst) ){ txta.setSelectionRange(caret.start-fst.length, caret.end+lst.length); // otherwise, insert snippet and set caret between pfx and sfx } else { txta.setSelection( fst+lst ).setSelectionRange( caret.start + fst.length ); } } return s; }, /* Method: suggest Suggestion snippets are dialog-boxes appearing as you type. When clicking items in the suggest dialogs, content is inserted in the textarea. */ suggest: function(){ var self = this, txta = self.textarea, caret = txta.getSelectionRange(), fromStart = txta.getFromStart(), suggestions = self.suggestions, cmd, suggest, snip; if( !self.options.autosuggest ) return; for( cmd in suggestions ){ snip = suggestions[cmd]; suggest = snip.suggest(txta, caret); if( suggest /*&& self.inScope(snip, fromStart)*/ ){ if(!suggest.tail) suggest.tail = 0; //ensure default value //console.log( "Suggest: "+ cmd + " [" + JSON.encode(suggest)+"]" ); self.setContext( snip, suggest ); return self.commands.action(cmd, suggest.match); } } //if you got here, no suggestions this.clearContext(); }, /* Method: suggestAction <todo> suggest = { start: start-position , match:'string', tail: length } */ suggestAction: function( cmd, value ){ var self = this, txta = self.textarea, suggest = self.context.suggest, end = suggest.start + suggest.match.length + suggest.tail; //console.log('SuggestAction: '+ cmd+' (' +value + ') [' + JSON.encode(suggest) + ']'); //set the selection to the replaceable text, and inject the new value txta.setSelectionRange( suggest.start, end ).setSelection( value ); //if tail, set the selection on the tail --why ?? if( suggest.tail>0 ){ txta.setSelectionRange( end - suggest.tail, txta.getSelectionRange().end ); } self.clearContext(); return self.suggest(); }, /* Function: nextAction Process the next ''{parameter}'' of the active snippet as you tab along or after you clicked a button or closed a dialog. Arguments: txta - Textarea object caret - caret object, indicating the start/end of the textarea selection */ nextAction: function(txta, caret){ var self = this, snip = self.context.snip, parms = snip.parms, dialog, pos; while( parms[0] /*.length > 0*/ ){ dialog = parms.shift(); pos = txta.getValue().indexOf(dialog, caret.start); //console.log("next action: "+dialog+ " pos:" + pos + " parms: "+parms+" caret:"+caret.start); //found the next {dialog} or possibly the end of the snippet if( (dialog !='') && (pos > -1) ){ if( parms[0] /*.length > 0*/ ){ // select the next {dialog} txta.setSelectionRange( pos, pos + dialog.length ); //invoke the new dialog //console.log('next action: invoke '+dialog+" "+snip[dialog]) self.commands.action( dialog, snip[dialog] ); //remember every selected snippet dialog self.undoredo.onChange(); return; // and retain the context snip for subsequent {dialogs} } else { // no more {dialogs}, move the caret after the end of the snippet txta.setSelectionRange( pos + dialog.length ); } } } self.clearContext(); }, /* Function: getState Return the current state which consist of the content and selection of the textarea. It implements the ''Undoable'' interface called from the [UndoRedo] class. */ getState: function(){ var txta = this.textarea, el = $(txta); return { main: this.mainarea.value, value: el.get('value'), cursor: txta.getSelectionRange(), scrollTop: el.scrollTop, scrollLeft: el.scrollLeft }; }, /* Function: putState Set a state of the Snip editor. This works in conjunction with the [UndoRedo] class. Argument: state - object originally created by the getState funcion */ putState: function(state){ var self = this, txta = self.textarea, el = $(txta); self.clearContext(); self.mainarea.value = state.main; el.value = state.value; el.scrollTop = state.scrollTop; el.scrollLeft = state.scrollLeft; txta.setSelectionRange( state.cursor.start, state.cursor.end ) .fireEvent('change',[state.value]); } }); <file_sep>/* JSPWiki - a JSP-based WikiWiki clone. Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); fyou may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ //TODO: refactor me /* Javascript routines to support JSPWiki Group management GroupContent.jsp div#viewgroup form#deleteGroup GroupTab.jsp form#groupForm NewGroupContent.jsp */ Wiki.add('#groupForm',function(form){ }); var WikiGroup = { MembersID : "membersfield", //GroupTltID : "grouptemplate", GroupID : "groupfield", NewGroupID : "newgroup", GroupInfoID : "groupinfo", CancelBtnID : "cancelButton", SaveBtnID : "saveButton", CreateBtnID : "createButton", DeleteBtnID : "deleteButton", groups : { "(new)": { members:"", groupInfo:"" } }, cursor : null, isEditOn : false, isCreateOn : false, putGroup: function(group, members, groupInfo, isSelected){ this.groups[group] = { members: members, groupInfo: groupInfo }; var g = $("grouptemplate"); gg = g.clone().removeProperty('id').setHTML(group).inject(g.getParent()).show(); if(isSelected || !this.cursor) this.onMouseOverGroup(gg); } , onMouseOverGroup: function(node){ if(this.isEditOn) return; this.setCursor(node); var g = this.groups[ (node.id == this.GroupID) ? "(new)": node.innerHTML ]; $(this.MembersID).value = g.members; $(this.GroupInfoID).innerHTML = g.groupInfo; } , setCursor: function(node){ if(this.cursor) $(this.cursor).removeClass('cursor'); this.cursor = $(node).addClass('cursor'); } , //create new group: focus on input field onClickNew: function(){ if(this.isEditOn) return; this.isCreateOn = true; $(this.MembersID).value = ""; this.toggle(); } , //toggle edit status of Group Editor toggle: function(){ this.isEditOn = !this.isEditOn; //toggle $(this.MembersID ).disabled = $(this.SaveBtnID ).disabled = $(this.CreateBtnID).disabled = $(this.CancelBtnID).disabled = !this.isEditOn; var del = $(this.DeleteBtnID); if(del) del.disabled = this.isCreateOn || !this.isEditOn; if(this.isCreateOn) { $(this.CreateBtnID).toggle(); $(this.SaveBtnID).toggle() }; var newGrp = $(this.NewGroupID), members = $(this.MembersID); if(this.isEditOn){ members.getParent().addClass("cursor"); newGrp.disabled = !this.isCreateOn; if(this.isCreateOn) { newGrp.focus(); } else { members.focus(); } } else { members.getParent().removeClass("cursor"); if(this.isCreateOn){ this.isCreateOn = false; newGrp.value = newGrp.defaultValue; members.value = ""; } newGrp.blur(); members.blur(); newGrp.disabled = false; } } , // submit form to create new group onSubmitNew: function(form, actionURL){ var newGrp = $(this.NewGroupID); if(newGrp.value == newGrp.defaultValue){ alert("group.validName".localize()); newGrp.focus(); } else this.onSubmit(form, actionURL); } , // submit form: fill out actual group and members info onSubmit: function(form, actionURL){ if(! this.cursor) return false; var g = (this.cursor.id == this.GroupID) ? $(this.NewGroupID).value: this.cursor.innerHTML; /* form.action = actionURL; -- doesn't work in IE */ form.setAttribute("action", actionURL) ; form.group.value = g; form.members.value = $(this.MembersID).value; form.action.value = "save"; Wiki.submitOnce(form); form.submit(); } } <file_sep>/*! JSPWiki - a JSP-based WikiWiki clone. Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); fyou may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* Class: Wiki.Edit The WikiEdit class implements the JSPWiki's specific editor, with support for JSPWIki's markup, suggestion popups, ajax based page preview, etc... It uses an enhanced textarea based on the [SnipEditor] class. */ !function( wiki ){ var container, textarea, snipe, preview, previewcache, sectionDropDown; wiki.add('#editform', function( element ){ container = element; textarea = container.getElement('.editor'); preview = container.getElement('.ajaxpreview'); sectionDropDown = container.getElement('[data-sections]'); onbeforeunload( textarea ); snipe = new Snipe( textarea, { snippets: wiki.Snips, directsnips: wiki.DirectSnips, onChange: preview ? livepreview : null, onConfig: config }); if( wiki.Context == 'edit' && sectionDropDown ){ new Snipe.Sections( sectionDropDown, { snipe: snipe, parser: sectionParser }); } resizer( element.getElement('.resizer'), 'EditorCookie' ); /* Initialize the configuration checkboxes: set the checkbox according to the wiki-prefs (cookie) and configure the snip-editor. */ ['tabcompletion','smartpairs','autosuggest','livepreview','previewcolumn'].each( function(cmd){ var el = container.getElement('[data-cmd='+cmd+']'); if( el ){ //console.log('init config ',cmd); el.checked = !!wiki.get(cmd); config( cmd ); } }) }); /* Function: onbeforeunload Install an onbeforeunload handler, which is called ''before'' the page unloads. The user gets a warning in case the textarea was changed, without saving. The onbeforeunload handler is automatically removed on regular exit of the page. */ function onbeforeunload( textarea ){ window.onbeforeunload = function(){ if( textarea.value != textarea.defaultValue ){ return "edit.areyousure".localize(); } }; textarea.getParent('form').addEvent('submit', function(){ window.onbeforeunload = null; }); } /* Function: makeResizable Activate the resize handle. While dragging the textarea, also update the size of the preview area. Store the new height in the 'EditorSize' prefs cookie. Arguments: element - draggable resize handle (DOM element) options - { cookie: name of the cookie to persist the editor size across pageloads } Globals: wiki - main wiki object, to get/set preference fields textarea - resizable textarea (DOM element) preview - preview (DOM element) */ function resizer( handle, cookie ){ var height = 'height', textarea = snipe.toElement(), size = wiki.get(cookie), y; function dragging(add){ handle.ifClass(add,'dragging'); } if( size ){ textarea.setStyle(height, size); preview.setStyle(height, size); } if( handle ){ //console.log("resizer ",textarea,preview); textarea.makeResizable({ handle: handle, modifiers: { x:null }, onDrag: function(){ y = this.value.now.y; preview.setStyle(height, y); wiki.set(cookie, y); }, onBeforeStart: dragging.pass(true), onComplete: dragging.pass(false), onCancel: dragging.pass(false) }); } } /* Function: livepreview Linked as onChange handler to the SnipEditor. Make AJAX call to the backend to convert the contents of the textarea (wiki markup) to HTML. FIXME: should work bothways. wysiwyg <-> wikimarkup */ function livepreview(v){ var text = snipe.toElement().get('value'); if( !$('livepreview').checked ){ //clean preview area if( previewcache ){ preview.empty(); previewcache = null; } } else if( previewcache != text.length ){ previewcache = text.length; //return preview.set('html',preview.get('html')+' Lorem ipsum'); //test code new Request.HTML({ url: wiki.XHRPreview, data: { page: wiki.PageName, wikimarkup: text }, update: preview, onRequest: function(){ preview.addClass('loading'); }, onComplete: function(){ preview.removeClass('loading'); wiki.update(); } }).send(); } } /* Function: config Change the configuration of the snip-editor, and store it in the wiki-prefs. (cookie) The configuration is read from DOM checkbox elements. The name of the DOM checkboxes correponds with the cookie names, and the cookienames correspond with the snip-editor state attribute, if applicable. - invoked by initconfig, to initialize checkboxes with cookie values. - invoked when the config cmd checkboxes are clicked (ref. snippet commands) Argument: cmd - which configuration command has been triggered or needs to be initialized. */ function config( cmd ){ var el = container.getElement('[data-cmd='+cmd+']'), state, editarea; if( el ){ wiki.set(cmd, state = el.checked); if( cmd.test(/livepreview|previewcolumn/) ){ editarea = container.getElement('.edit-area').ifClass(state,cmd); if( cmd == 'livepreview' ){ container.getElement('[data-cmd=previewcolumn]').disabled = !state; } else { //cmd == 'previewcolumn' if(state){ editarea.adopt(preview); } else { preview.inject( container.getElement('.resizer'), 'after'); } } } snipe.set(cmd, state).fireEvent('change'); } } /* Function: sectionParser Convert a jspwiki-markup page to an array of page sections. Sections are marked with a JSPWiki header line. ( !, !! !!! ) This function is a callback function for the [SnipEditor]. It is called by [snipeditor.buildToc] every time the textarea of the snipeditor is being changed. Returns: This function returns a array of objects [{title, start, depth}] title - (string) plain title of the section (no wiki markup) start - (number) offset within the text string where this section starts depth - (number) nesting level of the section 0,1...n */ function sectionParser( text ){ var result = [], DELIM = '\u00a4', tt = text // mask any header markup inside a {{{ ... }}} but keep length of the text unchanged! .replace(/\{\{\{([\s\S]*?)\}\}\}/g, function(match){ return match.replace( /^!/mg, ' ' ); }) // break string up into array of headers and section-bodies : // [0] : text prior to the first header // [1,odd] : header markup !, !! or !!! // [2,even] : remainder of the section, starting with header title .replace( /^([!]{1,3})/mg, DELIM+"$1"+DELIM ) .split(DELIM), pos = tt.shift().length, //get length of the first element, prior to first section count = tt.length, i, hlen, title; for( i=0; i<count; i=i+2 ){ hlen = tt[i].length; //take first line title = tt[i+1].split(/[\r\n]/)[0] //remove unescaped(~) inline wiki markup __,'',{{,}}, %%(*), /% .replace(/(^|[^~])(__|''|\{\{|\}\}|%%\([^\)]+\)|%%\S+\s|%%\([^\)]+\)|\/%)/g,'$1') //and remove wiki-markup escape chars ~ .replace(/~([^~])/g, '$1'); //depth: convert length of header markup (!!!,!!,!) into #depth-level: 3,2,1 => 0,1,2 result.push({ title:title, start:pos, depth:3-hlen }); pos += hlen + tt[i+1].length; } return result; } }(Wiki); <file_sep>/* JSPWiki - a JSP-based WikiWiki clone. Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); fyou may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* Class: Dialog.Font The Dialog.Font is a Dialog.Selection object, to selecting a font. Each selectable item is redered in its proper font. Arguments: options - optional, see options below Options: fonts - (object) set of font definitions with name/value others - see Dialog.Selection options Inherits from: [Dialog.Selection] Example (start code) dialog= new Dialog.Font({ fonts:{'Font name1':'font1', 'Font name2':'font2'}, caption:"Select a Font", onSelect:function(value){ alert( value ); } }); (end) */ Dialog.Font = new Class({ Extends:Dialog.Selection, options: { fonts: { 'arial':'Arial', 'comic sans ms':'Comic Sans', 'courier new':'Courier New', 'garamond':'Garamond', 'georgia':'Georgia', 'helvetica':'Helvetica', 'impact':'Impact', 'times new roman':'Times', 'tahoma':'Tahoma', 'trebuchet ms':'Trebuchet', 'verdana':'Verdana' } }, initialize:function(options){ var self = this, fonts = options.fonts; //options.cssClass = '.font'+(options.cssClass||'') this.setClass('.font',options); options.body = fonts ? fonts : self.options.fonts; self.parent(options); self.getItems().each(function(li){ li.setStyle('font-family', li.get('title') ); }); } }); <file_sep>/* JSPWiki - a JSP-based WikiWiki clone. Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); fyou may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* Class: Textarea The textarea class enriches a TEXTAREA element, and provides cross browser support to handle text selection: get and set the selected text, changing the selection, etc. It also provide support to retrieve and validate the caret/cursor position. Example: (start code) <script> var txta = new Textarea( "mainTextarea" ); </script> (end) */ var Textarea = new Class({ Implements: [Options,Events], //options: { onChange:function(e){} ); initialize: function(el,options){ var self = this, txta = self.ta = $(el), lastValue, lastLength = -1, changeFn = function(e){ var v = txta.value; if( v.length != lastLength || v !== lastValue ){ self.fireEvent('change', e); lastLength = v.length; lastValue = v; } }; self.setOptions(options); txta.addEvents({ change:changeFn, keyup:changeFn }); //Create shadow div to support pixel measurement of the caret in the textarea //self.taShadow = new Element('div',{ // styles: { position:'absolute', visibility:'hidden', overflow:'auto'/*,top:0, left:0, zIndex:1, white-space:pre-wrap*/ } //}) self.taShadow = new Element('div[style=position:absolute;visibility:hidden;overflow:auto]') .inject(txta,'before') .setStyles( txta.getStyles( 'font-family0font-size0line-height0text-indent0padding-top0padding-right0padding-bottom0padding-left0border-left-width0border-right-width0border-left-style0border-right-style0white-space0word-wrap' .split(0) )); return this; }, /* Function: toElement Return the DOM textarea element. This allows the dollar function to return the element when passed an instance of the class. (mootools 1.2.x) Example: > var txta = new Textarea('textarea-element'); > $('textarea-element') == txta.toElement(); > $('textarea-element') == $(txta); //mootools 1.2.x */ toElement: function(){ return this.ta; }, /* Function: getValue Returns the value (text content) of the textarea. */ getValue: function(){ return this.ta.value; }, /* Function: slice Mimics the string slice function on the value (text content) of the textarea. Arguments: Ref. javascript slice function */ slice: function(start,end){ return this.ta.value.slice(start,end); }, /* Function: getFromStart Returns the first not selected part of the textarea, till the start of the selection. */ getFromStart: function(){ return this.slice( 0, this.getSelectionRange().start ); }, /* Function: getTillEnd Returns the last not selected part of the textarea, starting from the end of the selection. */ getTillEnd: function(){ return this.slice( this.getSelectionRange().end ); }, /* Function: getSelection Returns the selected text as a string Note: IE fixme: this may return any selection, not only selected text in this textarea //if(Browser.Engine.trident) return document.selection.createRange().text; */ getSelection: function(){ var cur = this.getSelectionRange(); return this.slice(cur.start, cur.end); }, /* Function: setSelectionRange Selects the selection range of the textarea from start to end Arguments: start - start position of the selection end - (optional) end position of the seletion (default == start) Returns: Textarea object */ setSelectionRange: function(start, end){ var txta = this.ta, value,diff,range; if(!end){ end = start; } if( txta.setSelectionRange ){ txta.setSelectionRange(start, end); } else { value = txta.value; diff = value.slice(start, end - start).replace(/\r/g, '').length; start = value.slice(0, start).replace(/\r/g, '').length; range = txta.createTextRange(); range.collapse(1 /*true*/); range.moveEnd('character', start + diff); range.moveStart('character', start); range.select(); //textarea.scrollTop = scrollPosition; //textarea.focus(); } return this; }, /* Function: getSelectionRange Returns an object describing the textarea selection range. Returns: {{ { 'start':number, 'end':number, 'thin':boolean } }} start - coordinate of the selection end - coordinate of the selection thin - boolean indicates whether selection is empty (start==end) */ /* ffs getIERanges: function(){ this.ta.focus(); var txta = this.ta, range = document.selection.createRange(), re = this.createTextRange(), dupe = re.duplicate(); re.moveToBookmark(range.getBookmark()); dupe.setEndPoint('EndToStart', re); return { start: dupe.text.length, end: dupe.text.length + range.text.length, length: range.text.length, text: range.text }; }, */ getSelectionRange: function(){ var txta = this.ta, caret = { start: 0, end: 0 /*, thin: true*/ }, range, dup, value, offset; if( txta.selectionStart!=null ){ caret = { start: txta.selectionStart, end: txta.selectionEnd }; } else { range = document.selection.createRange(); //if (!range || range.parentElement() != txta){ return caret; } if ( range && range.parentElement() == txta ){ dup = range.duplicate(); value = txta.value; offset = value.length - value.match(/[\n\r]*$/)[0].length; dup.moveToElementText(txta); dup.setEndPoint('StartToEnd', range); caret.end = offset - dup.text.length; dup.setEndPoint('StartToStart', range); caret.start = offset - dup.text.length; } } caret.thin = (caret.start==caret.end); return caret; }, /* Function: setSelection Replaces the selection with a new value (concatenation of arguments). On return, the selection is set to the replaced text string. Arguments: string - string to be inserted in the textarea. If multiple arguments are passed, all strings will be concatenated. Returns: Textarea object, with a new selection Example: > txta.setSelection("new", " value"); //replace selection by 'new value' */ setSelection: function(){ var value = Array.from(arguments).join('').replace(/\r/g, ''), txta = this.ta, scrollTop = txta.scrollTop, //cache top start,end,v,range; if( txta.selectionStart!=null ){ start = txta.selectionStart; end = txta.selectionEnd; v = txta.value; //txta.value = v.substr(0, start) + value + v.substr(end); txta.value = v.slice(0, start) + value + v.substr(end); txta.selectionStart = start; txta.selectionEnd = start + value.length; } else { txta.focus(); range = document.selection.createRange(); range.text = value; range.collapse(1 /*true*/); range.moveStart("character", -value.length); range.select(); } txta.focus(); txta.scrollTop = scrollTop; txta.fireEvent('change'); return this; }, /* Function: insertAfter Inserts the arguments after the selection, and puts caret after inserted value Arguments: string( one or more) - string to be inserted in the textarea. Returns: Textarea object */ insertAfter: function(){ var value = Array.from(arguments).join(''); return this.setSelection( value ) .setSelectionRange( this.getSelectionRange().start + value.length ); }, /* Function: isCaretAtStartOfLine Returns boolean indicating whether caret is at the start of a line. */ isCaretAtStartOfLine: function(){ var i = this.getSelectionRange().start; return( (i<1) || ( this.ta.value.charAt( i-1 ).test( /[\n\r]/ ) ) ); }, /* Function: getCoordinates Returns the absolute coordinates (px) of the character at a certain offset in the textarea. Default returns pixel coordinates of the selection. Credits: Inspired by http://github.com/sergeche/tx-content-assist. Arguments: offset - character index If omitted, the pixel position of the caret is returned. Returns: {{ { top, left, width, height, right, bottom } }} */ getCoordinates: function( offset ){ var txta = this.ta, taShadow = this.taShadow, delta = 0, el,css,style,t,l,w,h; //prepare taShadow css = txta.getStyles(['padding-left','padding-right','border-left-width','border-right-width']); for(style in css){ delta +=css[style].toInt() } //default offset is the position of the caret if( !offset ){ offset = this.getSelectionRange().end; } el = taShadow.set({ styles: { width: txta.offsetWidth - delta, height: txta.getStyle('height') //ensure proper handling of scrollbars - if any }, //FIXME: should we put the full selection inside the <i></i> bracket ? (iso a single char) html: txta.value.slice(0, offset) + '<i>A</i>' + txta.value.slice(offset+1) }).getElement('i'); t = txta.offsetTop + el.offsetTop - txta.scrollTop; l = txta.offsetLeft + el.offsetLeft - txta.scrollLeft; w = el.offsetWidth; h = el.offsetHeight; return {top:t, left:l, width:w, height:h, right:l+w, bottom:t+h} } }); <file_sep>/*! JSPWiki - a JSP-based WikiWiki clone. Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); fyou may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* Class: SnipEditor.Sections This dialog displays the list of page sections. A page section includes the header (all) - allows to select all sections (auto generated) start-of-page - only present when first section starts on an offset > 0 section1..n - section titles, with indentation level depending on their weight The set of sections is generated by the parseSections() callback handler. This parser returns an array of section 'descriptors': > [ {title:text, start:char-offset, indent:indentation-level}, ... ] Clicking an entry triggers the updateSections() callback handler. FIXME: why not fire an onAction event (similar to other dialogs) Depends: Snipe */ Snipe.Sections = new Class({ Implements: [Events], Binds: ['show','update','action'], options: { //snipe:snip-editor //parser: function all: "( all )".localize(), startOfPage: "Start of Page".localize() }, initialize: function(element, options){ var self = this; self.element = element //dropdown menu .onHover( self.container = element.get('data-sections'), self.show ) .addEvent( 'click:relay(a)', self.action ); self.container = element.getParent( element.get('data-sections') ); self.parser = options.parser; self.main = options.snipe.get('mainarea'); self.work = options.snipe.toElement().addEvents({ keyup: self.update, change: self.update }); self.parse(); self.action( location.search ); //url?section=0..n self.show(); }, /* Function: parse Invoke the external parser on the contents of the main textarea. This external parser should return an array with an entry for each section: [ {title:text, start:char-offset, depth:nesting level}, ... ] > 0 : start-of-page (if applicable) => title=s-1 => cursor=-1 > 1..n : page sections => title=s0..sn => cursor=0..n */ parse: function(){ this.sections = this.parser( this.main.value ); }, /* Function: onOpen UPDATE/RFEFRESH the textarea section dialog. Build the DOM list-items (start code) ul.dropdown-menu li a.indent-0.section-2 (all) li a.indent-0.section-1 Start Of Page li.divider li a.indent-0.section0 Title-Section-0 li a.indent-0.section1 Title-Section-1 ... li a.indent-0.section99 Title-Section-2 (end) */ //onOpen: function( dialog ){ show: function( ){ var options = this.options, data = [], sections = this.sections, addItem = function(indent,name,offset){ data.push('li',['a.indent-'+indent+'.section'+offset,{ html:name }]); } addItem(0, options.all ,-2); if( sections[0] ){ if( sections[0].start > 0 ){ addItem(0, options.startOfPage, -1); } data.push('li.divider'); sections.each( function(item, idx){ addItem( item.depth, item.title.trunc(36), idx ); }); } this.element.empty().adopt( data.slick() ); }, /* Function: update Make sure that changes to the work textarea are propagated to the main textarea. This functions handles the correct insertion of the changed section into the main textarea. */ update: function(){ //console.log("Sections: update"); var self = this, main = self.main, work = self.work.value, sections = self.sections, s = main.value, //insert \n to ensure the next section always starts on a new line. linefeed = (work.slice(-1) != '\n') ? '\n' : ''; //console.log('change txta: from='+sections.begin+ ' end='+sections.end); main.value = s.slice(0, self.begin) + work + linefeed + s.slice(self.end); self.end = self.begin + work.length; self.parse(); }, /* Function: onAction This function copies the selected section from the main to the work textarea. It is invoked at initialization and through the dialog onAction click handler. Arguments: item - index of selected section: all, -1, 0..n */ //onAction:function( item ){ /* setValue: function(value){ }, action: function(item){ var value = item.get('title'); this.setValue(value).parent(value); }, */ action:function( item ){ var self = this, main = self.main.value, sections = self.sections, begin = 0, end = main.length; if( item ){ //item.target => event.target; this is an onclick invocation if( item.target ) item = item.target.className; //section-2=All, section-1=StartOfPage, section0..section99=rest item = ( item.match( /section=?(-?\d+)/ )||[,-2])[1].toInt(); if( item == -1 ){ //show the Start Of Page, prior to the first real section end = sections[0].start; } else if(item >= 0 && sections[item] ){ begin = sections[item].start; //if( item+1 < sections.length ){ end = sections[item+1].start; } if( sections[item+1] ){ end = sections[item+1].start; } } } self.work.value = main.slice(begin, end); self.begin = begin; self.end = end; //now close the hover menu and focus the text-area... self.container.removeClass('open'); self.container.ifClass( item >= -1, 'section-selected'); } });
549c3ac020db0bcf20fd15f431d40ad6fb6a690e
[ "JavaScript" ]
15
JavaScript
linetor/JSPAnalysis
b40d8ed3d6d485b9a3fffabdabfadb1d7fca4be7
3c270bd5dbe256883340976a35f1a461f30f2829
refs/heads/master
<repo_name>kingsdigitallab/african-rock-art<file_sep>/_pages/country.md --- layout: country_index permalink: /country/ title: Countries collection: coll_country ---<file_sep>/_coll_country/malawi.md --- contentful: sys: id: 3Rc64q2rIcq4sGuGywWmAm created_at: !ruby/object:DateTime 2015-12-08 11:21:35.564000000 Z updated_at: !ruby/object:DateTime 2018-05-17 16:56:05.842000000 Z content_type_id: country revision: 12 name: 'Malawi ' slug: malawi col_url: http://www.britishmuseum.org/research/collection_online/search.aspx?people=197356&place=107993%7C107992%7C108205%7C107988%7C107990%7C107989%7C107991%7C107982%7C27049 map_progress: true intro_progress: true image_carousel: - sys: id: 3cyuIf03T2A0AsgWwoWcgm created_at: !ruby/object:DateTime 2016-07-27 07:46:34.288000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:49:55.624000000 Z title: '2013,2034.20243' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3739870&partId=1&searchText=MALMPH0070006&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/3cyuIf03T2A0AsgWwoWcgm/854c599e052c9ed2e5458ff22437bc17/MALMPH0070006.jpg" - sys: id: 64o0AnaZnGAiWmaMIImUA8 created_at: !ruby/object:DateTime 2016-07-27 07:46:34.232000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:50:40.402000000 Z title: '2013,2034.20144' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3738287&partId=1&searchText=MALTWA0010013&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/64o0AnaZnGAiWmaMIImUA8/74fb87e6d78416403b25cc95fe0929ba/MALTWA0010013.jpg" - sys: id: 5Et44XU3HUQiOeSAY0yIMY created_at: !ruby/object:DateTime 2016-07-27 07:46:34.082000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:51:20.705000000 Z title: '2013,2034.20354' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3733432&partId=1&searchText=MALPHA0010017&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/5Et44XU3HUQiOeSAY0yIMY/0e7c2c118b52323fe13dea781164c232/MALPHA0010017.jpg" featured_site: sys: id: 5C6UTnDXt6A4q6ggIcYMmu created_at: !ruby/object:DateTime 2016-07-27 07:45:11.921000000 Z updated_at: !ruby/object:DateTime 2016-07-27 08:51:26.975000000 Z content_type_id: featured_site revision: 5 title: 'Namzeze, Malawi ' slug: namzeze chapters: - sys: id: 5kJvUt9jLqo0GuIoWskUgA created_at: !ruby/object:DateTime 2016-07-27 07:45:24.101000000 Z updated_at: !ruby/object:DateTime 2016-07-27 08:32:20.393000000 Z content_type_id: chapter revision: 2 title_internal: 'Malawi: featured site, chapter 1' body: 'Namzeze, one of the most emblematic sites in the Chongoni rock art area, is currently one of the three that can be visited and is open to the public. Unlike many of the other sites, which are grouped together, the Namzeze shelter is isolated in the centre of the protected area. Located in a position overlooking the valley towards the Chongoni Hill, the impressive rock face of Namzeze contains some of the best examples of both traditions of Malawian rock art, the red schematic and white paintings. The site also has a strong symbolism for the Chewa people who still inhabit the area and for whom the white paintings of the later period still have deep spiritual implications. ' - sys: id: MUbQnik9qKECmGamGEkKa created_at: !ruby/object:DateTime 2016-07-27 07:45:24.019000000 Z updated_at: !ruby/object:DateTime 2017-01-24 16:33:30.093000000 Z content_type_id: image revision: 3 image: sys: id: 1IFNGAi4IkScieYwOmGiMA created_at: !ruby/object:DateTime 2016-07-27 07:46:38.189000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:38.189000000 Z title: MALDED0060001 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1IFNGAi4IkScieYwOmGiMA/c57b23e18a40a00a63f25361a859805e/MALDED0060001.jpg" caption: View of the landscape from Namzeze, with two signs indicating the presence of rock art paintings and codes of behaviour in the foreground. 2013,2034.19844 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3730077&partId=1 - sys: id: 5R7b3Vb7H2UueCms0uC6Cy created_at: !ruby/object:DateTime 2016-07-27 07:45:23.819000000 Z updated_at: !ruby/object:DateTime 2017-01-24 16:34:17.661000000 Z content_type_id: image revision: 3 image: sys: id: 3mGBPrPBdYqWW4MUUissms created_at: !ruby/object:DateTime 2016-07-27 07:46:38.998000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:38.998000000 Z title: MALDED0060017 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3mGBPrPBdYqWW4MUUissms/0989042b0914b15d42be755ae787f5de/MALDED0060017.jpg" caption: Rock art panel with red and white depictions. Namzeze. 2013,2034.19860 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3730116&partId=1 - sys: id: 1DWS9OfqHuK6Sca6IMYEEU created_at: !ruby/object:DateTime 2016-07-27 07:45:23.189000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:45:23.189000000 Z content_type_id: chapter revision: 1 title_internal: 'Malawi: featured site, chapter 2' body: "The superimpositions in the panel above show that the red, schematic paintings covering most of the rock face are undoubtedly older than those made in white. Representations include a multitude of geometric signs: series of parallel lines, grid-style shapes, concentric ovals and circular shapes made with series of dots. In some cases the red signs were infilled with series of tiny white dots, a feature uncommon in the red schematic rock art depictions but with the best examples represented here in Namzeze. Its interpretation, as with most geometric depictions, is a challenging issue, but these types of paintings have been traditionally related to ancestors of Batwa people, hunter-gatherers, who inhabited the region until the 1800s. Studies of Batwa ethnography and cosmology point to these places as related to fertility and rainmaking ceremonies. It is difficult to establish the chronology. The oldest occupation documented in the region is dated to the mid-first millennium BC, and the red images precede the arrival of the Chewa people in the 2nd millennium AD, responsible for the white paintings style, but there is no datable evidence for the paintings. \n" - sys: id: 1sxQJiwCfecQeO88iQiQgm created_at: !ruby/object:DateTime 2016-07-27 07:45:23.173000000 Z updated_at: !ruby/object:DateTime 2017-01-24 16:34:50.814000000 Z content_type_id: image revision: 2 image: sys: id: 26hf0yyVDWY6MAGWQeiaMY created_at: !ruby/object:DateTime 2016-07-27 07:46:39.075000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:39.075000000 Z title: MALNAM0010015 description: url: "//images.ctfassets.net/xt8ne4gbbocd/26hf0yyVDWY6MAGWQeiaMY/d24ebe749ebd39df56c7587ec2ab9825/MALNAM0010015.jpg" caption: Detail of red geometric sign infilled with white dots. Namzeze. 2013,2034. 20283 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3730246&partId=1 - sys: id: 4NKmod8inm0CKoKWeIE4CW created_at: !ruby/object:DateTime 2016-07-27 07:45:23.031000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:45:23.031000000 Z content_type_id: chapter revision: 1 title_internal: 'Malawi: featured site, chapter 3' body: The second type of painting found in Namzeze is radically different and depicts mainly quadrupeds and birds, as well as some geometric symbols and a car, proof of a relatively recent date for some of these paintings. Quadrupeds have a very characteristic rectangular body and hooves that in some cases are represented as feet. The technique is very different too, consisting of white clay daubed on the wall with the fingers. These white figures usually appear surrounding the previous depictions, in some rare occasions overlapping them. In this case, the authorship, chronology and interpretation of the paintings are more straightforward. Researchers agree that these types of paintings have been made by the Chewa, a group of farmers that arrived to the region around the 16th century and have maintained rock art painting traditions until the 20th century (as the car represented in this shelter proves). - sys: id: 5LnKSbFOfuiEwG4gKk2muG created_at: !ruby/object:DateTime 2016-07-27 07:45:22.972000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:45:22.972000000 Z content_type_id: image revision: 1 image: sys: id: 1AdufAw4d6U6ioCOEiQyye created_at: !ruby/object:DateTime 2016-07-27 07:46:39.002000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:39.002000000 Z title: MALDED0060019 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1AdufAw4d6U6ioCOEiQyye/d6ab356b64107c958388d56ebc74a7e9/MALDED0060019.jpg" caption: Rock art panel with red geometric signs and white animal-like figures, Namzeze. 2013,2034.19862 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3730114&partId=1 - sys: id: 4b9kxjjlvWgowy6QaKISeM created_at: !ruby/object:DateTime 2016-07-27 07:45:22.920000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:45:22.920000000 Z content_type_id: chapter revision: 1 title_internal: 'Malawi: featured site, chapter 4' body: 'Regarding the interpretation of the paintings, they are directly related to the *nyau*, a secret society of the Chewa and other neighbouring groups in Malawi, Zambia and Mozambique which plays a significant role in funerary and girl’s initiation ceremonies. The *nyau* rituals include dancing and rely heavily on the use of masks, including face masks as well as other mobile structures carried by one or two people. These masks are central for the *nyau* secret society and are kept in secret, hidden from non-initiates. The white paintings of Namzeze and many other sites have been interpreted as representations of masks, depicted during initiation ceremonies that took place in these isolated shelters where secrets of the *nyau* were explained to the new initiates. ' - sys: id: 10PySD1RyuIycESgkSC6wc created_at: !ruby/object:DateTime 2016-07-27 07:45:22.859000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:45:22.859000000 Z content_type_id: image revision: 1 image: sys: id: 7iE4ypc2QwGUOmSAscwqC8 created_at: !ruby/object:DateTime 2016-07-27 07:46:39.077000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:39.077000000 Z title: MALNAM0010035 description: url: "//images.ctfassets.net/xt8ne4gbbocd/7iE4ypc2QwGUOmSAscwqC8/2e085aba2bd10c62941a32016835323c/MALNAM0010035.jpg" caption: White animal-like figures related to the Nyau rituals. Namzeze. 2013,2034.19892 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3730149&partId=1 - sys: id: 7oK266GlZ6uWwAyIQU2Ka2 created_at: !ruby/object:DateTime 2016-07-27 07:45:22.733000000 Z updated_at: !ruby/object:DateTime 2016-07-27 09:05:31.732000000 Z content_type_id: chapter revision: 2 title_internal: 'Malawi: featured site, chapter 5' body: "In fact, some of the more than 100 types of masks can be easily identified in the rock shelters. The most common is the *kasiyamaliro*, a big structure representing an antelope, with a rectangular shape and meant to be carried by two people (an [excellent example](http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=472359&partId=1) can be seen in Room 25 in the British Museum), but others, such as the *Galimoto* (a car structure) and birds are also documented. Some of the features of the animals depicted in this panel corroborate with this interpretation: the shape of the hooves which is more similar to feet, and the fact that in some cases the feet of the forelegs and the hind legs are facing each other, as if they corresponded to two different people. Some researchers have interpreted this feature as a pictorial tool to teach people the proper way of wearing and using the structure to avoid stumbling, which would expose the men hidden in the structure and thus the secret of the mask would be revealed. \n" - sys: id: 3aGsr1Cs7Ccqu2AeSqo6GI created_at: !ruby/object:DateTime 2016-07-27 07:45:22.151000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:45:22.151000000 Z content_type_id: image revision: 1 image: sys: id: 3oM6s0shy0UgQe8MAgy0GK created_at: !ruby/object:DateTime 2016-07-27 07:46:39.101000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:39.101000000 Z title: MALNAM0010036 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3oM6s0shy0UgQe8MAgy0GK/f85d336dfd78d4665fb96b6010db6682/MALNAM0010036.jpg" caption: Detail of a white animal with the legs facing each other, interpreted as a costume for a Nyau masquerade, Namzeze. 2013,2034.20304 © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3730272&partId=1 - sys: id: 1XMXz5051iESkU004EmQsi created_at: !ruby/object:DateTime 2016-07-27 07:45:22.173000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:45:22.173000000 Z content_type_id: image revision: 1 image: sys: id: 2hJ1GBmp4cgOsaYWaCU684 created_at: !ruby/object:DateTime 2016-07-27 07:46:38.309000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:38.309000000 Z title: 17-03-2016 171 description: url: "//images.ctfassets.net/xt8ne4gbbocd/2hJ1GBmp4cgOsaYWaCU684/bc96220c1a95462408c1b72f33fbc183/17-03-2016_171.jpg" caption: 'Costume for Nyau masquerade in form of an animal construction (kasiyamaliro). Af1993,09.150 ' col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=472359&partId=1 - sys: id: 4uCXTRqJMQeYuogAgOWY8Y created_at: !ruby/object:DateTime 2016-07-27 07:45:22.059000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:45:22.059000000 Z content_type_id: chapter revision: 1 title_internal: 'Malawi: featured site, chapter 6' body: "Paintings associated to the *nyau* secret society were used during a very specific period of time (before that other styles of white paintings were used), when the secret society was persecuted first by Ngoni invaders in the 19th century, then by missionaries and colonial governments in the 20th century. With their traditional practices and places forbidden, the members of this society had to look for alternative ways to teach the secrets of the secret society secrets, with the paintings starting to represent *nyau* objects, to be used as a didactic tool. The Namzeze paintings show very explicitly the adaptability of societies to their different challenges and historical contexts. Either as a tool to summon the rain or as a coded message to transmit sacred secrets, the painted symbols depicted in Namzeze show the incredible complexity of rock art meanings throughout time, and their importance for the communities that painted them. \n" citations: - sys: id: 43haKDmJdC0QCSgEkw0gyW created_at: !ruby/object:DateTime 2016-07-27 07:45:22.058000000 Z updated_at: !ruby/object:DateTime 2016-07-27 10:01:31.562000000 Z content_type_id: citation revision: 2 citation_line: '<NAME>. 2001. ''Forbidden Images: Rock Paintings and the Nyau Secret Society of Central Malawi and Eastern Zambia''. *African Archaeological Review, 18 (4)* pp. 187-212' background_images: - sys: id: 7iE4ypc2QwGUOmSAscwqC8 created_at: !ruby/object:DateTime 2016-07-27 07:46:39.077000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:39.077000000 Z title: MALNAM0010035 description: url: "//images.ctfassets.net/xt8ne4gbbocd/7iE4ypc2QwGUOmSAscwqC8/2e085aba2bd10c62941a32016835323c/MALNAM0010035.jpg" - sys: id: 26hf0yyVDWY6MAGWQeiaMY created_at: !ruby/object:DateTime 2016-07-27 07:46:39.075000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:39.075000000 Z title: MALNAM0010015 description: url: "//images.ctfassets.net/xt8ne4gbbocd/26hf0yyVDWY6MAGWQeiaMY/d24ebe749ebd39df56c7587ec2ab9825/MALNAM0010015.jpg" key_facts: sys: id: TDxrMhDuc8QiYm8sa4Kqm created_at: !ruby/object:DateTime 2016-07-27 07:45:24.278000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:45:24.278000000 Z content_type_id: country_key_facts revision: 1 title_internal: 'Malawi: Key Facts' image_count: '759' date_range: 1,000 BC onwards main_areas: 'Chongoni Hills ' techniques: Painting main_themes: Cattle, anthropomorphs, geometric symbols thematic_articles: - sys: id: 2ULickNOv688OaGigYCWYm created_at: !ruby/object:DateTime 2018-05-09 15:26:39.131000000 Z updated_at: !ruby/object:DateTime 2018-05-09 15:28:31.662000000 Z content_type_id: thematic revision: 2 title: Landscapes of Rock Art slug: landscapes-of-rock-art lead_image: sys: id: 62Htpy9mk8Gw28EuUE6SiG created_at: !ruby/object:DateTime 2015-11-30 16:58:24.956000000 Z updated_at: !ruby/object:DateTime 2015-11-30 16:58:24.956000000 Z title: SOADRB0050042_1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/62Htpy9mk8Gw28EuUE6SiG/9cd9572ea1c079f4814104f40045cfb6/SOADRB0050042.jpg" chapters: - sys: id: Ga9XxWBfqwke88qwUKGc2 - sys: id: 5NCw7svaw0IoWWK2uuYEQG - sys: id: 7ng9hfsvLi2A0eWU6A0gWe - sys: id: 4ptu3L494cEYqk6KaY40o4 - sys: id: 5C3yAo4w24egO2O46UCCQg - sys: id: 5FmuBPI2k0o6aCs8immMWQ - sys: id: 6cU5WF1xaEUIiEEkyoWaoq - sys: id: 1YZyNsFTHWIoYegcigYaik - sys: id: 6fhRJ1NiO4wSwSmqmSGEQA - sys: id: 6EhIOeplUA6ouw2kiOcmWe - sys: id: 2g0O5GIiaESIIGC2OOMeuC - sys: id: 4Zj7sd5KJW4Eq2i4aSmQSS - sys: id: 5I9qkMsO5iqI0s6wqQkisk - sys: id: 6WsItqVm8wawokCiCgE4Gu - sys: id: 1631tf7fv4QUwei0IIEk6I - sys: id: 6ycsEOIb0AgkqoQ4MUOMQi - sys: id: 2aa2jzRtPqwK8egGek6G6 - sys: id: 47L9Y10YHmWY04QWCmI4qe - sys: id: 175X82dwJgqGAqkqCu4CkQ - sys: id: 5CGHVFKSUEA0oqY0cS2Cgo - sys: id: 60mUuKWzEkUMUeg4MEUO68 - sys: id: 5AvLn9pvKoeYW2OKqwkUgQ citations: - sys: id: 5z9VWU8t2MeaiAeQWa0Ake background_images: - sys: id: 1yhBeyGEMYkuay2osswcyg created_at: !ruby/object:DateTime 2018-05-09 15:16:49.135000000 Z updated_at: !ruby/object:DateTime 2018-05-09 15:16:49.135000000 Z title: SOANTC0030004 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1yhBeyGEMYkuay2osswcyg/7cab20823cbc01ae24ae6456d6518dbd/SOANTC0030004.jpg" - sys: id: 1rRAJpaj6UMCs6qMKsGm8K created_at: !ruby/object:DateTime 2018-05-09 15:14:41.480000000 Z updated_at: !ruby/object:DateTime 2018-05-09 15:14:41.480000000 Z title: SOANTC0050054 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1rRAJpaj6UMCs6qMKsGm8K/f92d2174d4c5109237ab00379c2088b7/SOANTC0050054.jpg" - sys: id: 5HZTuIVN8AASS4ikIea6m6 created_at: !ruby/object:DateTime 2017-12-19 12:27:08.508000000 Z updated_at: !ruby/object:DateTime 2017-12-19 12:27:08.508000000 Z content_type_id: thematic revision: 1 title: Introduction to rock art in central and eastern Africa slug: rock-art-in-central-and-east-africa lead_image: sys: id: 3esXNapo5GOWIKSImcY4QW created_at: !ruby/object:DateTime 2015-11-25 18:56:43.836000000 Z updated_at: !ruby/object:DateTime 2017-12-15 17:01:05.082000000 Z title: '2013,2034.12982' description: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3776396 url: "//images.ctfassets.net/xt8ne4gbbocd/3esXNapo5GOWIKSImcY4QW/6436b2034659eccb953844b21a400070/2013_2034.12982.jpg" chapters: - sys: id: 4ln5fQLq2saMKsOA4WSAgc created_at: !ruby/object:DateTime 2015-11-25 19:09:33.580000000 Z updated_at: !ruby/object:DateTime 2015-12-11 11:17:25.155000000 Z content_type_id: chapter revision: 4 title: Central and East Africa title_internal: 'East Africa: regional, chapter 1' body: |- Central Africa is dominated by vast river systems and lakes, particularly the Congo River Basin. Characterised by hot and wet weather on both sides of the equator, central Africa has no regular dry season, but aridity increases in intensity both north and south of the equator. Covered with a forest of about 400,000 m² (1,035,920 km²), it is one of the greenest parts of the continent. The rock art of central Africa stretches from the Zambezi River to the Angolan Atlantic coast and reaches as far north as Cameroon and Uganda. Termed the ‘schematic rock art zone’ by <NAME> (1959), it is dominated by finger-painted geometric motifs and designs, thought to extend back many thousands of years. Eastern Africa, from the Zambezi River Valley to Lake Turkana, consists largely of a vast inland plateau with the highest elevations on the continent, such as Mount Kilimanjaro (5,895m above sea level) and Mount Kenya (5,199 m above sea level). Twin parallel rift valleys run through the region, which includes the world’s second largest freshwater lake, Lake Victoria. The climate is atypical of an equatorial region, being cool and dry due to the high altitude and monsoon winds created by the Ethiopian Highlands. The rock art of eastern Africa is concentrated on this plateau and consists mainly of paintings that include animal and human representations. Found mostly in central Tanzania, eastern Zambia and Malawi; in comparison to the widespread distribution of geometric rock art, this figurative tradition is much more localised, and found at just a few hundred sites in a region of less than 100km in diameter. - sys: id: 4nyZGLwHTO2CK8a2uc2q6U created_at: !ruby/object:DateTime 2015-11-25 18:57:48.121000000 Z updated_at: !ruby/object:DateTime 2017-12-15 17:05:00.916000000 Z content_type_id: image revision: 2 image: sys: id: 3esXNapo5GOWIKSImcY4QW created_at: !ruby/object:DateTime 2015-11-25 18:56:43.836000000 Z updated_at: !ruby/object:DateTime 2017-12-15 17:01:05.082000000 Z title: '2013,2034.12982' description: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3776396 url: "//images.ctfassets.net/xt8ne4gbbocd/3esXNapo5GOWIKSImcY4QW/6436b2034659eccb953844b21a400070/2013_2034.12982.jpg" caption: Laikipia, Kenya. 2013,2034.12982 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3776396 - sys: id: 1OvIWDPyXaCO2gCWw04s06 created_at: !ruby/object:DateTime 2015-11-25 19:10:23.723000000 Z updated_at: !ruby/object:DateTime 2015-12-11 11:18:19.325000000 Z content_type_id: chapter revision: 2 title_internal: 'East Africa: regional, chapter 2' body: This collection from Central and East Africa comprises rock art from Kenya, Uganda and Tanzania, as well as the Horn of Africa; although predominantly paintings, engravings can be found in most countries. - sys: id: 4JqI2c7CnYCe8Wy2SmesCi created_at: !ruby/object:DateTime 2015-11-25 19:10:59.991000000 Z updated_at: !ruby/object:DateTime 2016-10-17 13:34:14.653000000 Z content_type_id: chapter revision: 3 title: History of research title_internal: 'East Africa: regional, chapter 3' body: |- The rock art of East Africa, in particular the red paintings from Tanzania, was extensively studied by Mary and <NAME> in the 1930s and 1950s. <NAME> observed Sandawe people of Tanzania making rock paintings in the mid-20th century, and on the basis of oral traditions argued that the rock art was made for three main purposes: casual art; magic art (for hunting purposes or connected to health and fertility) and sacrificial art (to appease ancestral spirits). Subsequently, during the 1970s Fidelis Masao and <NAME> recorded numerous sites, classifying the art in broad chronological and stylistic categories, proposing tentative interpretations with regard to meaning. There has much debate and uncertainty about Central African rock art. The history of the region has seen much mobility and interaction of cultural groups and understanding how the rock art relates to particular groups has been problematic. Pioneering work in this region was undertaken by <NAME> in central Malawi in the early 1920s, <NAME> visited Zambia in 1936 and attempted to provide a chronological sequence and some insight into the meaning of the rock art. Since the 1950s (Clarke, 1959), archaeologists have attempted to situate rock art within broader archaeological frameworks in order to resolve chronologies, and to categorise the art with reference to style, colour, superimposition, subject matter, weathering, and positioning of depictions within the panel (Phillipson, 1976). Building on this work, our current understanding of rock in this region has been advanced by <NAME> (1995, 1997, 2001) with his work in Zambia and Malawi. - sys: id: 35HMFoiKViegWSY044QY8K created_at: !ruby/object:DateTime 2015-11-25 18:59:25.796000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:51:25.789000000 Z content_type_id: image revision: 5 image: sys: id: 6KOxC43Z9mYCuIuqcC8Qw0 created_at: !ruby/object:DateTime 2015-11-25 18:57:00.077000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:57:00.077000000 Z title: '2013,2034.17450' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6KOxC43Z9mYCuIuqcC8Qw0/e25141d07f483d0100c4cf5604e3e525/2013_2034.17450.jpg" caption: This painting of a large antelope is possibly one of the earliest extant paintings. <NAME> believes similar paintings could be more than 28,000 years old. 2013,2034.17450 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3711689 - sys: id: 1dSBI9UNs86G66UGSEOOkS created_at: !ruby/object:DateTime 2015-12-09 11:56:31.754000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:50:18.203000000 Z content_type_id: chapter revision: 5 title: East African Rock Art title_internal: Intro to east africa, chapter 3.5 body: "Rock art of East Africa consists mainly of paintings, most of which are found in central Tanzania, and are fewer in number in eastern Zambia and Malawi; scholars have categorised them as follows:\n\n*__Red Paintings__*: \nRed paintings can be sub-divided into those found in central Tanzania and those found stretching from Zambia to the Indian Ocean.\nTanzanian red paintings include large, naturalistic animals with occasional geometric motifs. The giraffe is the most frequently painted animal, but antelope, zebra, elephant, rhino, felines and ostrich are also depicted. Later images show figures with highly distinctive stylised human head forms or hairstyles and body decoration, sometimes in apparent hunting and domestic scenes. The Sandawe and Hadza, hunter-gatherer groups, indigenous to north-central and central Tanzania respectively, claim their ancestors were responsible for some of the later art.\n\nThe area in which Sandawe rock art is found is less than 100km in diameter and occurs at just a few hundred sites, but corresponds closely to the known distribution of this group. There have been some suggestions that Sandawe were making rock art early into the 20th century, linking the art to particular rituals, in particular simbo; a trance dance in which the Sandawe communicate with the spirit world by taking on the power of an animal. The art displays a range of motifs and postures, features that can be understood by reference to simbo and to trance experiences; such as groups of human figures bending at the waist (which occurs during the *simbo* dance), taking on animal features such as ears and tails, and floating or flying; reflecting the experiences of those possessed in the dance." - sys: id: 7dIhjtbR5Y6u0yceG6y8c0 created_at: !ruby/object:DateTime 2015-11-25 19:00:07.434000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:51:51.887000000 Z content_type_id: image revision: 5 image: sys: id: 1fy9DD4BWwugeqkakqWiUA created_at: !ruby/object:DateTime 2015-11-25 18:57:11.188000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:57:11.188000000 Z title: '2013,2034.16849' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1fy9DD4BWwugeqkakqWiUA/9f8f1330c6c0bc0ff46d744488daa152/2013_2034.16849.jpg" caption: Three schematic figures formed by the use of multiple thin parallel lines. The shape and composition of the heads suggests either headdresses or elaborate hairstyles. Kondoa, Tanzania. 2013,2034.16849 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3709812 - sys: id: 1W573pi2Paks0iA8uaiImy created_at: !ruby/object:DateTime 2015-11-25 19:12:00.544000000 Z updated_at: !ruby/object:DateTime 2015-12-11 11:21:09.647000000 Z content_type_id: chapter revision: 8 title_internal: 'East Africa: regional, chapter 4' body: "Zambian rock art does not share any similarities with Tanzanian rock art and can be divided into two categories; animals (with a few depictions of humans), and geometric motifs. Animals are often highly stylised and superimposed with rows of dots. Geometric designs include, circles, some of which have radiating lines, concentric circles, parallel lines and ladder shapes. Predominantly painted in red, the remains of white pigment is still often visible. David Phillipson (1976) proposed that the naturalistic animals were earlier in date than geometric designs. Building on Phillipson’s work, <NAME> studied ethnographic records and demonstrated that geometric motifs were made by women or controlling the weather.\n\n*__Pastoralist paintings__*: \nPastoralist paintings are rare, with only a few known sites in Kenya and other possible sites in Malawi. Usually painted in black, white and grey, but also in other colours, they include small outlines, often infilled, of cattle and are occasional accompanied by geometric motifs. Made during the period from 3,200 to 1,800 years ago the practice ceased after Bantu language speaking people had settled in eastern Africa. Similar paintings are found in Ethiopia but not in southern Africa, and it has been assumed that these were made by Cushitic or Nilotic speaking groups, but their precise attribution remains unclear (Smith, 2013:154).\n" - sys: id: 5jReHrdk4okicG0kyCsS6w created_at: !ruby/object:DateTime 2015-11-25 19:00:41.789000000 Z updated_at: !ruby/object:DateTime 2017-12-15 17:10:04.890000000 Z content_type_id: image revision: 3 image: sys: id: 1hoZEK3d2Oi8iiWqoWACo created_at: !ruby/object:DateTime 2015-11-25 18:56:43.848000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:56:43.848000000 Z title: '2013,2034.13653' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1hoZEK3d2Oi8iiWqoWACo/1a1adcfad5d5a1cf0a341316725d61c4/2013_2034.13653.jpg" caption: Two red bulls face right. <NAME>, Kenya. 2013,2034.13653. © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3700058 - sys: id: 7rFAK9YoBqYs0u0EmCiY64 created_at: !ruby/object:DateTime 2015-11-25 19:00:58.494000000 Z updated_at: !ruby/object:DateTime 2017-12-15 17:11:37.760000000 Z content_type_id: image revision: 3 image: sys: id: 3bqDVyvXlS0S6AeY2yEmS8 created_at: !ruby/object:DateTime 2015-11-25 18:56:43.880000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:56:43.880000000 Z title: '2013,2034.13635' description: url: "//images.ctfassets.net/xt8ne4gbbocd/3bqDVyvXlS0S6AeY2yEmS8/c9921f3d8080bcef03c96c6b8f1b0323/2013_2034.13635.jpg" caption: Two cattle with horns in twisted perspective. Mt Elgon, Kenya. 2013,2034.13635. © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3698905 - sys: id: 1tX4nhIUgAGmyQ4yoG6WEY created_at: !ruby/object:DateTime 2015-11-25 19:14:33.823000000 Z updated_at: !ruby/object:DateTime 2015-11-25 19:14:33.823000000 Z content_type_id: chapter revision: 1 title_internal: 'East Africa: regional, chapter 5' body: |- *__Late White Paintings__*: Commonly painted in white, or off-white with the fingers, so-called ‘Late White’ depictions include quite large crudely rendered representations of wild animals, mythical animals, human figures and numerous geometric motifs. These paintings are attributed to Bantu language speaking, iron-working farmers who entered eastern Africa about 2,000 years ago from the west on the border of Nigeria and Cameroon. Moving through areas occupied by the Batwa it is thought they learned the use of symbols painted on rock, skin, bark cloth and in sand. Chewa peoples, Bantu language speakers who live in modern day Zambia and Malawi claim their ancestors made many of the more recent paintings which they used in rites of passage ceremonies. - sys: id: 35dNvNmIxaKoUwCMeSEO2Y created_at: !ruby/object:DateTime 2015-11-25 19:01:26.458000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:52:15.838000000 Z content_type_id: image revision: 4 image: sys: id: 6RGZZQ13qMQwmGI86Ey8ei created_at: !ruby/object:DateTime 2015-11-25 18:57:11.188000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:57:11.188000000 Z title: '2013,2034.16786' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6RGZZQ13qMQwmGI86Ey8ei/6d37a5bed439caf7a1223aca27dc27f8/2013_2034.16786.jpg" caption: Under a long narrow granite overhang, Late White designs including rectangular grids, concentric circles and various ‘square’ shapes. 2013,2034.16786 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3709608 - sys: id: 2XW0X9BzFCa8u2qiKu6ckK created_at: !ruby/object:DateTime 2015-11-25 19:01:57.959000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:53:21.559000000 Z content_type_id: image revision: 4 image: sys: id: 1UT4r6kWRiyiUIYSkGoACm created_at: !ruby/object:DateTime 2015-11-25 18:57:11.138000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:57:11.138000000 Z title: '2013,2034.16797' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1UT4r6kWRiyiUIYSkGoACm/fe915c6869b6c195d55b5ef805df7671/2013_2034.16797.jpg" caption: A monuments guard stands next to Late White paintings attributed to Bantu speaking farmers in Tanzania, probably made during the last 700 years. 2013,2034.16797 © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3709628 - sys: id: 3z28O8A58AkgMUocSYEuWw created_at: !ruby/object:DateTime 2015-11-25 19:15:04.047000000 Z updated_at: !ruby/object:DateTime 2015-11-25 19:15:04.047000000 Z content_type_id: chapter revision: 1 title_internal: 'East Africa: regional, chapter 6' body: |- *__Meat-feasting paintings__*: Meat-feasting shelters exist from northern Tanzania through Kenya to Lake Turkana, and are places where Maa-speaking initiated men, who are not permitted to eat meat in their homes, gather to kill and feast on animals, predominantly cattle. The term Maa relates to a group of closely related Eastern Nilotic languages, which historically dominated the east African hinterland; and today is spoken by around a million people. During or after feasting, symbols of the animals that had been eaten were painted on the shelter ceiling in white or less often red. Maa speakers brand their cattle and camels with symbols that signify the lineage of their owners, but may also indicate if an animal has been treated for a particular disease. Different symbols may be used for male and female animals. Over the centuries, because the depictions are on the ceiling of meat feasting rock shelters, and because sites are used even today, a build-up of soot has obscured or obliterated the paintings. Unfortunately, few have been recorded or mapped. - sys: id: 1yjQJMFd3awKmGSakUqWGo created_at: !ruby/object:DateTime 2015-11-25 19:02:23.595000000 Z updated_at: !ruby/object:DateTime 2017-12-15 17:19:11.619000000 Z content_type_id: image revision: 3 image: sys: id: p4E0BRJzossaus6uUUkuG created_at: !ruby/object:DateTime 2015-11-25 18:56:49.743000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:56:49.743000000 Z title: '2013,2034.13004' description: url: "//images.ctfassets.net/xt8ne4gbbocd/p4E0BRJzossaus6uUUkuG/13562eee76ac2a9efe8c0d12e62fa23a/2013_2034.13004.jpg" caption: Huge granite boulder with Ndorobo man standing before a rock overhang used for meat-feasting. Laikipia, Kenya. 2013,2034. 13004. © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3700175 - sys: id: 6lgjLZVYrY606OwmwgcmG2 created_at: !ruby/object:DateTime 2015-11-25 19:02:45.427000000 Z updated_at: !ruby/object:DateTime 2017-12-15 17:20:14.877000000 Z content_type_id: image revision: 3 image: sys: id: 1RLyVKKV8MA4KEk4M28wqw created_at: !ruby/object:DateTime 2015-11-25 18:57:11.150000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:57:11.150000000 Z title: '2013,2034.13018' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1RLyVKKV8MA4KEk4M28wqw/044529be14a590fd1d0da7456630bb0b/2013_2034.13018.jpg" caption: This symbol is probably a ‘brand’ used on cattle that were killed and eaten at a Maa meat feast. Laikipia, Kenya. 2013,2034.13018 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3700193 - sys: id: 5UQc80DUBiqqm64akmCUYE created_at: !ruby/object:DateTime 2015-11-25 19:15:34.582000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:53:53.936000000 Z content_type_id: chapter revision: 4 title: Central African Rock Art title_internal: 'East Africa: regional, chapter 7' body: The rock art of central Africa is attributed to hunter-gatherers known as Batwa. This term is used widely in eastern central and southern Africa to denote any autochthonous hunter-gatherer people. The rock art of the Batwa can be divided into two categories which are quite distinctive stylistically from the Tanzanian depictions of the Sandawe and Hadza. Nearly 3,000 sites are currently known from within this area. The vast majority, around 90%, consist of finger-painted geometric designs; the remaining 10% include highly stylised animal forms (with a few human figures) and rows of finger dots. Both types are thought to date back many thousands of years. The two traditions co-occur over a vast area of eastern and central Africa and while often found in close proximity to each other are only found together at a few sites. However, it is the dominance of geometric motifs that make this rock art tradition very distinctive from other regions in Africa. - sys: id: 4m51rMBDX22msGmAcw8ESw created_at: !ruby/object:DateTime 2015-11-25 19:03:40.666000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:54:25.415000000 Z content_type_id: image revision: 4 image: sys: id: 2MOrR79hMcO2i8G2oAm2ik created_at: !ruby/object:DateTime 2015-11-25 18:56:49.737000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:56:49.737000000 Z title: '2013,2034.15306' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2MOrR79hMcO2i8G2oAm2ik/86179e84233956e34103566035c14b76/2013_2034.15306.jpg" caption: Paintings in red and originally in-filled in white cover the underside of a rock shelter roof. The art is attributed to central African Batwa; the age of the paintings is uncertain. Lake Victoria, Uganda. 2013,2034.15306 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3691242 - sys: id: 5rNOG3568geMmIEkIwOIac created_at: !ruby/object:DateTime 2015-11-25 19:16:07.130000000 Z updated_at: !ruby/object:DateTime 2015-11-25 19:16:19.722000000 Z content_type_id: chapter revision: 2 title_internal: 'East Africa: regional, chapter 8' body: "*__Engravings__*:\nThere are a few engravings occurring on inland plateaus but these have elicited little scientific interest and are not well documented. \ Those at the southern end of Lake Turkana have been categorised into two types: firstly, animals, human figures and geometric forms and also geometric forms thought to involve lineage symbols.\nIn southern Ethiopia, near the town of Dillo about 300 stelae, some of which stand up to two metres in height, are fixed into stones and mark grave sites. People living at the site ask its spirits for good harvests. \n" - sys: id: LrZuJZEH8OC2s402WQ0a6 created_at: !ruby/object:DateTime 2015-11-25 19:03:59.496000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:54:51.576000000 Z content_type_id: image revision: 5 image: sys: id: 1uc9hASXXeCIoeMgoOuO4e created_at: !ruby/object:DateTime 2015-11-25 18:57:11.176000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:57:11.176000000 Z title: '2013,2034.16206' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1uc9hASXXeCIoeMgoOuO4e/09a7504449897509778f3b9455a42f8d/2013_2034.16206.jpg" caption: Group of anthropomorphic stelae with carved faces. <NAME>ela, Southern Ethiopia. 2013,2034.16206 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3703754 - sys: id: 7EBTx1IjKw6y2AUgYUkAcm created_at: !ruby/object:DateTime 2015-11-25 19:16:37.210000000 Z updated_at: !ruby/object:DateTime 2015-12-11 11:22:04.007000000 Z content_type_id: chapter revision: 2 title_internal: 'East Africa: regional, chapter 9' body: In the Sidamo region of Ethiopia, around 50 images of cattle are engraved in bas-relief on the wall of a gorge. All the engravings face right and the cows’ udders are prominently displayed. Similar engravings of cattle, all close to flowing water, occur at five other sites in the area, although not in such large numbers. - sys: id: 6MUkxUNFW8oEK2aqIEcee created_at: !ruby/object:DateTime 2015-11-25 19:04:34.186000000 Z updated_at: !ruby/object:DateTime 2017-12-19 12:22:24.891000000 Z content_type_id: image revision: 3 image: sys: id: PlhtduNGSaOIOKU4iYu8A created_at: !ruby/object:DateTime 2015-11-25 18:56:43.849000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:56:43.849000000 Z title: '2013,2034.16235' description: url: "//images.ctfassets.net/xt8ne4gbbocd/PlhtduNGSaOIOKU4iYu8A/7625c8a21caf60046ea73f184e8b5c76/2013_2034.16235.jpg" caption: Around 50 images of cattle are engraved in bas-relief into the sandstone wall of a gorge in the Sidamo region of Ethiopia. 2013,2034.16235 © TARA/David Coulson col_link: http://bit.ly/2hMU0vm - sys: id: 6vT5DOy7JK2oqgGK8EOmCg created_at: !ruby/object:DateTime 2015-11-25 19:17:53.336000000 Z updated_at: !ruby/object:DateTime 2015-12-11 11:25:38.678000000 Z content_type_id: chapter revision: 3 title: Rock art in the Horn of Africa title_internal: 'East Africa: regional, chapter 10' body: "The Horn of Africa has historically been a crossroads area between the Eastern Sahara, the Subtropical regions to the South and the Arabic Peninsula. These mixed influences can be seen in many archaeological and historical features throughout the region, the rock art being no exception. Since the early stages of research in the 1930s, a strong relationship between the rock art in Ethiopia and the Arabian Peninsula was detected, leading to the establishment of the term *Ethiopian-Arabian* rock art by Pavel Červiček in 1971. This research thread proposes a progressive evolution from naturalism to schematism, ranging from the 4th-3rd millennium BC to the near past. Although the *Ethiopian-Arabian* proposal is still widely accepted and stylistic similarities between the rock art of Somalia, Ethiopia, Yemen or Saudi Arabia are undeniable, recent voices have been raised against the term because of its excessive generalisation and lack of operability. In addition, recent research to the south of Ethiopia have started to discover new rock art sites related to those found in Uganda and Kenya.\n\nRegarding the main themes of the Horn of Africa rock art, cattle depictions seem to have been paramount, with cows and bulls depicted either isolated or in herds, frequently associated with ritual scenes which show their importance in these communities. Other animals – zebus, camels, felines, dogs, etc. – are also represented, as well as rows of human figures, and fighting scenes between warriors or against lions. Geometric symbols are also common, usually associated with other depictions; and in some places they have been interpreted as tribal or clan marks. Both engraving and painting is common in most regions, with many regional variations. \n" - sys: id: 4XIIE3lDZYeqCG6CUOYsIG created_at: !ruby/object:DateTime 2015-11-25 19:04:53.913000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:55:12.472000000 Z content_type_id: image revision: 4 image: sys: id: 3ylztNmm2cYU0GgQuW0yiM created_at: !ruby/object:DateTime 2015-11-25 18:57:11.155000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:57:11.155000000 Z title: '2013,2034.15749' description: url: "//images.ctfassets.net/xt8ne4gbbocd/3ylztNmm2cYU0GgQuW0yiM/3be240bf82adfb5affc0d653e353350b/2013_2034.15749.jpg" caption: Painted roof of rock shelter showing decorated cows and human figures. <NAME>. 2013,2034.15749 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3691391 - sys: id: 2IKYx0YIVOyMSwkU8mQQM created_at: !ruby/object:DateTime 2015-11-25 19:18:28.056000000 Z updated_at: !ruby/object:DateTime 2015-12-11 11:26:13.401000000 Z content_type_id: chapter revision: 2 title_internal: 'East Africa: regional, chapter 11' body: |- Rock art in the Horn of Africa faces several challenges. One of them is the lack of consolidated chronologies and absolute dating for the paintings and engravings. Another is the uneven knowledge of rock art throughout the region, with research often affected by political unrest. Therefore, distributions of rock art in the region are steadily growing as research is undertaken in one of the most interactive areas in East Africa. The rock art of Central and East Africa is one of the least documented and well understood of the corpus of African rock art. However, in recent years scholars have undertaken some comprehensive reviews of existing sites and surveys of new sites to open up the debates and more fully understand the complexities of this region. citations: - sys: id: 7d9bmwn5kccgO2gKC6W2Ys created_at: !ruby/object:DateTime 2015-11-25 19:08:04.014000000 Z updated_at: !ruby/object:DateTime 2017-12-19 12:24:18.659000000 Z content_type_id: citation revision: 2 citation_line: "<NAME>. 1996. ‘Cultural Patterns in the Rock Art of Central Tanzania.’ in *The Prehistory of Africa*. XIII International Congress of Prehistoric and Protohistoric Sciences Forli-Italia-8/14 September.\n\nČerviček, P. 1971. ‘Rock paintings of Laga Oda (Ethiopia)’ in *Paideuma*, 17, pp.121-136.\n\nClark, <NAME>. 1954. *The Prehistoric Cultures of the Horn of Africa*. New York: Octagon Press.\n\nClark, J.C.D. 1959. ‘Rock Paintings of Northern Rhodesia and Nyasaland’, in Summers, R. (ed.) *Prehistoric Rock Art of the Federation of Rhodesia & Nyasaland*: Glasgow: National Publication Trust, pp.163- 220.\n\nJoussaume, R. (ed.) 1995. Tiya, *l’Ethiopie des mégalithes : du biface à l’art rupestre dans la Corne de l’Afrique*. Association des publications chauvinoises (A.P.C.), Chauvigny.\n\nLeakey, M. 1983. *Africa’s Vanishing Art – The Rock Paintings of Tanzania*. London: Hamish Hamilton Ltd.\n\nMasao, F.T. 1979. *The Later Stone Age and the Rock Paintings of Central Tanzania*. Wiesbaden: Franz Steiner Verlag. \n\nNamono, Catherine. 2010. *A contextual interpretive approach to the rock art of Uganda*. Unpublished PhD Thesis. Johannesburg: University of Witwatersrand\n\nPhillipson, D.W. 1976. ‘The Rock Paintings of Eastern Zambia’, in *The Prehistory of Eastern Zambia: Memoir 6 of the british Institute in Eastern Africa*. Nairobi.\n\n<NAME>. (1995), Rock art in south-Central Africa: A study based on the pictographs of Dedza District, Malawi and Kasama District Zambia. dissertation. Cambridge: University of Cambridge, Unpublished Ph.D. dissertation.\n\n<NAME>. (1997), Zambia’s ancient rock art: The paintings of Kasama. Zambia: The National Heritage Conservation Commission of Zambia.\n\nSmith B.W. (2001), Forbidden images: Rock paintings and the Nyau secret society of Central Malaŵi and Eastern Zambia. *African Archaeological Review*18(4): 187–211.\n\n<NAME>. 2013, ‘Rock art research in Africa; in In: Lane, P. & Mitchell, P. (eds) *Handbook of African Archaeology*. Oxford: Oxford University Press, pp.145-162.\n\nTen Raa, E. 1974. ‘A record of some prehistoric and some recent Sandawe rock paintings’ in *Tanzania Notes and Records* 75, pp.9-27." background_images: - sys: id: 4aeKk2gBTiE6Es8qMC4eYq created_at: !ruby/object:DateTime 2015-12-07 19:42:27.348000000 Z updated_at: !ruby/object:DateTime 2017-12-19 12:25:55.914000000 Z title: '2013,2034.1298' description: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3592557 url: "//images.ctfassets.net/xt8ne4gbbocd/4aeKk2gBTiE6Es8qMC4eYq/31cde536c4abf1c0795761f8e35b255c/2013_2034.1298.jpg" - sys: id: 6DbMO4lEBOU06CeAsEE8aA created_at: !ruby/object:DateTime 2015-12-07 19:41:53.440000000 Z updated_at: !ruby/object:DateTime 2017-12-19 12:26:40.898000000 Z title: '2013,2034.15749' description: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3691391 url: "//images.ctfassets.net/xt8ne4gbbocd/6DbMO4lEBOU06CeAsEE8aA/9fc2e1d88f73a01852e1871f631bf4ff/2013_2034.15749.jpg" country_introduction: sys: id: Yh91lE4KycSSwYOQQOqkW created_at: !ruby/object:DateTime 2016-07-27 07:44:27.867000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:44:27.867000000 Z content_type_id: country_information revision: 1 title: 'Malawi: country introduction' chapters: - sys: id: 3xJlmjTd44aAqYWCeI82ac created_at: !ruby/object:DateTime 2016-07-27 07:45:21.966000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:45:21.966000000 Z content_type_id: chapter revision: 1 title: Introduction title_internal: 'Malawi: country, chapter 1' body: "Malawi is a landlocked country in south-eastern Africa, located between Mozambique, Tanzania and Zambia. It stretches from north to south with the eastern boundary of the country marked by the Lake Malawi. Rock art can be found throughout the country but is especially abundant in central Malawi, near the western border with Mozambique. It consists exclusively of paintings attributed to two very distinctive groups (hunter-gatherers and farmers), and shows obvious links with other sites located in Zambia and western Mozambique. The images consist mainly of animals, anthropomorphic figures and geometric symbols, with a chronology that ranges from the Late Stone Age to the 1950s. \ \n" - sys: id: 5KKSbUlQm4MUMEgAUaweyu created_at: !ruby/object:DateTime 2016-07-27 07:45:21.937000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:45:21.937000000 Z content_type_id: chapter revision: 1 title: Geography and rock art distribution title_internal: 'Malawi: country, chapter 2' body: 'The geography of Malawi is conditioned by the Great Rift Valley, which runs from north to south and which contains Lake Malawi (also known as Lake Nyasa). Almost 600 km long and more than 50 km wide, Lake Malawi is the second biggest lake in Africa and a key geographical feature of Malawi and the surrounding countries, as well as an important economic resource for the country. The rest of the country west of the Rift Valley is dominated by high plateaus, mostly ranging from 900-1200 m above sea level but reaching 2500 m in the Nyika Plateau to the north and 3000 m at Mt. Mulanje, to the south. The climate is equatorial, with strong seasonal differences, and hotter in the southern part of the country. ' - sys: id: 1zuN2gMyiAg88cw2aKGYWe created_at: !ruby/object:DateTime 2016-07-27 07:45:21.761000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:45:21.761000000 Z content_type_id: image revision: 1 image: sys: id: pDDj71RyBUyqiqsouEeew created_at: !ruby/object:DateTime 2016-07-27 07:46:39.282000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:39.282000000 Z title: MALCHE0010001 description: url: "//images.ctfassets.net/xt8ne4gbbocd/pDDj71RyBUyqiqsouEeew/a0ab78ba58be69235256271b0af54de2/MALCHE0010001.jpg" caption: Landscape in the Chongoni Hills. 2013,2034.20054 © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3737098&partId=1 - sys: id: 2iANG11zHqMAmKYmsIKeu8 created_at: !ruby/object:DateTime 2016-07-27 07:45:21.150000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:45:21.150000000 Z content_type_id: chapter revision: 1 title_internal: 'Malawi: country, chapter 3' body: 'Although rock art can be found in several areas in Malawi, the main concentration of sites is located in the Chongoni area, in the westernmost part of central Malawi, very near the border with Mozambique. In that area around 150 rock art sites have been located so far, belonging to the two main traditions of rock art found in the country. Other smaller concentrations of rock art can be found to the south and to the north-west, and around the southern side of Lake Malawi. The distribution of the different styles of Malawian rock art varies substantially: while the older paintings attributed to hunter-gatherers can be found everywhere throughout the country, those made by farmers are concentrated in the Chongoni area, as well as nearby areas of Mozambique and Zambia. Rock art is usually scattered throughout the landscape, in hilly areas where gneiss outcrops provide shelters and well-protected surfaces adequate for painting. ' - sys: id: 271lgJ95Pmkmu0s8a4Qw2k created_at: !ruby/object:DateTime 2016-07-27 07:45:21.218000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:45:21.218000000 Z content_type_id: image revision: 1 image: sys: id: 3lEqMHYBwIse0EmgGkOygW created_at: !ruby/object:DateTime 2016-07-27 07:46:40.051000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:40.051000000 Z title: MALMPH0030003 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3lEqMHYBwIse0EmgGkOygW/26ce17dd2e9b61bef2220ce2ba9afb60/MALMPH0030003.jpg" caption: Rock Art panel showing a lizard and several geometric shapes. Mphunzi, <NAME>. 2013,2034.20205 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3739366&partId=1 - sys: id: 5qpJtPXB4W0a4a04aQeSgG created_at: !ruby/object:DateTime 2016-07-27 07:45:21.145000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:45:21.145000000 Z content_type_id: chapter revision: 1 title: Research history title_internal: 'Malawi: country, chapter 4' body: 'Rock art in Malawi has been documented by Europeans since at least the 1920s, although it wasn’t until the 1950s when the first articles on the subject were published, and it was only in 1978 a first synthesis on Malawian rock art was undertaken (Lindgren, N.E. & Schoffeleers, J.M. 1978). In the 1980s research increased, especially on Chongoni rock art as its importance as a secret society artefact became evident. In 1995 the Chongoni rock art area was comprehensively studied by <NAME> as a part of his doctoral research (1995), which is still the main reference on the topic. Most of the research on Malawi rock art has focused on the study of the two different painting traditions found in Malawi. A basic proposal was made in 1978 when the red paintings—mostly geometric—considered older and attributed to hunter-gatherers, while white paintings were related to more modern groups of farmers which arrived early in the 2nd millennium AD and preserved their painting traditions until the 1950s. Since 1978, the knowledge of these two groups has substantially improved, with a more refined proposal made by <NAME> in his doctoral dissertation. ' - sys: id: 1JMW93aEcQSEcwcG06gg6y created_at: !ruby/object:DateTime 2016-07-27 07:45:21.025000000 Z updated_at: !ruby/object:DateTime 2018-09-19 14:56:42.286000000 Z content_type_id: image revision: 2 image: sys: id: 2OXCOlKLfWO4yUYMc6YiOK created_at: !ruby/object:DateTime 2016-07-27 07:46:40.017000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:40.017000000 Z title: MALDED0090006 description: url: "//images.ctfassets.net/xt8ne4gbbocd/2OXCOlKLfWO4yUYMc6YiOK/0446391cb8c39e21a2baeca5d2566522/MALDED0090006.jpg" caption: Rock Art panel with multitude of red geometric signs. Nthulu, Chongoni Hills. 2013,2034.20003 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3733695&partId=1&searchText=2013,2034.20003&page=1 - sys: id: 5lHiHzAofecm6YEEG8YGOu created_at: !ruby/object:DateTime 2016-07-27 07:45:20.950000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:45:20.950000000 Z content_type_id: chapter revision: 1 title_internal: 'Malawi: country, chapter 5' body: 'Another important aspect of rock art research in Malawi has been to look at the maintenance of painting traditions until relatively recent times. These exceptional examples have provided fertile ground for further research, as many of these later paintings have been effectively interpreted as parts of initiation rituals that are still undertaken today. The study of the secret societies that preserve this knowledge has been a characteristic feature of Malawi rock art research since the 1970s (Lindgren, N.E. & Schoffeleers, J.M. 1978). ' - sys: id: 1oucgcWELuwwQ8QgCG4kKY created_at: !ruby/object:DateTime 2016-07-27 07:45:20.830000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:45:20.830000000 Z content_type_id: chapter revision: 1 title: 'Themes ' title_internal: 'Malawi: country, chapter 6' body: 'Rock art in Malawi is clearly defined in two groups with different styles, chronologies and production contexts. The first one is characterized by red schematic paintings with parallels in Central Africa from Malawi to Angola. These paintings are associated with the ancestors of modern Batwa hunter-gatherers, and can be classified into two different types. The first can be considered the most characteristic and is represented by circles with radiating lines, concentric circles, ovals, wavy or parallel lines. In some cases, red figures are infilled in white painting or white dots. The second type is very scarce (only two examples have been found in Chongoni) and depicts very schematic animals, sometimes accompanied by humans. Both types are finely executed with red oxide pigment. Regarding their interpretation, the figures seem to have been associated with rainmaking and fertility concepts. ' - sys: id: 2shnvvJ5isC2AcYeUmYogI created_at: !ruby/object:DateTime 2016-07-27 07:45:20.783000000 Z updated_at: !ruby/object:DateTime 2016-07-27 08:55:24.416000000 Z content_type_id: image revision: 2 image: sys: id: 2D4MCayW9iK0Oi00QGWsIq created_at: !ruby/object:DateTime 2016-07-27 07:46:40.074000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:40.074000000 Z title: MALMPH0010008 description: url: "//images.ctfassets.net/xt8ne4gbbocd/2D4MCayW9iK0Oi00QGWsIq/278456bd2263cfcc1be94ccd74ad8437/MALMPH0010008.jpg" caption: Rock art panel with red geometric depictions ascribed to hunter-gatherers. Mphunzi. 2013,2034.20202 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3738324&partId=1 - sys: id: 1ggf46GoBKEqigYYyegCyC created_at: !ruby/object:DateTime 2016-07-27 07:45:20.069000000 Z updated_at: !ruby/object:DateTime 2016-07-27 08:56:52.968000000 Z content_type_id: chapter revision: 2 title_internal: 'Malawi: country, chapter 7' body: 'The second and more modern rock art tradition found in Malawi is represented by white figures made with white clay daubed onto rock surfaces with the finger. Associated with the agriculturalist Chewa people, the depictions usually represent zoomorphic, spread-eagled or snake-like figures which could represent mythological beings, sometimes accompanied by geometric symbols. As in the case of the schematic figures, two types of paintings have been proposed: those related to spread-eagled figures and those representing zoomorphs (animal-like figures). The paintings were made until several decades ago, as testified by depictions of cars that can be found at some sites. In this case, the interpretation of the paintings is straightforward, as the images depicted can still be related to current rituals often employing masks in a variety of shapes. The spread-eagled paintings may be associated with a Chewa girl’s initiation ceremony and would act as a mnemonic tool during the ritual, while the zoomorphic paintings may depict spirit characters of the Chewa men’s secret society, the *nyau*. In many cases, these paintings can overlap the older red paintings already existing at some sites' - sys: id: 2QkvnVmQb64kASYWcmGcge created_at: !ruby/object:DateTime 2016-07-27 07:45:20.051000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:45:20.051000000 Z content_type_id: image revision: 1 image: sys: id: 3jS61b3w2AMEwogGu2CoEI created_at: !ruby/object:DateTime 2016-07-27 07:46:39.175000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:39.175000000 Z title: MALCHE0010011 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3jS61b3w2AMEwogGu2CoEI/807f22eb6e58077d7a003f3e893a91a3/MALCHE0010011.jpg" caption: Rock Art panel with multitude of white human-like and reptile-like depictions, surrounded by red and white geometric signs. Chentcherere. 2013,2034.20064d © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3737077&partId=1 - sys: id: 5x1toGMQuWueQmUiYUmSa2 created_at: !ruby/object:DateTime 2016-07-27 07:45:20.009000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:45:20.009000000 Z content_type_id: chapter revision: 1 title: Chronology title_internal: 'Malawi: country, chapter 8' body: 'Although it is generally accepted that the red schematic paintings are older than the white ones, the exact chronology of these styles is still under discussion. The earliest evidence for human occupation in the region according to the archaeological record is around 2,500 years ago, and it is generally assumed that Late Stone Age hunters and gatherers made this rock art. Unfortunately no datable evidence has been found although groups of these people survived until the 1800s in Malawi. For the white paintings, chronologies are more accurate: the Chewa people are thought to have arrived to central Malawi in the 15th century, and as aforementioned, painting traditions were still alive in the mid-20th century. ' - sys: id: 5qd3rUg0MwUMKM2CkEgII created_at: !ruby/object:DateTime 2016-07-27 07:45:19.940000000 Z updated_at: !ruby/object:DateTime 2017-01-24 16:28:33.674000000 Z content_type_id: image revision: 2 image: sys: id: 2xzgTrXwqQKa0Wa0w6K06k created_at: !ruby/object:DateTime 2016-07-21 15:01:45.256000000 Z updated_at: !ruby/object:DateTime 2016-07-21 15:01:45.256000000 Z title: MALPHA0010009 description: url: "//images.ctfassets.net/xt8ne4gbbocd/2xzgTrXwqQKa0Wa0w6K06k/dbe565ce1dd67cb2835e2a9201be3e7f/MALPHA0010009.jpg" caption: Rock Art panel with multitude of white human-like and reptile-like depictions, surrounded by geometric signs. Phanga la Ngoni. 2013,2034.20346 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3733409&partId=1 citations: - sys: id: Ao0sic2MKGOE4G66MYqkm created_at: !ruby/object:DateTime 2016-07-27 07:45:19.885000000 Z updated_at: !ruby/object:DateTime 2016-07-27 10:02:45.154000000 Z content_type_id: citation revision: 2 citation_line: "Lindg<NAME>. & <NAME>. 1978. 'Rock art and nyau symbolism in Malawi' *Malawi Government, Department of Antiquities 18.* Malawi, Montfort Press \n\nSmith, B.W. 1995. 'Rock art in south-Central Africa: A study based on the pictographsof Dedza District, Malawi and Kasama District Zambia'. Cambridge, University of Cambridge, Unpublished Ph.D. dissertation\n\nSmith, B.W. 2014. 'Chongoni rock art area' In: <NAME>. (ed) *Encyclopedia of Global Archaeology*, pp. 1448-1452. New York, Springer\n" background_images: - sys: id: 6JgzRM8OJiUKiayKQ228Sw created_at: !ruby/object:DateTime 2016-07-27 07:46:35.003000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:35.003000000 Z title: MALCHE0010001 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6JgzRM8OJiUKiayKQ228Sw/bd974f27c56e33738cc6e0f7c29275e8/MALCHE0010001.jpg" - sys: id: NTffnJXH20AWqI04asQ8k created_at: !ruby/object:DateTime 2015-12-08 13:45:27.414000000 Z updated_at: !ruby/object:DateTime 2015-12-08 13:45:27.414000000 Z title: MALDED0060066 description: url: "//images.ctfassets.net/xt8ne4gbbocd/NTffnJXH20AWqI04asQ8k/a4bd99365aa8a60347ba956c7196cc6c/MALDED0060066.jpg" - sys: id: 36UwCkPblCA86cUS8Cc6e8 created_at: !ruby/object:DateTime 2016-07-27 07:46:35.020000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:35.020000000 Z title: MALCHE0010011 description: url: "//images.ctfassets.net/xt8ne4gbbocd/36UwCkPblCA86cUS8Cc6e8/da2426b400a51c8c62284b51169c81c9/MALCHE0010011.jpg" region: Southern Africa ---<file_sep>/_coll_country/mauritania.md --- contentful: sys: id: 19GvoR0748mEow0i6iaYka created_at: !ruby/object:DateTime 2015-11-26 18:54:03.919000000 Z updated_at: !ruby/object:DateTime 2018-05-17 17:03:29.064000000 Z content_type_id: country revision: 9 name: Mauritania slug: mauritania col_url: http://www.britishmuseum.org/research/collection_online/search.aspx?people=197356&place=17542 map_progress: true intro_progress: true image_carousel: - sys: id: 6a9PIc2PD2GoSys6umKim created_at: !ruby/object:DateTime 2015-11-26 12:50:25.597000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:15:13.181000000 Z title: '2013,2034.12277' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3645968&partId=1&searchText=2013,2034.12277&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/6a9PIc2PD2GoSys6umKim/df4fd71d342462545f28c306a798de62/2013_2034.12277.jpg" - sys: id: 5u1VecbrbOq4cCICyqiOAw created_at: !ruby/object:DateTime 2015-11-26 12:50:25.656000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:20:04.418000000 Z title: '2013,2034.12427' description: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3646352&partId=1&searchText=2013,2034.12427&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/5u1VecbrbOq4cCICyqiOAw/c4223338beae42378b3c34f8ab1b5a8e/2013_2034.12421.jpg" - sys: id: W4EibqP766CYAamWyqkQK created_at: !ruby/object:DateTime 2015-11-26 12:50:25.952000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:21:05.070000000 Z title: '2013,2034.12332' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3646132&partId=1&searchText=2013,2034.12332&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/W4EibqP766CYAamWyqkQK/523fee62695a3de60ff7940899dfaaf1/2013_2034.12332.jpg" - sys: id: 4zNeoXAAesUaCGoaSic6qO created_at: !ruby/object:DateTime 2015-11-26 12:50:25.588000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:21:40.547000000 Z title: '2013,2034.12285' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3645983&partId=1&searchText=2013,2034.12285&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/4zNeoXAAesUaCGoaSic6qO/97398e8ebe5bd8be1adf57f450a72e08/2013_2034.12285.jpg" featured_site: sys: id: QsOItel9sWUGymKiQe8QC created_at: !ruby/object:DateTime 2015-11-25 16:34:24.351000000 Z updated_at: !ruby/object:DateTime 2015-12-08 14:43:50.662000000 Z content_type_id: featured_site revision: 4 title: Guilemsi, Mauritania slug: guilemsi chapters: - sys: id: 3PyEd6v57yqOQ4GyumkyG8 created_at: !ruby/object:DateTime 2015-11-25 16:28:56.057000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:28:56.057000000 Z content_type_id: chapter revision: 1 title_internal: 'Mauritania: featured site, chapter 1' body: A significant concentration of rock art in Mauritania is in the region of Guilemsi, an 11-km long ridge, about 70 m high at its highest point. Guilemsi is located in the desert, around 50 km north of the town of Tidjika, and about 200 km west of the renowned Neolithic sites at Dhar Tichitt. Guilemsi’s south face contains many ravines with rock shelters, and the rock painting sites scattered around the area are to be found in open shelters and ridges or boulders on the cliff faces, as well as on the stone banks of a dry river. These sites are notable both for the solely painted nature of the rock art, and the variety of its subject matter. - sys: id: 68H1B3nwreqsiWmGqa488G created_at: !ruby/object:DateTime 2015-11-25 16:21:40.277000000 Z updated_at: !ruby/object:DateTime 2018-08-23 14:31:27.636000000 Z content_type_id: image revision: 2 image: sys: id: 1uRo8OtMas0sE0uiOUSIok created_at: !ruby/object:DateTime 2015-11-25 16:19:58.328000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:19:58.328000000 Z title: '2013,2034.12416' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1uRo8OtMas0sE0uiOUSIok/71ebc908be14899de348803b21cddc31/2013_2034.12416.jpg" caption: Painted human figure on horseback. Guilemsi, <NAME>, 2013,2034.12418 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3646307&partId=1&searchText=2013,2034.12418&page=1 - sys: id: 6MRt7S2BckWkaGcGW4iEMY created_at: !ruby/object:DateTime 2015-11-25 16:29:11.911000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:29:11.911000000 Z content_type_id: chapter revision: 1 title_internal: 'Mauritania: featured site, chapter 2' body: There are many stone constructions at Guilemsi that have been known to archaeologists for decades, although they have not received the academic attention that those further to the East in the Tichitt-Walata region had. The Dhars Tagant, Tichitt, Walata and Néma form an enormous crescent-shaped chain of sandstone escarpments, enclosing much of southern Mauritania and associated with a Neolithic ‘Tichitt Tradition’, which is based on the remains of over 400 apparent settlements along the escarpment ridges. This culture is thought to have existed between about 2,000 BC and 200 BC, based on pastoralism and the cultivation of millet, before declining due to the increasing aridity of the environment and possible incursion by other cultural groups from the North. - sys: id: 2uYbn8i2oQQEcu4gMYyKCQ created_at: !ruby/object:DateTime 2015-11-25 16:22:17.768000000 Z updated_at: !ruby/object:DateTime 2018-08-23 14:32:15.715000000 Z content_type_id: image revision: 3 image: sys: id: 5MkqJUXrj2o4e8SmweeoW2 created_at: !ruby/object:DateTime 2015-11-25 16:19:58.333000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:19:58.333000000 Z title: '2013,2034.12357' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5MkqJUXrj2o4e8SmweeoW2/92eeb35eb7e827596e213cd06cf9fe4a/2013_2034.12357.jpg" caption: View looking South from the West summit on the sandstone ridge of Guilemsi, Tagant, Mauritania. 2013,2034.12357 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3646542&partId=1&searchText=2013,2034.12357&page=1 - sys: id: 1CiJq8i5liqkImaM4mEWe created_at: !ruby/object:DateTime 2015-11-25 16:29:28.225000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:29:28.226000000 Z content_type_id: chapter revision: 1 title_internal: 'Mauritania: featured site, chapter 3' body: The Tichitt Tradition is characterised by dry stonewall remains, and these are found at Guilemsi, although the extent of the connection with the Tichitt culture to the East is unclear. The ridge at Guilemsi contains many apparent funerary monuments consisting of rectangular stone platforms, as well as apparent dwelling structures. Some of the funerary monuments appear to be associated with rock shelters, but any connection of the stone structures to the rock art remains unknown. - sys: id: 1blgrBPnEoSKqeCASmUgGI created_at: !ruby/object:DateTime 2015-11-25 16:22:58.090000000 Z updated_at: !ruby/object:DateTime 2018-08-23 14:32:49.841000000 Z content_type_id: image revision: 2 image: sys: id: 7yy2sbn6PCoeuqyQOAgcA8 created_at: !ruby/object:DateTime 2015-11-25 16:19:58.288000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:19:58.288000000 Z title: '2013,2034.12494' description: url: "//images.ctfassets.net/xt8ne4gbbocd/7yy2sbn6PCoeuqyQOAgcA8/0914de8f403684d18accff0284017210/2013_2034.12494.jpg" caption: Stonewall remains, Guilemsi, Tagant, Mauritania. 2013,2034. 12494 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3646554&partId=1&searchText=2013,2034.12494&page=1 - sys: id: 2d8TB564qE4E6yw6I0MG2A created_at: !ruby/object:DateTime 2015-11-25 16:29:44.594000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:29:44.594000000 Z content_type_id: chapter revision: 1 title_internal: 'Mauritania: featured site, chapter 4' body: The rock art at Guilemsi appears to be all painted, which marks a contrast to Tichitt sites which more often feature engraved rock art. The only non-painted rock markings encountered at Guilemsi was several groups of cupules (round, man-made depressions in the rock) which were found in three rock shelters. Some of the paintings in the area are unusual in themselves- one of the most striking is a panel of handprints in red (Fig. 4.), as well as a couple of rare paintings appearing to be of big cats, and the heads and finely rendered horns of seven antelope, perhaps oryx (Fig. 5.). - sys: id: 1pP6kJroQ4C2CYAim6KGQy created_at: !ruby/object:DateTime 2015-11-25 16:23:33.025000000 Z updated_at: !ruby/object:DateTime 2018-08-23 14:33:17.453000000 Z content_type_id: image revision: 2 image: sys: id: 6uIYZ0iOROas4Uqo4u4UyW created_at: !ruby/object:DateTime 2015-11-25 16:19:51.669000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:19:51.669000000 Z title: '2013,2034.12382' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6uIYZ0iOROas4Uqo4u4UyW/3215c1e93f536598e0a14be6fcecfa82/2013_2034.12382.jpg" caption: Paint handprints on rock shelter wall, Guilemsi, Tagant, Mauritania. 2013,2034.12382 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3646167&partId=1&searchText=2013,2034.12382&page=1 - sys: id: 3exPT8hfMAQ2SUIeGqKgSU created_at: !ruby/object:DateTime 2015-11-25 16:24:09.355000000 Z updated_at: !ruby/object:DateTime 2018-08-23 14:34:51.120000000 Z content_type_id: image revision: 2 image: sys: id: 2QrzxNR1jq4w8EO2KEUUoE created_at: !ruby/object:DateTime 2015-11-25 16:19:58.317000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:19:58.317000000 Z title: '2013,2034.12421' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2QrzxNR1jq4w8EO2KEUUoE/10c62c938cb1ed9f9b6d25edf4d17205/2013_2034.12421.jpg" caption: Painted heads of seven antelope (oryx?), rock shelter wall, Guilemsi, Tagant, Mauritania. 2013,2034.12427 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3646352&partId=1&searchText=Painted+heads+of+seven+antelope+&page=1 - sys: id: 3Q3fT8FApyQooa8cikOkiU created_at: !ruby/object:DateTime 2015-11-25 16:30:05.118000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:30:05.118000000 Z content_type_id: chapter revision: 1 title_internal: 'Mauritania: featured site, chapter 5' body: 'Cattle, perhaps the most common animal subject in Mauritanian rock art, are also depicted here, notably in another singular scene: one of an otherwise naturalistic cow with dramatically elongated legs, next to an artificially inflated-looking human figure (Fig. 8). Domestic cattle were present in the area from at least the second Millennium BC, so these paintings must post-date this, although whether they are associated with Tichitt-Tradition pastoralists or later groups is not known. The fact that even the more normally-proportioned cattle representations at Guilemsi are depicted in a variety of styles (Figs. 6 & 7) while in the same vicinity may suggest successive (or perhaps even contemporary) painting by peoples with different stylistic traditions.' - sys: id: 2WJOpXkkG4C4sce8wkcE4U created_at: !ruby/object:DateTime 2015-11-25 16:24:46.144000000 Z updated_at: !ruby/object:DateTime 2018-08-23 15:03:22.300000000 Z content_type_id: image revision: 2 image: sys: id: 32ojd6nNewwy8qSU0kuYYk created_at: !ruby/object:DateTime 2015-11-25 16:20:01.824000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:20:01.824000000 Z title: '2013,2034.12381' description: url: "//images.ctfassets.net/xt8ne4gbbocd/32ojd6nNewwy8qSU0kuYYk/3328ca79a097f10fe9b125c43352c0a8/2013_2034.12381.jpg" caption: Painted bichrome cow, cave wall, Guilemsi, Tagant, Mauritania. 2013,2034.12381 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3646170&partId=1&searchText=2013,2034.12381+&page=1 - sys: id: Z2iJHm63qoW8e8wsAqCAK created_at: !ruby/object:DateTime 2015-11-25 16:25:17.499000000 Z updated_at: !ruby/object:DateTime 2018-08-23 15:04:00.340000000 Z content_type_id: image revision: 2 image: sys: id: 3Z70aGhdUsOCKyWyK6u8eE created_at: !ruby/object:DateTime 2015-11-25 16:19:51.681000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:19:51.681000000 Z title: '2013,2034.12449' description: url: "//images.ctfassets.net/xt8ne4gbbocd/3Z70aGhdUsOCKyWyK6u8eE/c818ef2eba7505c159c231e4aa35ad4a/2013_2034.12449.jpg" caption: Two schematic painted cattle, Guilemsi, Tagant, Mauritania. 2013,2034.12449 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3647071&partId=1&searchText=2013,2034.12449&page=1 - sys: id: 56Ia1KTWDKwuw0ekagww6K created_at: !ruby/object:DateTime 2015-11-25 16:30:23.129000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:30:23.129000000 Z content_type_id: chapter revision: 1 title_internal: 'Mauritania: featured site, chapter 6' body: 'Two of the most impressive panels of paintings from Guilemsi involve not cattle but another important domesticate: ridden horses. There is evidence of horses having reached the far West of North Africa by about 600 AD, but horses may have been used in the area much earlier, from the mid-1st Millennium BC, if not earlier. Although elsewhere in the Sahara the earliest horse images appear to show them used for draught purposes rather than riding, in Mauritania, almost all depictions of horses in rock art show them being ridden, often by apparently armed riders (eg. Fig. 11). At Guilemsi, there are several styles of paintings showing horses and riders: the ‘bi-triangular’ and stick-figure like styles (Figs. 10 & 11), which have been proposed to be associated with early Berber peoples, and another style, showing horses with elongated, stylised bodies and short necks (Fig. 9). These horse depictions appear to be of a form thus far unrecorded in the rock art of the area, and as such are an interesting addition to the known corpus, as Mauritanian rock art has not been as thoroughly studied as that of other Saharan countries.' - sys: id: 6mPD0Om12wAcaOmOiaumYk created_at: !ruby/object:DateTime 2015-11-25 16:25:53.929000000 Z updated_at: !ruby/object:DateTime 2018-08-23 15:04:24.323000000 Z content_type_id: image revision: 2 image: sys: id: 2CFj8amCm8aMkkmQ0emk0o created_at: !ruby/object:DateTime 2015-11-25 16:19:51.669000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:19:51.669000000 Z title: '2013,2034.12474' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2CFj8amCm8aMkkmQ0emk0o/c4ea95ada7f53b9ffb0c43bb6f412b8f/2013_2034.12474.jpg" caption: Painted figures of contorted cow and human figure, and regularly-proportioned cow, Guilemsi, Tagant, Mauritania. 2013,2034.12474 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3646484&partId=1&searchText=2013,2034.12474+&page=1 - sys: id: 2da6EUC7TC6wSWGAOwQaAO created_at: !ruby/object:DateTime 2015-11-25 16:26:22.515000000 Z updated_at: !ruby/object:DateTime 2018-08-23 15:04:47.280000000 Z content_type_id: image revision: 2 image: sys: id: 58CHInxW4wagKgwCAsWcqY created_at: !ruby/object:DateTime 2015-11-25 16:19:58.272000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:19:58.272000000 Z title: '2013,2034.12411' description: url: "//images.ctfassets.net/xt8ne4gbbocd/58CHInxW4wagKgwCAsWcqY/f1370f3f0700aaae60918abb3821cb22/2013_2034.12411.jpg" caption: Painted figures of mounted horses on cave wall, Guilemsi, Tagant, Mauritania. 2013,2034.12411 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3646326&partId=1&searchText=2013,2034.12411+&page=1 - sys: id: 4UfKI7DmWA4A4eqocC0iMG created_at: !ruby/object:DateTime 2015-11-25 16:26:54.429000000 Z updated_at: !ruby/object:DateTime 2018-08-23 15:05:23.813000000 Z content_type_id: image revision: 2 image: sys: id: 3nZtTK8uIEc2MqGAqQC8c6 created_at: !ruby/object:DateTime 2015-11-25 16:19:51.680000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:19:51.680000000 Z title: '2013,2034.12454' description: url: "//images.ctfassets.net/xt8ne4gbbocd/3nZtTK8uIEc2MqGAqQC8c6/c36ab38978b6ccdc3ff693edeeb20091/2013_2034.12454.jpg" caption: Three painted “bi-triangular” schematic horses and riders, with white geometric shape and several unidentified figures. Guilemsi, <NAME>. 2013,2034.12454 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3648285&partId=1&searchText=2013,2034.12454&page=1 - sys: id: 16gHbuP8Hqo4KwCQK0sWeI created_at: !ruby/object:DateTime 2015-11-25 16:30:45.101000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:30:45.101000000 Z content_type_id: chapter revision: 1 title_internal: 'Mauritania: featured site, chapter 7' body: Another very interesting tableau is that in Fig. 11, which is to the right of the panel in Fig. 9, but in executed in a very different style. It appears to depict a group of armed horsemen, and warriors on foot, vanquishing others who are unmounted, who lie, presumably dead, to the left of the horsemen, surrounded by spears. This is an unusually dynamic depiction of conflict, and it is not known whether it depicts an imagined or real confrontation, or, if real, whether it is the work of an artist from the culture of the horsemen or those opposing them. - sys: id: 60nybfnB4cmoOaIQq8sWkC created_at: !ruby/object:DateTime 2015-11-25 16:27:25.377000000 Z updated_at: !ruby/object:DateTime 2018-09-17 17:56:58.326000000 Z content_type_id: image revision: 2 image: sys: id: 1EGPJpRMnmuk6Y6c0Qigos created_at: !ruby/object:DateTime 2015-11-25 16:19:58.251000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:19:58.251000000 Z title: '2013,20134.12436' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1EGPJpRMnmuk6Y6c0Qigos/332e9d6c97776b73a42854cff4ea81b4/2013_20134.12436.jpg" caption: Painted figures of mounted horses with armed riders, two armed human figures on foot, several prone human figures, with possible mounted cow at lower right. Guilemsi, Tagant, Mauritania. 2013,20134.12424 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3646333&partId=1&searchText=Guilemsi,+Tagant&&page=2 - sys: id: 41eYfH850QI2GswScg6uE8 created_at: !ruby/object:DateTime 2015-11-25 16:31:05.524000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:31:05.524000000 Z content_type_id: chapter revision: 1 title_internal: 'Mauritania: featured site, chapter 8' body: |- It has been suggested that the painting of the horse scenes, in line with similar images from other rock art traditions, may be a cathartic spiritual exercise made, possibly by victims of raids, in response to violent intercultural contact. However as with the other images, without an accurate way of scientifically dating such paintings, it is hard to know exactly when they were painted and therefore difficult to propose of or by whom, much less ascribe motivations. Stone tools and the remains of iron smelting activity at Guilemsi suggest successive occupations, possibly over a long period. Stylistic links to other sites may be made, however: despite the fact that some of the iconography at Guilemsi appears quite unique, other elements, such as the bichrome cow in Fig. 6, and other square figures at Guilemsi of a man and giraffe, have similar looking counterparts in the Tichitt region, while the “bi-triangular” horses are found elsewhere in the Tagant and Adrar regions of Mauritania, and even as far away as Chad. Understanding of these links is still nascent, as is the interpretation of most Mauritanian rock art, but the variety present at Guilemsi is a valuable addition to the record, and more such sites may remain to be brought to the notice of scholars. citations: - sys: id: 1Y8dbSWSLaGs4Iyeq8COE created_at: !ruby/object:DateTime 2015-11-25 16:28:18.975000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:28:18.975000000 Z content_type_id: citation revision: 1 citation_line: |- <NAME>., <NAME>., <NAME>., & <NAME>., *Funerary Monuments and Horse Paintings: A Preliminary Report on the Archaeology of a Site in the Tagant Region of South East Mauritania- Near Dhar Tichitt*. The journal of North African Studies, Vol. 10, No. 3-4, pp. 459-470 <NAME>., <NAME>., <NAME>., & <NAME>. 2006, *Some Mauritanian Rock art Sites*. Sahara. Prehistory and History of the Sahara, Vol. 17, pp.143-148 background_images: - sys: id: 6uIYZ0iOROas4Uqo4u4UyW created_at: !ruby/object:DateTime 2015-11-25 16:19:51.669000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:19:51.669000000 Z title: '2013,2034.12382' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6uIYZ0iOROas4Uqo4u4UyW/3215c1e93f536598e0a14be6fcecfa82/2013_2034.12382.jpg" - sys: id: 7yy2sbn6PCoeuqyQOAgcA8 created_at: !ruby/object:DateTime 2015-11-25 16:19:58.288000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:19:58.288000000 Z title: '2013,2034.12494' description: url: "//images.ctfassets.net/xt8ne4gbbocd/7yy2sbn6PCoeuqyQOAgcA8/0914de8f403684d18accff0284017210/2013_2034.12494.jpg" key_facts: sys: id: 6IUFnTtK7eQeQawcmcoy0Y created_at: !ruby/object:DateTime 2015-11-26 11:26:24.685000000 Z updated_at: !ruby/object:DateTime 2017-11-17 17:32:32.000000000 Z content_type_id: country_key_facts revision: 2 title_internal: 'Mauritania: key facts' image_count: '208 images ' date_range: Mostly 3,000 BC onwards main_areas: Adrar and Tagant Plateaux, Tichitt-Walata area techniques: Engravings, painting main_themes: Cattle, hunting scenes with antelope and ostrich, horse riders, camels thematic_articles: - sys: id: 7oNFGUa6g8qSweyAyyiCAe created_at: !ruby/object:DateTime 2015-11-26 18:11:30.861000000 Z updated_at: !ruby/object:DateTime 2015-12-07 20:51:34.879000000 Z content_type_id: thematic revision: 4 title: The domesticated horse in northern African rock art slug: the-domesticated-horse lead_image: sys: id: n2MxgdjbMW2gm0IoOKkCU created_at: !ruby/object:DateTime 2015-11-26 17:51:43.133000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:43.133000000 Z title: Fig. 1. Painted horse description: url: "//images.ctfassets.net/xt8ne4gbbocd/n2MxgdjbMW2gm0IoOKkCU/e2c7369ef1e4ab11c71023a769f8fe0d/Fig._1._Painted_horse.jpg" chapters: - sys: id: 27bcd1mylKoMWiCQ2KuKMa created_at: !ruby/object:DateTime 2015-11-26 18:00:19.777000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:00:19.777000000 Z content_type_id: chapter revision: 1 title_internal: 'Thematic: horse, chapter 1' body: Throughout northern Africa, there is a wealth of rock art depicting the domestic horse and its various uses, providing valuable evidence for the uses of horses at various times in history, as well as a testament to their importance to Saharan peoples. - sys: id: 2EbfpTN9L6E0sYmuGyiaec created_at: !ruby/object:DateTime 2015-11-26 17:52:26.605000000 Z updated_at: !ruby/object:DateTime 2018-05-15 16:39:29.412000000 Z content_type_id: image revision: 2 image: sys: id: n2MxgdjbMW2gm0IoOKkCU created_at: !ruby/object:DateTime 2015-11-26 17:51:43.133000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:43.133000000 Z title: Fig. 1. Painted horse description: url: "//images.ctfassets.net/xt8ne4gbbocd/n2MxgdjbMW2gm0IoOKkCU/e2c7369ef1e4ab11c71023a769f8fe0d/Fig._1._Painted_horse.jpg" caption: 'Painted horse and rider, Ennedi Plateau, Chad. 2013,2034.6406 © TARA/David Coulson. ' col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3641775&partId=1&searchText=2013,2034.6406&page=1 - sys: id: 4QexWBEVXiAksikIK6g2S4 created_at: !ruby/object:DateTime 2015-11-26 18:00:49.116000000 Z updated_at: !ruby/object:DateTime 2018-05-15 16:40:28.446000000 Z content_type_id: chapter revision: 2 title: Horses and chariots title_internal: 'Thematic: horse, chapter 2' body: The first introduction of the domestic horse to Ancient Egypt- and thereby to Africa- is usually cited at around 1600 BC, linked with the arrival in Egypt of the Hyksos, a group from the Levant who ruled much of Northern Egypt during the Second Intermediate Period. By this point, horses had probably only been domesticated for about 2,000 years, but with the advent of the chariot after the 3rd millennium BC in Mesopotamia, the horse proved to be a valuable martial asset in the ancient world. One of the first clear records of the use of horses and chariots in battle in Africa is found in depictions from the mortuary complex of the Pharaoh Ahmose at Abydos from around 1525 BC, showing their use by Egyptians in defeating the Hyksos, and horses feature prominently in later Egyptian art. - sys: id: 22x06a7DteI0C2U6w6oKes created_at: !ruby/object:DateTime 2015-11-26 17:52:52.323000000 Z updated_at: !ruby/object:DateTime 2018-05-15 16:40:52.214000000 Z content_type_id: image revision: 2 image: sys: id: 1AZD3AxiUwwoYUWSWY8MGW created_at: !ruby/object:DateTime 2015-11-26 17:51:50.284000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:50.284000000 Z title: '2013,2034.1001' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1AZD3AxiUwwoYUWSWY8MGW/b68bd24c9b19c5c8c7752bfb75a5db0e/2013_2034.1001.jpg" caption: Painted two-horse chariot, Acacus Mountains, Libya. 2013,2034.1001 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3588526&partId=1&people=197356&museumno=2013,2034.1001&page=1 - sys: id: 1voXfvqIcQkgUYqq4w8isQ created_at: !ruby/object:DateTime 2015-11-26 18:01:15.173000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:01:15.173000000 Z content_type_id: chapter revision: 1 title_internal: 'Thematic: horse, chapter 3' body: 'Some of the most renowned images of horses in Saharan rock art are also those of chariot teams: in particular, those of the so-called ‘flying gallop’ style chariot pictures, from the Tassili n’Ajjer and Acacus mountains in modern Algeria and Libya. These distinctive images are characterised by depictions of one or more horses pulling a chariot with their legs outstretched in a stylised manner and are sometimes attributed to the Garamantes, a group who were a local power in the central Sahara from about 500 BC-700 AD. But the Ajjer Plateau is over a thousand miles from the Nile- how and when did the horse and chariot first make their way across the Western Desert to the rest of North Africa in the first place? Egyptian accounts indicate that by the 11th century BC Libyans (people living on the north African coast around the border of modern Egypt and Libya) were using chariots in war. Classical sources later write about the chariots of the Garamantes and of chariot use by peoples of the far western Sahara continuing into the 1st century BC, by which time the chariot horse had largely been eclipsed in war by the cavalry mount.' - sys: id: LWROS2FhUkywWI60eQYIy created_at: !ruby/object:DateTime 2015-11-26 17:53:42.845000000 Z updated_at: !ruby/object:DateTime 2018-05-15 16:41:33.841000000 Z content_type_id: image revision: 2 image: sys: id: 6N6BF79qk8EUygwkIgwcce created_at: !ruby/object:DateTime 2015-11-26 17:51:44.708000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:44.708000000 Z title: '2013,2034.4574' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6N6BF79qk8EUygwkIgwcce/ac95a5214a326794542e0707c0d819d7/2013_2034.4574.jpg" caption: Painted human figure and horse. Tarssed Jebest, Tassili n’Ajjer, Algeria. Horse displays Arabian breed-type characteristics such as dished face and high tail carriage. 2013,2034.4574 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3603790&partId=1&people=197356&museumno=2013,2034.4574+&page=1 - sys: id: 6eaH84QdUs46sEQoSmAG2u created_at: !ruby/object:DateTime 2015-11-26 18:01:48.835000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:01:48.835000000 Z content_type_id: chapter revision: 1 title: Horse Riding title_internal: 'Thematic: horse, chapter 4' body: As well as the unique iconography of rock art chariot depictions, there are also numerous paintings and engravings across northern Africa of people riding horses. Riding may have been practiced since the earliest times of horse domestication, though the earliest definitive depictions of horses being ridden come from the Middle East in the late 3rd and early 2nd millennia BC. Images of horses and riders in rock art occur in various areas of Morocco, Egypt and Sudan and are particularly notable in the Ennedi region of Chad and the Adrar and Tagant plateaus in Mauritania (interestingly, however, no definite images of horses are known in the Gilf Kebir/Jebel Uweinat area at the border of Egypt, Sudan and Libya). - sys: id: 6LTzLWMCTSak4IIukAAQMa created_at: !ruby/object:DateTime 2015-11-26 17:54:23.846000000 Z updated_at: !ruby/object:DateTime 2018-05-15 16:41:52.743000000 Z content_type_id: image revision: 2 image: sys: id: 4NdhGNLc9yEck4My4uQwIo created_at: !ruby/object:DateTime 2015-11-26 17:51:43.495000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:43.495000000 Z title: ME22958 description: url: "//images.ctfassets.net/xt8ne4gbbocd/4NdhGNLc9yEck4My4uQwIo/703945afad6a8e3c97d10b09c487381c/ME22958.jpg" caption: Terracotta mould of man on horseback, Old Babylonian, Mesopotamia 2000-1600 BC. One of the oldest known depictions of horse riding in the world. British Museum ME22958 © Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=388860&partId=1&people=197356&museumno=22958&page=1 - sys: id: 5YkSCzujy8o08yuomIu6Ei created_at: !ruby/object:DateTime 2015-11-26 17:54:43.227000000 Z updated_at: !ruby/object:DateTime 2018-05-16 11:12:34.068000000 Z content_type_id: image revision: 2 image: sys: id: 1tpjS4kZZ6YoeiWeIi8I4C created_at: !ruby/object:DateTime 2015-11-26 17:51:43.188000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:43.188000000 Z title: Fig. 5. Painted ‘bitriangular’ description: url: "//images.ctfassets.net/xt8ne4gbbocd/1tpjS4kZZ6YoeiWeIi8I4C/c798c1afb41006855c34363ec2b54557/Fig._5._Painted____bitriangular___.jpg" caption: Painted ‘bi-triangular’ horse and rider with saddle. Oued Jrid, Assaba, Mauritania. 2013,2034.12285 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3645983&partId=1&searchText=2013,2034.12285&page=1 - sys: id: 1vZDFfKXU0US2qkuaikG8m created_at: !ruby/object:DateTime 2015-11-26 18:02:13.433000000 Z updated_at: !ruby/object:DateTime 2018-05-16 11:14:56.468000000 Z content_type_id: chapter revision: 2 title_internal: 'Thematic: horse, chapter 5' body: Traditional chronologies for Saharan rock art areas tend to place depictions of ridden horses chronologically after those of horses and chariots, and in general use horse depictions to categorise regional stylistic periods of rock art according to broad date boundaries. As such, in most places, the ‘horse’ rock art period is usually said to cover about a thousand years from the end of the 2nd millennium BC. It is then considered to be succeeded by a ‘camel’ period, where the appearance of images of dromedaries – known only to have been introduced to the eastern Sahara from Arabia at the end of the 1st century BC – reflects the next momentous influx of a beast of burden to the area and thus a new dating parameter ([read more about depictions of camels in the Sahara](https://africanrockart.britishmuseum.org/thematic/camels-in-saharan-rock-art/)). However, such simplistic categorisation can be misleading. For one thing, although mounting horses certainly gained popularity over driving them, it is not always clear that depictions of ridden horses are not contemporary with those of chariots. Further, the horse remained an important martial tool after the use of war-chariots declined. Even after the introduction of the camel, there are several apparently contemporary depictions featuring both horse and camel riders. - sys: id: 2gaHPgtyEwsyQcUqEIaGaq created_at: !ruby/object:DateTime 2015-11-26 17:55:29.704000000 Z updated_at: !ruby/object:DateTime 2018-05-16 11:32:44.364000000 Z content_type_id: image revision: 3 image: sys: id: 6quML2y0nuYgSaeG0GGYy4 created_at: !ruby/object:DateTime 2015-11-26 17:51:50.292000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:50.292000000 Z title: '2013,2034.5739' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6quML2y0nuYgSaeG0GGYy4/7f48ae9c550dd6b4f0e80b8da10a3da6/2013_2034.5739.jpg" caption: Engraved ridden horse and camel. Draa Valley, Morocco. 2013,2034.5739 ©TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3619780&partId=1&people=197356&museumno=2013,2034.5739+&page=1 - sys: id: 583LKSbz9SSg00uwsqquAG created_at: !ruby/object:DateTime 2015-11-26 18:02:41.576000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:02:41.576000000 Z content_type_id: chapter revision: 1 title: Berber Horses title_internal: 'Thematic: horse, chapter 6' body: As the more manoeuvrable rider rose in popularity against the chariot as a weapon of war, historical reports from classical authors like Strabo tell us of the prowess of African horsemen such as the cavalry of the Numidians, a Berber group that allied with Carthage against the Romans in the 3rd century BC. Berber peoples would remain heavily associated with horse breeding and riding, and the later rock art of Mauritania has been attributed to Berber horsemen, or the sight of them. Although horses may already have reached the areas of modern Mauritania and Mali by this point, archaeological evidence does not confirm their presence in these south-westerly regions of the Sahara until much later, in the mid-1st millennium AD, and it has been suggested that some of the horse paintings in Mauritania may be as recent as 16th century. - sys: id: 7zrBlvCEGkW86Qm8k2GQAK created_at: !ruby/object:DateTime 2015-11-26 17:56:24.617000000 Z updated_at: !ruby/object:DateTime 2018-05-16 11:16:52.557000000 Z content_type_id: image revision: 2 image: sys: id: uOFcng0Q0gU8WG8kI2kyy created_at: !ruby/object:DateTime 2015-11-26 17:51:44.717000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:44.717000000 Z title: '2013,2034.5202' description: url: "//images.ctfassets.net/xt8ne4gbbocd/uOFcng0Q0gU8WG8kI2kyy/7fba0330e151fc416d62333f3093d950/2013_2034.5202.jpg" caption: Engraved horses and riders surrounded by Libyan-Berber script. Oued <NAME>. These images appear to depict riders using Arab-style saddles and stirrups, thus making them probably no older than 7th c. AD. 2013,2034.5202 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3624404&partId=1&people=197356&museumno=2013,2034.5202&page=1 - sys: id: 45vpX8SP7aGeOS0qGaoo4a created_at: !ruby/object:DateTime 2015-11-26 18:03:14.279000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:03:14.279000000 Z content_type_id: chapter revision: 1 title_internal: 'Thematic: horse, chapter 7' body: 'Certainly, from the 14th century AD, horses became a key commodity in trans-Saharan trade routes and became items of great military value in West Africa following the introduction of equipment such as saddles with structured trees (frames). Indeed, discernible images of such accoutrements in Saharan rock art can help to date it following the likely introduction of the equipment to the area: for example, the clear depiction of saddles suggests an image to be no older than the 1st century AD; images including stirrups are even more recent.' - sys: id: 7GeTQBofPamw0GeEAuGGee created_at: !ruby/object:DateTime 2015-11-26 17:56:57.851000000 Z updated_at: !ruby/object:DateTime 2018-05-16 11:29:02.520000000 Z content_type_id: image revision: 2 image: sys: id: 5MaSKooQvYssI4us8G0MyO created_at: !ruby/object:DateTime 2015-11-26 17:51:43.501000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:43.501000000 Z title: RRM12824 description: url: "//images.ctfassets.net/xt8ne4gbbocd/5MaSKooQvYssI4us8G0MyO/8c3a7c2d372f2c48a868d60201909932/RRM12824.jpg" caption: 19th-century Moroccan stirrups with typical curved base of the type possibly visible in the image above. 1939,0311.7-8 © Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=217451&partId=1&page=1 - sys: id: 6mNtqnqaEE2geSkU0IiYYe created_at: !ruby/object:DateTime 2015-11-26 18:03:32.195000000 Z updated_at: !ruby/object:DateTime 2018-05-16 11:29:50.228000000 Z content_type_id: chapter revision: 2 title_internal: 'Thematic: horse, chapter 8' body: 'Another intriguing possibility is that of gaining clues on the origins of modern horse breeds from rock art, in particular the ancient Barb breed native to the Maghreb, where it is still bred. Ancient Mesopotamian horses were generally depicted as heavily-built, and it has been suggested that the basic type for the delicate Arabian horse, with its dished (concave) facial profile and high-set tail, may have been developed in north-east Africa prior to its subsequent appearance and cultivation in Arabia, and that these features may be observed in Ancient Egyptian images from the New Kingdom. Likewise, there is the possibility that some of the more naturalistic paintings from the central Sahara show the similarly gracile features of the progenitors of the Barb, distinguishable from the Arab by its straight profile and low-set tail. Like the Arab, the Barb is a desert horse: hardy, sure-footed and able to withstand great heat; it is recognised as an ancient breed with an important genetic legacy, both in the ancestry of the Iberian horses later used throughout the Americas, and that of the modern racing thoroughbred.' - sys: id: 3OM1XJI6ruwGOwwmkKOKaY created_at: !ruby/object:DateTime 2015-11-26 17:57:25.145000000 Z updated_at: !ruby/object:DateTime 2018-05-16 11:30:30.915000000 Z content_type_id: image revision: 2 image: sys: id: 6ZmNhZjLCoQSEIYKIYUUuk created_at: !ruby/object:DateTime 2015-11-26 17:51:50.293000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:50.293000000 Z title: '2013,2034.1452' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6ZmNhZjLCoQSEIYKIYUUuk/45bbff5b29985eb19679e1e513499d6b/2013_2034.1452.jpg" caption: Engraved horses and riders, Awis, Acacus Mountains, Libya. High head carriage and full rumps suggest Arabian/Barb breed type features. Riders have been obscured. 2013,2034.1452 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3592678&partId=1&people=197356&museumno=2013,2034.1452&page=1 - sys: id: 40E0pTCrUIkk00uGWsus4M created_at: !ruby/object:DateTime 2015-11-26 17:57:49.497000000 Z updated_at: !ruby/object:DateTime 2018-05-16 11:33:55.443000000 Z content_type_id: image revision: 2 image: sys: id: 5mbJWrbZV6aQQOyamKMqIa created_at: !ruby/object:DateTime 2015-11-26 17:51:43.468000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:43.468000000 Z title: Fig. 10. Barb horses description: url: "//images.ctfassets.net/xt8ne4gbbocd/5mbJWrbZV6aQQOyamKMqIa/87f29480513be0a531e0a93b51f9eae5/Fig._10._Barb_horses.jpg" caption: Barb horses ridden at a festival in Agadir, Morocco. ©Notwist (Wikimedia Commons) col_link: https://commons.wikimedia.org/wiki/File:Berber_warriors_show.JPG - sys: id: 3z5YSVu9y8caY6AoYWge2q created_at: !ruby/object:DateTime 2015-11-26 18:04:02.770000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:04:02.770000000 Z content_type_id: chapter revision: 1 title: The symbolism of the horse title_internal: 'Thematic: horse, chapter 9' body: However, caution must be taken in drawing such comparisons based on morphology alone, especially given the gulf of time that has elapsed and the relative paucity of ‘naturalistic’ rock art images. Indeed, there is huge diversity of horse depictions throughout northern Africa, with some forms highly schematic. This variation is not only in style – and, as previously noted, in time period and geography – but also in context, as of course images of one subject cannot be divorced from the other images around them, on whichever surface has been chosen, and are integral to these surroundings. - sys: id: 1FRP1Z2hyQEWUSOoKqgic2 created_at: !ruby/object:DateTime 2015-11-26 17:58:21.234000000 Z updated_at: !ruby/object:DateTime 2019-02-21 15:41:39.821000000 Z content_type_id: image revision: 2 image: sys: id: 4EatwZfN72waIquQqWEeOs created_at: !ruby/object:DateTime 2015-11-26 17:51:43.121000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:43.121000000 Z title: '2013,2034.11147' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4EatwZfN72waIquQqWEeOs/d793f6266f2ff486e0e99256c2c0ca39/2013_2034.11147.jpg" caption: Engraved ‘Libyan Warrior-style’ figure with horse. Indakatte, Western Aïr Mountains, Niger. 2013,2034.11147 © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3637713&partId=1&people=197356&museumno=2013,2034.11147+&page=1 - sys: id: 45pI4ivRk4IM6gaG40gUU0 created_at: !ruby/object:DateTime 2015-11-26 17:58:41.308000000 Z updated_at: !ruby/object:DateTime 2019-02-21 15:41:59.784000000 Z content_type_id: image revision: 2 image: sys: id: 2FcYImmyd2YuqMKQMwAM0s created_at: !ruby/object:DateTime 2015-11-26 17:51:43.117000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:43.117000000 Z title: Fig. 12. Human figure description: url: "//images.ctfassets.net/xt8ne4gbbocd/2FcYImmyd2YuqMKQMwAM0s/e48fda8e2a23b12e6afde5c560c3f164/Fig._12._Human_figure.jpg" caption: Human figure painted over by horse to appear mounted (digitally enhanced image). © TARA/<NAME> - sys: id: 54hoc6Htwck8eyewsa6kA8 created_at: !ruby/object:DateTime 2015-11-26 18:04:26.929000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:04:26.929000000 Z content_type_id: chapter revision: 1 title_internal: 'Thematic: horse, chapter 10' body: The nature of the depictions in this sense speaks intriguingly of the apparent symbolism and implied value of the horse image in different cultural contexts. Where some Tassilian horses are delicately painted in lifelike detail, the stockier images of horses associated with the so-called ‘Libyan Warrior’ style petroglyphs of the Aïr mountains and Adrar des Ifoghas in Niger and Mali appear more as symbolic accoutrements to the central human figures and tend not to be shown as ridden. By contrast, there are paintings in the Ennedi plateau of Chad where galloping horse figures have clearly been painted over existing walking human figures to make them appear as if riding. - sys: id: 4XMm1Mdm7Y0QacMuy44EKa created_at: !ruby/object:DateTime 2015-11-26 17:59:06.184000000 Z updated_at: !ruby/object:DateTime 2019-02-21 15:42:27.444000000 Z content_type_id: image revision: 2 image: sys: id: 21xnJrk3dKwW6uSSkGumMS created_at: !ruby/object:DateTime 2015-11-26 17:51:44.697000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:44.697000000 Z title: '2013,2034.6297' description: url: "//images.ctfassets.net/xt8ne4gbbocd/21xnJrk3dKwW6uSSkGumMS/698c254a9a10c5a9a56d69e0525bca83/2013_2034.6297.jpg" caption: Engraved horse, <NAME>, <NAME>, Chad. 2013,2034.6297 © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3637529&partId=1&people=197356&museumno=2013,2034.6297&page=1 - sys: id: 4rB9FCopjOCC4iA2wOG48w created_at: !ruby/object:DateTime 2015-11-26 17:59:26.549000000 Z updated_at: !ruby/object:DateTime 2019-02-21 15:43:34.211000000 Z content_type_id: image revision: 2 image: sys: id: 3PfHuSbYGcqeo2U4AEKsmM created_at: !ruby/object:DateTime 2015-11-26 17:51:43.196000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:43.196000000 Z title: Fig. 14. Engraved horse description: url: "//images.ctfassets.net/xt8ne4gbbocd/3PfHuSbYGcqeo2U4AEKsmM/33a068fa954954fd3b9b446c943e0791/Fig._14._Engraved_horse.jpg" caption: Engraved horse, Eastern Aïr Mountains. 2013,2034.9421 ©TARA/<NAME>. col_link: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3640574&partId=1&searchText=2013,2034.9421&page=1 - sys: id: 6tFSQzFupywiK6aESCgCia created_at: !ruby/object:DateTime 2015-11-26 18:04:56.612000000 Z updated_at: !ruby/object:DateTime 2019-02-21 15:47:26.838000000 Z content_type_id: chapter revision: 2 title_internal: 'Thematic: horse, chapter 11' body: |- In each of these cases, the original symbolic intent of the artists have been lost to time, but with these horse depictions, as with so much African rock art imagery, there is great scope for further future analysis. Particularly intriguing, for example, are the striking stylistic similarities in horse depictions across great distances, such the horse depictions with bi-triangular bodies (see above), or with fishbone-style tails which may be found almost two thousand miles apart in Chad and Mauritania. Whatever the myriad circumstances and significances of the images, it is clear that following its introduction to the continent, the hardy and surefooted desert horse’s usefulness for draught, transport and fighting purposes transformed the societies which used it and gave it a powerful symbolic value. - sys: id: 2P6ERbclfOIcGEgI6e0IUq created_at: !ruby/object:DateTime 2015-11-26 17:59:46.042000000 Z updated_at: !ruby/object:DateTime 2019-02-21 15:45:12.419000000 Z content_type_id: image revision: 2 image: sys: id: 3UXc5NiGTYQcmu2yuU42g created_at: !ruby/object:DateTime 2015-11-26 17:51:43.128000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:43.128000000 Z title: Fig. 15. Painted horse, Terkei description: url: "//images.ctfassets.net/xt8ne4gbbocd/3UXc5NiGTYQcmu2yuU42g/7586f05e83f708ca9d9fca693ae0cd83/Fig._15._Painted_horse__Terkei.jpg" caption: Painted horse, Terkei, Ennedi Plateau, Chad. 2013,2034.6537 © TARA/David Coulson col_link: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3640682&partId=1&searchText=2013,2034.6537&page=1 citations: - sys: id: 32AXGC1EcoSi4KcogoY2qu created_at: !ruby/object:DateTime 2015-11-26 17:51:20.602000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:20.602000000 Z content_type_id: citation revision: 1 citation_line: "<NAME>. & <NAME>. 2000, *The Origins and Development of African Livestock: archaeology, genetics, linguistics and ethnography*. London; New York, NY: UCL Press\n \n<NAME>., <NAME>., <NAME>., 2012. *The Horse: From Arabia to Royal Ascot*. London: British Museum Press\n \nLaw, R., 1980. *The Horse in West African History*. Oxford: Oxford University Press\n \nHachid, M. 2000. *Les Premieres Berbères*. Aix-en-Provence: Edisud\n \nLhote, H. 1952. 'Le cheval et le chameau dans les peintures et gravures rupestres du Sahara', *Bulletin de l'Institut franç ais de l'Afrique noire* 15: 1138-228\n \n<NAME>. & <NAME>. 2010, *A gift from the desert: the art, history, and culture of the Arabian horse*. Lexington, KY: Kentucky Horse Park\n\n" background_images: - sys: id: 2avgKlHUm8CauWie6sKecA created_at: !ruby/object:DateTime 2015-12-07 18:44:31.346000000 Z updated_at: !ruby/object:DateTime 2015-12-07 18:44:31.346000000 Z title: EAF 141485 description: url: "//images.ctfassets.net/xt8ne4gbbocd/2avgKlHUm8CauWie6sKecA/cf02168ca83c922f27eca33f16e8cc90/EAF_141485.jpg" - sys: id: 1wtaUDwbSk4MiyGiISE6i8 created_at: !ruby/object:DateTime 2015-12-07 18:43:51.804000000 Z updated_at: !ruby/object:DateTime 2015-12-07 18:43:51.804000000 Z title: 01522751 001 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1wtaUDwbSk4MiyGiISE6i8/5918544d0289f9c4b2b4724f4cda7a2d/01522751_001.jpg" - sys: id: 1KwPIcPzMga0YWq8ogEyCO created_at: !ruby/object:DateTime 2015-11-26 16:25:56.681000000 Z updated_at: !ruby/object:DateTime 2015-12-07 20:49:15.151000000 Z content_type_id: thematic revision: 5 title: 'Sailors on sandy seas: camels in Saharan rock art' slug: camels-in-saharan-rock-art lead_image: sys: id: 46X3vtG1faouSYYws0Aywu created_at: !ruby/object:DateTime 2015-11-26 16:07:51.521000000 Z updated_at: !ruby/object:DateTime 2019-02-12 02:30:35.572000000 Z title: View of camel salt caravan crossing the Ténéré desert. Niger. ©David Coulson/TARA description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3652083&partId=1&searchText=2013,2034.10379&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/46X3vtG1faouSYYws0Aywu/6ff8cc3f26c918c81157746e1b2b3131/Fig._1._Camel.jpg" chapters: - sys: id: 1Q7xHD856UsISuceGegaqI created_at: !ruby/object:DateTime 2015-11-26 16:19:29.618000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:19:29.618000000 Z content_type_id: chapter revision: 1 title_internal: 'Camels: thematic, chapter 1' body: 'If we were to choose a defining image for the Sahara Desert, it would probably depict an endless sea of yellow dunes under a blue sky and, off in the distance, a line of long-legged, humped animals whose profiles have become synonymous with deserts: the one-humped camel (or dromedary). Since its domestication, the camel’s resistance to heat and its ability to survive with small amounts of water and a diet of desert vegetation have made it a key animal for inhabitants of the Sahara, deeply bound to their economy, material culture and lifestyle.' - sys: id: 4p7wUbC6FyiEYsm8ukI0ES created_at: !ruby/object:DateTime 2015-11-26 16:09:23.136000000 Z updated_at: !ruby/object:DateTime 2019-02-12 02:30:19.986000000 Z content_type_id: image revision: 3 image: sys: id: 46X3vtG1faouSYYws0Aywu created_at: !ruby/object:DateTime 2015-11-26 16:07:51.521000000 Z updated_at: !ruby/object:DateTime 2019-02-12 02:30:35.572000000 Z title: View of camel salt caravan crossing the Ténéré desert. Niger. ©David Coulson/TARA description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3652083&partId=1&searchText=2013,2034.10379&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/46X3vtG1faouSYYws0Aywu/6ff8cc3f26c918c81157746e1b2b3131/Fig._1._Camel.jpg" caption: Camel salt caravan crossing the Ténéré desert in Niger. 2013,2034.10487 ©<NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3652360&partId=1&searchText=2013,2034.10487&page=1 - sys: id: 1LsXHHPAZaIoUksC2US08G created_at: !ruby/object:DateTime 2015-11-26 16:19:46.820000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:19:46.820000000 Z content_type_id: chapter revision: 1 title_internal: 'Camels: thematic, chapter 2' body: Yet, surprising as it seems, the camel is a relative newcomer to the Sahara – at least when compared to other domestic animals such as cattle, sheep, horses and donkeys. Although the process is not yet fully known, camels were domesticated in the Arabian Peninsula around the third millennium BC, and spread from there to the Middle East, North Africa and Somalia from the 1st century AD onwards. The steps of this process from Egypt to the Atlantic Ocean have been documented through many different historical sources, from Roman texts to sculptures or coins, but it is especially relevant in Saharan rock art, where camels became so abundant that they have given their name to a whole period. The depictions of camels provide an incredible amount of information about the life, culture and economy of the Berber and other nomadic communities from the beginnings of the Christian era to the Muslim conquest in the late years of the 7th century. - sys: id: j3q9XWFlMOMSK6kG2UWiG created_at: !ruby/object:DateTime 2015-11-26 16:10:00.029000000 Z updated_at: !ruby/object:DateTime 2018-05-17 14:21:07.255000000 Z content_type_id: image revision: 2 image: sys: id: 6afrRs4VLUS4iEG0iwEoua created_at: !ruby/object:DateTime 2015-11-26 16:07:34.273000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:34.273000000 Z title: EA26664 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6afrRs4VLUS4iEG0iwEoua/e00bb3c81c6c9b44b5e224f5a8ce33a2/EA26664.jpg" caption: Roman terracotta camel with harness, 1st – 3rd century AD, Egypt. British Museum 1891,0403.31 © Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?museumno=1891,0430.31&objectId=118725&partId=1 - sys: id: NxdAnazJaUkeMuyoSOy68 created_at: !ruby/object:DateTime 2015-11-26 16:20:03.948000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:20:03.948000000 Z content_type_id: chapter revision: 1 title_internal: 'Camels: thematic, chapter 3' body: 'What is it that makes camels so suited to deserts? It is not only their ability to transform the fat stored in their hump into water and energy, or their capacity to eat thorny bushes, acacia leaves and even fish and bones. Camels are also able to avoid perspiration by manipulating their core temperature, enduring fluctuations of up to six degrees that could be fatal for other mammals. They rehydrate very quickly, and some of their physical features (nostrils, eyebrows) have adapted to increase water conservation and protect the animals from dust and sand. All these capacities make camels uniquely suited to hot climates: in temperatures of 30-40 °C, they can spend up to 15 days without water. In addition, they are large animals, able to carry loads of up to 300kg, over long journeys across harsh environments. The pads on their feet have evolved so as to prevent them from sinking into the sand. It is not surprising that dromedaries are considered the ‘ships of the desert’, transporting people, commodities and goods through the vast territories of the Sahara.' - sys: id: 2KjIpAzb9Kw4O82Yi6kg2y created_at: !ruby/object:DateTime 2015-11-26 16:10:36.039000000 Z updated_at: !ruby/object:DateTime 2018-05-17 14:39:34.523000000 Z content_type_id: image revision: 2 image: sys: id: 6iaMmNK91YOU00S4gcgi6W created_at: !ruby/object:DateTime 2015-11-26 16:07:51.477000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:51.477000000 Z title: Af1937,0105.16 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6iaMmNK91YOU00S4gcgi6W/4a850695b34c1766d1ee5a06f61f2b36/Af1937_0105.16.jpg" caption: Clay female dromedary (possibly a toy), Somalia. British Museum Af1937,0105.16 © Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?assetId=1088379&objectId=590967&partId=1 - sys: id: 12mIwQ0wG2qWasw4wKQkO0 created_at: !ruby/object:DateTime 2015-11-26 16:11:00.578000000 Z updated_at: !ruby/object:DateTime 2018-05-17 14:45:29.810000000 Z content_type_id: image revision: 2 image: sys: id: 4jTR7LKYv6IiY8wkc2CIum created_at: !ruby/object:DateTime 2015-11-26 16:07:51.505000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:51.505000000 Z title: Fig. 4. Man description: url: "//images.ctfassets.net/xt8ne4gbbocd/4jTR7LKYv6IiY8wkc2CIum/3dbaa11c18703b33840a6cda2c2517f2/Fig._4._Man.jpg" caption: Man leading a camel train through the Ennedi Plateau, Chad. 2013,2034.6134 ©<NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3636989&partId=1&searchText=2013,2034.6134&page=1 - sys: id: 6UIdhB0rYsSQikE8Yom4G6 created_at: !ruby/object:DateTime 2015-11-26 16:20:29.219000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:20:29.219000000 Z content_type_id: chapter revision: 1 title_internal: 'Camels: thematic, chapter 4' body: As mentioned previously, camels came from the Arabian Peninsula through Egypt, where bone remains have been dated to the early 1st millennium BC. However, it took hundreds of years to move into the rest of North Africa due to the River Nile, which represented a major geographical and climatic barrier for these animals. The expansion began around the beginning of the Christian era, and probably took place both along the Mediterranean Sea and through the south of the Sahara. At this stage, it appears to have been very rapid, and during the following centuries camels became a key element in the North African societies. They were used mainly for riding, but also for transporting heavy goods and even for ploughing. Their milk, hair and meat were also used, improving the range of resources available to their herders. However, it seems that the large caravans that crossed the desert searching for gold, ivory or slaves came later, when the Muslim conquest of North Africa favoured the establishment of vast trade networks with the Sahel, the semi-arid region that lies south of the Sahara. - sys: id: YLb3uCAWcKm288oak4ukS created_at: !ruby/object:DateTime 2015-11-26 16:11:46.395000000 Z updated_at: !ruby/object:DateTime 2018-05-17 14:46:15.751000000 Z content_type_id: image revision: 2 image: sys: id: 5aJ9wYpcHe6SImauCSGoM8 created_at: !ruby/object:DateTime 2015-11-26 16:06:48.336000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:06:48.336000000 Z title: '1923,0401.850' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5aJ9wYpcHe6SImauCSGoM8/74efd37612ec798fd91c2a46c65587f7/1923_0401.850.jpg" caption: Glass paste gem imitating beryl, engraved with a short, bearded man leading a camel with a pack on its hump. Roman Empire, 1st – 3rd century AD. 1923,0401.850 ©Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=434529&partId=1&museumno=1923,0401.850&page=1 - sys: id: 3uitqbkcY8s8GCcicKkcI4 created_at: !ruby/object:DateTime 2015-11-26 16:20:45.582000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:20:45.582000000 Z content_type_id: chapter revision: 1 title_internal: 'Camels: thematic, chapter 5' body: Rock art can be extremely helpful in learning about the different ways in which camels were used in the first millennium AD. Images of camels are found in both engravings and paintings in red, white or – on rare occasions – black; sometimes the colours are combined to achieve a more impressive effect. They usually appear in groups, alongside humans, cattle and, occasionally, dogs and horses. Sometimes, even palm trees and houses are included to represent the oases where the animals were watered. Several of the scenes show female camels herded or taking care of their calves, showing the importance of camel-herding and breeding for the Libyan-Berber communities. - sys: id: 5OWosKxtUASWIO6IUii0EW created_at: !ruby/object:DateTime 2015-11-26 16:12:17.552000000 Z updated_at: !ruby/object:DateTime 2018-05-17 15:11:49.775000000 Z content_type_id: image revision: 2 image: sys: id: 3mY7XFQW6QY6KekSQm6SIu created_at: !ruby/object:DateTime 2015-11-26 16:06:48.343000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:06:48.343000000 Z title: '2013,2034.383' description: url: "//images.ctfassets.net/xt8ne4gbbocd/3mY7XFQW6QY6KekSQm6SIu/85c0b70ab40ead396c695fe493081801/2013_2034.383.jpg" caption: Painted scene of a village, depicting a herd or caravan of camels guided by riders and dogs. W<NAME>, Acacus Mountains, Libya. 2013,2034.383 © David Coulson/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3579914&partId=1&museumno=2013,2034.383&page=1 - sys: id: 2Ocb7A3ig8OOkc2AAQIEmo created_at: !ruby/object:DateTime 2015-11-26 16:12:48.147000000 Z updated_at: !ruby/object:DateTime 2018-05-17 15:12:22.249000000 Z content_type_id: image revision: 2 image: sys: id: 2xR2nZml7mQAse8CgckCa created_at: !ruby/object:DateTime 2015-11-26 16:07:51.480000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:51.480000000 Z title: '2013,2034.5117' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2xR2nZml7mQAse8CgckCa/984e95b65ebdc647949d656cb08c0fc9/2013_2034.5117.jpg" caption: Engravings of a female camel with calves. Oued Djerat, Algeria. 2013,2034.5117 © David Coulson/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3624292&partId=1&museumno=2013,2034.5117&page=1 - sys: id: 4iTHcZ38wwSyGK8UIqY2yQ created_at: !ruby/object:DateTime 2015-11-26 16:13:13.897000000 Z updated_at: !ruby/object:DateTime 2018-05-17 15:31:09.339000000 Z content_type_id: image revision: 2 image: sys: id: 1ecCbVeHUGa2CsYoYSQ4Sm created_at: !ruby/object:DateTime 2015-11-26 16:07:34.241000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:34.241000000 Z title: Fig. 8. Painted description: url: "//images.ctfassets.net/xt8ne4gbbocd/1ecCbVeHUGa2CsYoYSQ4Sm/21b2aebd215d0691482411608ad5682f/Fig._8._Painted.jpg" caption: " Painted scene of Libyan-Berber warriors riding camels, accompanied by infantry and cavalrymen. Kozen Pass, Chad. 2013,2034.7295 © <NAME>/TARA" col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3655154&partId=1&searchText=2013,2034.7295&page=1 - sys: id: 2zqiJv33OUM2eEMIK2042i created_at: !ruby/object:DateTime 2015-11-26 16:21:08.068000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:21:08.068000000 Z content_type_id: chapter revision: 1 title_internal: 'Camels: thematic, chapter 6' body: |- That camels were used to transport goods is obvious, and depictions of long lines of animals are common, sometimes with saddles on which to place the packs and ropes to tie the animals together. However, if rock art depictions are some indication of camel use, it seems that until the Muslim conquest the main function of one-humped camels was as mounts, often linked to war. The Sahara desert contains dozens of astonishingly detailed images of warriors riding camels, armed with spears, long swords and shields, sometimes accompanied by infantry soldiers and horsemen. Although camels are not as good as horses for use as war mounts (they are too tall and make insecure platforms for shooting arrows), they were undoubtedly very useful in raids – the most common type of war activity in the desert – as well as being a symbol of prestige, wealth and authority among the desert warriors, much as they still are today. Moreover, the extraordinary detail of some of the rock art paintings has provided inestimable help in understanding how (and why) camels were ridden in the 1st millennium AD. Unlike horses, donkeys or mules, one-humped camels present a major problem for riders: where to put the saddle. Although it might be assumed that the saddle should be placed over the hump, they can, in fact, also be positioned behind or in front of the hump, depending on the activity. It seems that the first saddles were placed behind the hump, but that position was unsuitable for fighting, quite uncomfortable, and unstable. Subsequently, a new saddle was invented in North Arabia around the 5th century BC: a framework of wood that rested over the hump and provided a stable platform on which to ride and fight more effectively. The North Arabian saddle led to a revolution in the domestication of one-humped camels, allowed a faster expansion of the use of these animals, and it is probably still the most used type of saddle today. - sys: id: 6dOm7ewqmA6oaM4cK4cy8c created_at: !ruby/object:DateTime 2015-11-26 16:14:25.900000000 Z updated_at: !ruby/object:DateTime 2018-05-17 15:31:33.078000000 Z content_type_id: image revision: 2 image: sys: id: 5qXuQrcnUQKm0qCqoCkuGI created_at: !ruby/object:DateTime 2015-11-26 16:06:48.345000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:06:48.345000000 Z title: As1974,29.17 description: url: "//images.ctfassets.net/xt8ne4gbbocd/5qXuQrcnUQKm0qCqoCkuGI/2b279eff2a6f42121ab0f6519d694a92/As1974_29.17.jpg" caption: North Arabian-style saddle, with a wooden framework designed to be put around the hump. Jordan. British Museum As1974,29.17 © Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3320111&partId=1&object=23696&page=1 - sys: id: 5jE9BeKCBUEK8Igg8kCkUO created_at: !ruby/object:DateTime 2015-11-26 16:21:27.156000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:21:27.156000000 Z content_type_id: chapter revision: 1 title_internal: 'Camels: thematic, chapter 7' body: 'Although North Arabian saddles are found throughout North Africa and are often depicted in rock art paintings, at some point a new kind of saddle was designed in North Africa: one placed in front of the hump, with the weight over the shoulders of the camel. This type of shoulder saddle allows the rider to control the camel with the feet and legs, thus improving the ride. Moreover, the rider is seated in a lower position and thus needs shorter spears and swords that can be brandished more easily, making warriors more efficient. This new kind of saddle, which is still used throughout North Africa today, appears only in the western half of the Sahara and is well represented in the rock art of Algeria, Niger and Mauritania. And it is not only saddles that are recognizable in Saharan rock art: harnesses, reins, whips or blankets are identifiable in the paintings and show astonishing similarities to those still used today by desert peoples.' - sys: id: 6yZaDQMr1Sc0sWgOG6MGQ8 created_at: !ruby/object:DateTime 2015-11-26 16:14:46.560000000 Z updated_at: !ruby/object:DateTime 2018-05-17 15:33:25.754000000 Z content_type_id: image revision: 2 image: sys: id: 40zIycUaTuIG06mgyaE20K created_at: !ruby/object:DateTime 2015-11-26 16:07:51.466000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:51.466000000 Z title: Fig. 10. Painting description: url: "//images.ctfassets.net/xt8ne4gbbocd/40zIycUaTuIG06mgyaE20K/1736927ffb5e2fc71d1f1ab04310a73f/Fig._10._Painting.jpg" caption: Painting of rider on a one-humped camel. Note the North Arabian saddle on the hump, similar to the example from Jordan above. Terkei, Ennedi plateau, Chad. 2013,2034.6568 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3640623&partId=1&searchText=2013,2034.6568&page=1 - sys: id: 5jHyVlfWXugI2acowekUGg created_at: !ruby/object:DateTime 2015-11-26 16:15:13.926000000 Z updated_at: !ruby/object:DateTime 2018-05-17 15:36:07.603000000 Z content_type_id: image revision: 2 image: sys: id: 6EvwTsiMO4qoiIY4gGCgIK created_at: !ruby/object:DateTime 2015-11-26 16:07:34.249000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:34.249000000 Z title: '2013,2034.4471' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6EvwTsiMO4qoiIY4gGCgIK/1db47ae083ff605b9533898d9d9fb10d/2013_2034.4471.jpg" caption: Camel-rider using a North African saddle (in front of the hump), surrounded by warriors with spears and swords, with Libyan-Berber graffiti. <NAME>, Tassili, Algeria. 2013,2034.4471 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3602860&partId=1&museumno=2013,2034.4471&page=1 - sys: id: 57goC8PzUs6G4UqeG0AgmW created_at: !ruby/object:DateTime 2015-11-26 16:16:51.920000000 Z updated_at: !ruby/object:DateTime 2019-02-12 02:33:53.275000000 Z content_type_id: image revision: 3 image: sys: id: 5JDO7LrdKMcSEOMEG8qsS8 created_at: !ruby/object:DateTime 2015-11-26 16:07:34.250000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:34.250000000 Z title: Fig. 12. Tuaregs description: url: "//images.ctfassets.net/xt8ne4gbbocd/5JDO7LrdKMcSEOMEG8qsS8/76cbecd637724d549db8a7a101553280/Fig._12._Tuaregs.jpg" caption: Tuaregs at <NAME>, an annual meeting of desert peoples. Note the saddles in front of the hump and the camels' harnesses, similar to the rock paintings above such as the image from Terkei. Ingal, Northern Niger. 2013,2034.10523 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3652377&partId=1&searchText=2013,2034.10523&page=1 - sys: id: 3QPr46gQP6sQWswuSA2wog created_at: !ruby/object:DateTime 2015-11-26 16:21:50.767000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:21:50.767000000 Z content_type_id: chapter revision: 1 title_internal: 'Camels: thematic, chapter 8' body: Since their introduction to the Sahara during the first centuries of the Christian era, camels have become indispensable for desert communities, providing a method of transport for people and commodities, but also for their milk, meat and hair for weaving. They allowed the improvement of wide cultural and economic networks, transforming the Sahara into a key node linking the Mediterranean Sea with Sub-Saharan Africa. A symbol of wealth and prestige, the Libyan-Berber peoples recognized camels’ importance and expressed it through paintings and engravings across the desert, leaving a wonderful document of their societies. The painted images of camel-riders crossing the desert not only have an evocative presence, they are also perfect snapshots of a history that started two thousand years ago and seems as eternal as the Sahara. - sys: id: 54fiYzKXEQw0ggSyo0mk44 created_at: !ruby/object:DateTime 2015-11-26 16:17:13.884000000 Z updated_at: !ruby/object:DateTime 2018-05-17 16:01:13.379000000 Z content_type_id: image revision: 2 image: sys: id: 3idPZkkIKAOWCiKouQ8c8i created_at: !ruby/object:DateTime 2015-11-26 16:07:34.244000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:34.244000000 Z title: Fig. 13. Camel-riders description: url: "//images.ctfassets.net/xt8ne4gbbocd/3idPZkkIKAOWCiKouQ8c8i/4527b1eebe112ef9c38da1026e7540b3/Fig._13._Camel-riders.jpg" caption: Camel-riders galloping. Butress cave, Archael Guelta, Chad. 2013,2034.6077 ©David Coulson/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3637992&partId=1&searchText=2013,2034.6077&page=1 - sys: id: 1ymik3z5wMUEway6omqKQy created_at: !ruby/object:DateTime 2015-11-26 16:17:32.501000000 Z updated_at: !ruby/object:DateTime 2018-05-17 16:02:41.679000000 Z content_type_id: image revision: 2 image: sys: id: 4Y85f5QkVGQiuYEaA2OSUC created_at: !ruby/object:DateTime 2015-11-26 16:07:06.194000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:06.194000000 Z title: Fig. 14. Tuareg description: url: "//images.ctfassets.net/xt8ne4gbbocd/4Y85f5QkVGQiuYEaA2OSUC/4fbca027ed170b221daefdff0ae7d754/Fig._14._Tuareg.jpg" caption: Tuareg rider galloping at the Cure Salee meeting. Ingal, northern Niger. 2013,2034.10528 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3652371&partId=1&searchText=2013,2034.10528&page=1 background_images: - sys: id: 3mhr7uvrpesmaUeI4Aiwau created_at: !ruby/object:DateTime 2015-12-07 18:13:48.396000000 Z updated_at: !ruby/object:DateTime 2015-12-07 18:13:48.396000000 Z title: CHAENP0340003 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3mhr7uvrpesmaUeI4Aiwau/65c691f09cd60bb7aa08457e18eaa624/CHAENP0340003_1_.JPG" - sys: id: BPzulf3QNqMC4Iqs4EoCG created_at: !ruby/object:DateTime 2015-12-07 18:13:31.094000000 Z updated_at: !ruby/object:DateTime 2015-12-07 18:13:31.094000000 Z title: CHAENP0340001 description: url: "//images.ctfassets.net/xt8ne4gbbocd/BPzulf3QNqMC4Iqs4EoCG/356b921099bfccf59008b69060d20d75/CHAENP0340001_1_.JPG" - sys: id: 1hw0sVC0XOUA4AsiG4AA0q created_at: !ruby/object:DateTime 2017-11-23 11:49:41.362000000 Z updated_at: !ruby/object:DateTime 2017-11-23 11:49:41.362000000 Z content_type_id: thematic revision: 1 title: 'Introduction to rock art in northern Africa ' slug: rock-art-in-northern-africa lead_image: sys: id: 1fzfpavYuGaOKaAM2ko6es created_at: !ruby/object:DateTime 2015-11-26 15:53:30.004000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:53:30.004000000 Z title: '2013,2034.3840' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1fzfpavYuGaOKaAM2ko6es/f1e27e311dca40ce58657e5e88cb8526/2013_2034.3840.jpg" chapters: - sys: id: axu12ftQUoS04AQkcSWYI created_at: !ruby/object:DateTime 2015-11-26 15:58:10.885000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:58:10.885000000 Z content_type_id: chapter revision: 1 title: title_internal: 'North Africa: regional, chapter 1' body: 'The Sahara is the largest non-polar desert in the world, covering almost 8,600,000 km² and comprising most of northern Africa, from the Red Sea to the Atlantic Ocean. Although it is considered a distinct entity, it is composed of a variety of geographical regions and environments, including sand seas, hammadas (stone deserts), seasonal watercourses, oases, mountain ranges and rocky plains. Rock art is found throughout this area, principally in the desert mountain and hill ranges, where stone ''canvas'' is abundant: the highlands of Adrar in Mauritania and Adrar des Ifoghas in Mali, the Atlas Mountains of Morocco and Algeria, the Tassili n’Ajjer and Ahaggar Mountains in Algeria, the mountainous areas of Tadrart Acacus and Messak in Libya, the Aïr Mountains of Nigeria, the Ennedi Plateau and Tibesti Mountains in Chad, the Gilf Kebir plateau of Egypt and Sudan, as well as the length of the Nile Valley.' - sys: id: 4DelCmwI7mQ4MC2WcuAskq created_at: !ruby/object:DateTime 2015-11-26 15:54:19.234000000 Z updated_at: !ruby/object:DateTime 2016-12-22 10:12:21.657000000 Z content_type_id: image revision: 2 image: sys: id: 1fzfpavYuGaOKaAM2ko6es created_at: !ruby/object:DateTime 2015-11-26 15:53:30.004000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:53:30.004000000 Z title: '2013,2034.3840' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1fzfpavYuGaOKaAM2ko6es/f1e27e311dca40ce58657e5e88cb8526/2013_2034.3840.jpg" caption: Bubalus Period engraving. Pelorovis Antiquus, Wadi Mathendous, Libya. 2013,2034.3840 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3593438&partId=1&images=true&people=197356&museumno=2013,2034.3840&page=1 - sys: id: 2XmfdPdXW0Y4cy6k4O4caO created_at: !ruby/object:DateTime 2015-11-26 15:58:31.891000000 Z updated_at: !ruby/object:DateTime 2016-10-17 13:40:03.509000000 Z content_type_id: chapter revision: 3 title: Types of rock art and distribution title_internal: 'North Africa: regional, chapter 2' body: |+ Although the styles and subjects of north African rock art vary, there are commonalities: images are most often figurative and frequently depict animals, both wild and domestic. There are also many images of human figures, sometimes with accessories such as recognisable weaponry or clothing. These may be painted or engraved, with frequent occurrences of both, at times in the same context. Engravings are generally more common, although this may simply be a preservation bias due to their greater durability. The physical context of rock art sites varies depending on geographical and topographical factors – for example, Moroccan rock engravings are often found on open rocky outcrops, while Tunisia’s Djebibina rock art sites have all been found in rock shelters. Rock art in the vast and harsh environments of the Sahara is often inaccessible and hard to find, and there is probably a great deal of rock art that is yet to be seen by archaeologists; what is known has mostly been documented within the last century. - sys: id: 2HqgiB8BAkqGi4uwao68Ci created_at: !ruby/object:DateTime 2016-10-17 13:41:30.844000000 Z updated_at: !ruby/object:DateTime 2016-10-17 13:41:30.844000000 Z content_type_id: chapter revision: 1 title: History of research title_internal: 'North Africa: regional chapter 2.5' body: Although the existence of rock art throughout the Sahara was known to local communities, it was not until the nineteenth century that it became known to Europeans, thanks to explorers such as <NAME>, who crossed the Messak Plateau in Libya in 1850, first noting the existence of engravings. Further explorations in the early twentieth century by celebrated travellers, ethnographers and archaeologists such as <NAME>, <NAME>, László Almásy, <NAME> and <NAME> brought the rock art of Sahara, and northern Africa in general, to the awareness of a European public. - sys: id: 5I9fUCNjB668UygkSQcCeK created_at: !ruby/object:DateTime 2015-11-26 15:54:54.847000000 Z updated_at: !ruby/object:DateTime 2016-12-22 10:13:53.921000000 Z content_type_id: image revision: 2 image: sys: id: 2N4uhoeNLOceqqIsEM6iCC created_at: !ruby/object:DateTime 2015-11-26 15:53:37.250000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:53:37.250000000 Z title: '2013,2034.1424' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2N4uhoeNLOceqqIsEM6iCC/240a45012afba4ff5508633fcaea3462/2013_2034.1424.jpg" caption: Pastoral Period painting, cattle and human figure. Tin Taborak, Acacus Mountains, Libya. 2013,2034.1424 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3592663 - sys: id: 5OkqapzKtqEcomSucG0EoQ created_at: !ruby/object:DateTime 2015-11-26 15:58:52.432000000 Z updated_at: !ruby/object:DateTime 2016-10-17 13:45:37.885000000 Z content_type_id: chapter revision: 4 title: Attribution and dating title_internal: 'North Africa: regional, chapter 3' body: 'The investigations of these researchers and those who have followed them have sought to date and attribute these artworks, with varying measures of success. Rock art may be associated with certain cultures through known parallels with the imagery in other artefacts, such as Naqada Period designs in Egyptian rock art that mirror those on dateable pottery. Authorship may be also guessed at through corroborating evidence: for example, due to knowledge of their chariot use, and the location of rock art depicting chariots in the central Sahara, it has been suggested that it was produced by – or at the same time as – the height of the Garamantes culture, a historical ethnic group who formed a local power around what is now southern Libya from 500 BC–700 AD. However, opportunities to anchor rock art imagery in this way to known ancient cultures are few and far between, and rock art is generally ascribed to anonymous hunter-gatherers, nomadic peoples, or pastoralists, with occasional imagery-based comparisons made with contemporary groups, such as the Fulani peoples.' - sys: id: 2KmaZb90L6qoEAK46o46uK created_at: !ruby/object:DateTime 2015-11-26 15:55:22.104000000 Z updated_at: !ruby/object:DateTime 2016-12-22 10:16:53.318000000 Z content_type_id: image revision: 2 image: sys: id: 5A1AwRfu9yM8mQ8EeOeI2I created_at: !ruby/object:DateTime 2015-11-26 15:53:37.288000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:53:37.288000000 Z title: '2013,2034.1152' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5A1AwRfu9yM8mQ8EeOeI2I/cac0592abfe1b31d7cf7f589355a216e/2013_2034.1152.jpg" caption: Round Head Period painting, human figures. Wadi Tafak, Acacus Mountains, Libya. 2013,2034.1152 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3592099&partId=1&images=true&people=197356&page=1 - sys: id: 27ticyFfocuOIGwioIWWYA created_at: !ruby/object:DateTime 2015-11-26 15:59:26.852000000 Z updated_at: !ruby/object:DateTime 2016-10-17 15:18:29.234000000 Z content_type_id: chapter revision: 2 title_internal: 'North Africa: regional, chapter 4' body: |- Occasionally, association with writing in the form of, for example, Libyan-Berber or Arabic graffiti can give a known dating margin, but in general, lack of contemporary writing and written sources (Herodotus wrote about the Garamantes) leaves much open to conjecture. Other forms of (rare) circumstantial evidence, such as rock art covered by a dateable stratigraphic layer, and (more common) stylistic image-based dating have been used instead to form a chronology of Saharan rock art periods that is widely agreed upon, although dates are contested. The first stage, known as the Early Hunter, Wild Fauna or Bubalus Period, is posited at about 12,000–6,000 years ago, and is typified by naturalistic engravings of wild animals, in particular an extinct form of buffalo identifiable by its long horns. - sys: id: q472iFYzIsWgqWG2esg28 created_at: !ruby/object:DateTime 2015-11-26 15:55:58.985000000 Z updated_at: !ruby/object:DateTime 2016-12-22 10:19:11.991000000 Z content_type_id: image revision: 2 image: sys: id: 1YAVmJPnZ2QQiguCQsgOUi created_at: !ruby/object:DateTime 2015-11-26 15:53:29.989000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:53:29.989000000 Z title: '2013,2034.4570' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1YAVmJPnZ2QQiguCQsgOUi/4080b87891cb255e12a17216d7e71286/2013_2034.4570.jpg" caption: Horse Period painting, charioteer and standing horses. Tarssed Jebest, <NAME>, Algeria. 2013,2034.4570 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3603794 - sys: id: 7tsWGNvkQgACuKEMmC0uwG created_at: !ruby/object:DateTime 2015-11-26 15:59:47.880000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:59:47.880000000 Z content_type_id: chapter revision: 1 title_internal: 'North Africa: regional, chapter 5' body: A possibly concurrent phase is known as the Round Head Period (about 10,000 to 8,000 years ago) due to the large discoid heads of the painted human figures. Following this is the most widespread style, the Pastoral Period (around 7,500 to 4,000 years ago), which is characterised by numerous paintings and engravings of cows, as well as occasional hunting scenes. The Horse Period (around 3,000 to 2,000 years ago) features recognisable horses and chariots and the final Camel Period (around 2,000 years ago to present) features domestic dromedary camels, which we know to have been widely used across the Sahara from that time. - sys: id: 13V2nQ2cVoaGiGaUwWiQAC created_at: !ruby/object:DateTime 2015-11-26 15:56:25.598000000 Z updated_at: !ruby/object:DateTime 2016-12-22 10:39:22.861000000 Z content_type_id: image revision: 2 image: sys: id: 6MOI9r5tV6Gkae0CEiQ2oQ created_at: !ruby/object:DateTime 2015-11-26 15:53:29.964000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:53:29.964000000 Z title: 2013,2034.1424 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6MOI9r5tV6Gkae0CEiQ2oQ/bad4ec8dd7c6ae553d623e4238641561/2013_2034.1424_1.jpg" caption: Camel engraving. <NAME>, <NAME>, Sudan. 2013,2034.335 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3586831 - sys: id: 3A64bY4VeMGkKCsGCGwu4a created_at: !ruby/object:DateTime 2015-11-26 16:00:04.267000000 Z updated_at: !ruby/object:DateTime 2016-10-17 15:30:04.896000000 Z content_type_id: chapter revision: 2 title_internal: 'North Africa: regional, chapter 6' body: "While this chronology serves as a useful framework, it must be remembered that the area – and the time period in which rock art was produced – is extensive and there is significant temporal and spatial variability within and across sites. There are some commonalities in rock art styles and themes across the Sahara, but there are also regional variations and idiosyncrasies, and a lack of evidence that any of these were directly, or even indirectly, related. The engravings of weaponry motifs from Morocco and the painted ‘swimming’ figures of the Gilf Kebir Plateau in Egypt and Sudan are not only completely different, but unique to their areas. Being thousands of kilometres apart and so different in style and composition, they serve to illustrate the limitations inherent in examining northern African rock art as a unit. The contemporary political and environmental challenges to accessing rock art sites in countries across the Sahara serves as another limiting factor in their study, but as dating techniques improve and further discoveries are made, this is a field with the potential to help illuminate much of the prehistory of northern Africa.\n\n" citations: - sys: id: 4AWHcnuAVOAkkW0GcaK6We created_at: !ruby/object:DateTime 2016-10-17 15:15:38.284000000 Z updated_at: !ruby/object:DateTime 2016-10-17 15:15:38.284000000 Z content_type_id: citation revision: 1 citation_line: | <NAME>. 1998. Art rupestre et préhistoire du Sahara: le Messak Libyen. Paris: Payot & Rivages <NAME>. 1995. Les images rupestres du Sahara. — Toulouse (author’s ed.), p. 447 <NAME>. 2001. Saharan Africa in (ed) <NAME>, Handbook of Rock Art Research, pp 605-636. AltaMira Press, Walnut Creek Riemer, H. 2013. Dating the rock art of Wadi Sura, in Wadi Sura – The Cave of Beasts, Kuper, R. (ed). Africa Praehistorica 26 – Köln: Heinrich-Barth-Institut, pp. 38-39 <NAME>. 1999. L'art rupestre du Haut Atlas Marocain. Paris, L'Harmattan Soukopova, J. 2012. Round Heads: The Earliest Rock Paintings in the Sahara. Newcastle upon Tyne: Cambridge Scholars Publishing Vernet, R. 1993. Préhistoire de la Mauritanie. Centre Culturel Français A. de Saint Exupéry-Sépia, Nouakchott background_images: - sys: id: 3ZTCdLVejemGiCIWMqa8i created_at: !ruby/object:DateTime 2015-12-07 19:41:46.025000000 Z updated_at: !ruby/object:DateTime 2015-12-07 19:41:46.025000000 Z title: EAF135068 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3ZTCdLVejemGiCIWMqa8i/5a0d13fdd2150f0ff81a63afadd4258e/EAF135068.jpg" - sys: id: 2jvgN3MMfqoAW6GgO8wGWo created_at: !ruby/object:DateTime 2015-12-07 19:41:50.029000000 Z updated_at: !ruby/object:DateTime 2015-12-07 19:41:50.029000000 Z title: EAF131007 description: url: "//images.ctfassets.net/xt8ne4gbbocd/2jvgN3MMfqoAW6GgO8wGWo/393c91068f4dc0ca540c35a79b965288/EAF131007.jpg" country_introduction: sys: id: 5uLhtUXIeA0kma8usA44eM created_at: !ruby/object:DateTime 2015-11-26 13:13:33.481000000 Z updated_at: !ruby/object:DateTime 2015-12-07 13:40:48.819000000 Z content_type_id: country_information revision: 2 title: 'Mauritania: country introduction' chapters: - sys: id: 7ZVEMUYkGAcAwIGQ2aYiu created_at: !ruby/object:DateTime 2015-11-26 13:03:29.927000000 Z updated_at: !ruby/object:DateTime 2015-11-26 13:03:29.927000000 Z content_type_id: chapter revision: 1 title: Introduction title_internal: 'Mauritania: country, chapter 1' body: Mauritania is one of Africa’s westernmost countries, stretching over 1,000 km inland from the Atlantic coast into the Sahara. Mauritania’s corpus of rock art is extensive and mostly appears to have been produced within the last 4,000 years. - sys: id: 6rGE0FRNFmqKCEwOOy2sEg created_at: !ruby/object:DateTime 2015-11-26 12:53:11.539000000 Z updated_at: !ruby/object:DateTime 2017-01-09 16:41:03.423000000 Z content_type_id: image revision: 2 image: sys: id: 6a9PIc2PD2GoSys6umKim created_at: !ruby/object:DateTime 2015-11-26 12:50:25.597000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:15:13.181000000 Z title: '2013,2034.12277' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3645968&partId=1&searchText=2013,2034.12277&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/6a9PIc2PD2GoSys6umKim/df4fd71d342462545f28c306a798de62/2013_2034.12277.jpg" caption: Painted horses, riders and standing human figure. Oued <NAME> <NAME>. 2013,2034.12277 © TARA/<NAME> col_link: http://bit.ly/2iaQquq - sys: id: 6BfTuIwDOEMoiw6AUYSiYm created_at: !ruby/object:DateTime 2015-11-26 13:04:41.054000000 Z updated_at: !ruby/object:DateTime 2017-01-09 16:41:57.874000000 Z content_type_id: chapter revision: 2 title: Geography and rock art distribution title_internal: 'Mauritania: country, chapter 2' body: |- In total Mauritania covers about 1,030,700 km², most of which forms part of the western portion of the Sahara desert. The southern part of Mauritania incorporates some of the more temperate Sahelian zone, forming part of the geographical and cultural border between Saharan and Sub-Saharan Africa. The landscape of the country is generally characterised by its flatness, but the two major neighbouring plateaux in the East-Centre of the country – the Tagant in the South and the Adrar further North – are furnished with rock shelters, boulders and other surfaces upon which can be found abundant rock art, more often engraved than painted. The principal concentrations of rock art in Mauritania are located in these two areas, as well as in the North around Bir Moghreïn (in the Mauritanian extension of the Zemmur mountains), the Hank ridge near the borders of Algeria and Mali and the Tichitt-Walata area to the east of the Tagant plateau. __Adrar__ There are about thirty known rock art sites in the Adrar region, although, as with most Mauritanian rock art, study has not been comprehensive and there may be many more as yet undocumented. Engraved rock art sites dominate along the northern edge of the massif, with some of the most significant to be found at the sites of El Beyyed and El Ghallaouiya. Rarer paintings of cattle are also to be found at El Ghallaouiya, as well as at the site of Amogjar. __Tagant__ Less well studied than Adrar, the Tagant plateau contains several painting sites showing horses and riders such as those at the sites of Agneitir Dalma and Tinchmart. The archaeologically significant area of the Tichitt-Walata ridge, a chain of escarpments known for its Neolithic settlements, is largely located within the wider Tagant region to the east of the plateau, and also features many engravings and some paintings. - sys: id: 1xRX7rqW0s4Wo0ewQCUGWu created_at: !ruby/object:DateTime 2015-11-26 13:05:22.127000000 Z updated_at: !ruby/object:DateTime 2015-11-26 13:05:22.127000000 Z content_type_id: chapter revision: 1 title: Research history title_internal: 'Mauritania: country, chapter 3' body: |- Recording and research on Mauritanian rock art has been limited in comparison with other Saharan rock art traditions, and has mainly been undertaken by French scholars, as Mauritania was formerly part of French West Africa. The first major publications cataloguing rock art sites in the country were those of Théodore Monod (1937-8), based on recordings collected on expeditions made between 1934 and 1936 and covering the entire western Saharan region. Following this, the explorers <NAME> and Odette du Puigaudeau published some paintings of the Tagant region in1939. A more comprehensive study of the paintings, engravings and inscriptions of West and North West Africa was made by <NAME> (1954), and emphasised the importance of systematically recording and studying the images in their contexts. More recently (1993), <NAME> produced a synthesis of known Mauritanian rock art in his *Préhistoire de la Mauritanie*. Many individual Mauritanian rock art sites have also been recorded and published over the decades since the 1940s, particularly in the context of associated archaeological sites, such as those at Tegdaoust and in the Tichitt-Walata region. - sys: id: 66wyHEf39KoaOmm4YA8ko created_at: !ruby/object:DateTime 2015-11-26 12:53:57.337000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:53:57.337000000 Z content_type_id: image revision: 1 image: sys: id: 4lA1J5Jly0MSImIsQ2GwUo created_at: !ruby/object:DateTime 2015-11-26 12:50:25.581000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:50:25.581000000 Z title: '2013,2034.2312' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4lA1J5Jly0MSImIsQ2GwUo/91ed83183f46bedf859da6b1fb5ffcaa/2013_2034.2312.jpg" caption: 'Painted geometric circle design, <NAME>, <NAME>, Mauritania. 2013,2034.2312 © TARA/<NAME> ' col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3618068&partId=1&searchText=2013,2034.2312&page=1 - sys: id: 3Lde3TfwY8aWu26K84weUa created_at: !ruby/object:DateTime 2015-11-26 13:05:45.305000000 Z updated_at: !ruby/object:DateTime 2015-11-26 13:05:45.305000000 Z content_type_id: chapter revision: 1 title: Themes title_internal: 'Mauritania: country, chapter 4' body: |- The range of subject matter in the rock art of Mauritania is similar to that of other Saharan countries, consisting primarily of images of domestic cattle, along with those of horses both mounted and unmounted, human figures and weaponry, wild fauna, hunting scenes, camels and Libyco-Berber/Tifinagh and Arabic script. Images of goats and sheep are extremely rare. Some general geographic tendencies in style and type can be made out, for example, deeply cut and polished naturalistic engravings of large wild animals are concentrated in the North of the country. There is an apparent North-South divide in engraving style, with images becoming more schematic further south. Rarer painting sites are clustered in certain areas such as north of Bir Moghreïn in the far north, and certain Adrar sites, with horse and rider paintings most common in the Tagant and Tichitt-Walata regions. - sys: id: AHzKqrsBricmEQwCmOYyQ created_at: !ruby/object:DateTime 2015-11-26 12:54:38.583000000 Z updated_at: !ruby/object:DateTime 2018-09-17 18:03:32.564000000 Z content_type_id: image revision: 2 image: sys: id: 5u1VecbrbOq4cCICyqiOAw created_at: !ruby/object:DateTime 2015-11-26 12:50:25.656000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:20:04.418000000 Z title: '2013,2034.12427' description: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3646352&partId=1&searchText=2013,2034.12427&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/5u1VecbrbOq4cCICyqiOAw/c4223338beae42378b3c34f8ab1b5a8e/2013_2034.12421.jpg" caption: Painted heads of antelope facing left, Guilemsi, Tadrart, Mauritania. 2013,2034.12427 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3646352&partId=1&searchText=2013,2034.12427&page=1 - sys: id: 4itpl0jzpKAqkcCa6yKqa6 created_at: !ruby/object:DateTime 2015-11-26 13:06:05.325000000 Z updated_at: !ruby/object:DateTime 2015-11-26 13:06:05.325000000 Z content_type_id: chapter revision: 1 title_internal: 'Mauritania: country, chapter 5' body: |- Mauritanian rock art consists most commonly of similar-looking scenes of cattle, hunting tableaux, or camel depictions, but there are some exceptions of interest, for example: the monumental bull engraving from Akhrejit in the Dhar Tichitt, which is nearly 5 metres long; the unusually naturalistic paintings of cattle at Amogjar and Tenses in the Adrar; and the curiously shaped painted horses at Guilemsi in the Tagant-Titchitt region. In addition, although images of chariots apparently drawn by oxen are known elsewhere in the Sahara, chariots in Saharan rock art are normally associated with horses. In Mauritania, however, there are several images of ox chariots or carts – both painted and engraved – as well as depictions of cattle apparently bearing burdens/saddles, or mounted. Moreover, Mauritania has no known depictions of chariots where the draught animal is identifiably a horse, although there are many images of horses and riders. Sometimes chariots are depicted independent of any animals drawing them, and in all there are over 200 known images of chariots in the country. - sys: id: 3MShhKY9bWiw8u6WGkek6s created_at: !ruby/object:DateTime 2015-11-26 12:55:35.339000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:55:35.339000000 Z content_type_id: image revision: 1 image: sys: id: 5LOsfjF8UEYmIUaQ00cA8i created_at: !ruby/object:DateTime 2015-11-26 12:50:25.657000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:50:25.657000000 Z title: '2013,2034.12381' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5LOsfjF8UEYmIUaQ00cA8i/2f5c949384c4cd1e5a23e4cc77a4904f/2013_2034.12381.jpg" caption: Cattle painted with different designs, Guilemsi, Tagant, Mauritania. 2013,2034.12381 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3646170&partId=1&searchText=2013,2034.12381+&page=1 - sys: id: 2mhsdlyizy886WMQkoOmmM created_at: !ruby/object:DateTime 2015-11-26 12:56:29.522000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:56:29.522000000 Z content_type_id: image revision: 1 image: sys: id: 6Cccz71bd66Es0EcmMqICa created_at: !ruby/object:DateTime 2015-11-26 12:50:25.724000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:50:25.724000000 Z title: '2013,2034.12449' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6Cccz71bd66Es0EcmMqICa/82071c6a91a03c64020c9d7ce81fc354/2013_2034.12449.jpg" caption: Cattle painted with different designs, Guilemsi, Tagant, Mauritania. 2013,2034.12449 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3647071&partId=1&searchText=2013%2c2034.12449&page=1 - sys: id: 5vzOFu8OlOEAUMGS0KYIw2 created_at: !ruby/object:DateTime 2015-11-26 13:06:27.333000000 Z updated_at: !ruby/object:DateTime 2015-11-26 13:06:27.333000000 Z content_type_id: chapter revision: 1 title: Chronology title_internal: 'Mauritania: country, chapter 6' body: 'As is the case with all Saharan rock art, sites found in Mauritania are very difficult to date, especially absolutely. Monod remarked: ‘it is impossible to propose even approximate dates: no landmark pinpoints the end of the Neolithic and the arrival of Libyan (Berber) horsemen’ (Monod, 1938, p.128). Relative chronologies of rock art styles are easier to identify than specific dates, as they may be based on visible elements such as superimpositions in paintings, and the darkness level of accrued patina in engravings. In Mauritania, researchers have generally paid particular attention to patina as well as themes and styles in order to try and place a timeframe on different rock art traditions. Even this is an inexact science – however, Monod did propose a three-phase chronology, with 1) ‘Ancient’ prehistoric rock art showing large wild fauna and cattle, 2) ‘Middle’ pre-Islamic art showing horses, camels, riders, arms and armour, hunting scenes and Libyco-Berber script and 3) ‘Modern’ Islamic-era art with modern Tifinagh and Arabic inscriptions.' - sys: id: 79JveWwduEWS0GOECouiCi created_at: !ruby/object:DateTime 2015-11-26 12:57:03.931000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:57:03.931000000 Z content_type_id: image revision: 1 image: sys: id: W4EibqP766CYAamWyqkQK created_at: !ruby/object:DateTime 2015-11-26 12:50:25.952000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:21:05.070000000 Z title: '2013,2034.12332' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3646132&partId=1&searchText=2013,2034.12332&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/W4EibqP766CYAamWyqkQK/523fee62695a3de60ff7940899dfaaf1/2013_2034.12332.jpg" caption: Engraved geometric shapes, M’Treoka, <NAME>, Mauritania. 2013,2034.12332 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3646132&partId=1&searchText=2013%2c2034.12332&page=1 - sys: id: 4AtrIwkF7OaKCEAiQ2GASg created_at: !ruby/object:DateTime 2015-11-26 13:06:44.804000000 Z updated_at: !ruby/object:DateTime 2015-11-26 13:06:44.804000000 Z content_type_id: chapter revision: 1 title_internal: 'Mauritania: country, chapter 7' body: Mauny later proposed a more nuanced chronology, based also on style and technique, along the same lines as Monod’s. Mauny’s proposed divisions include a ‘naturalist’ period from 5,000–2,000 BC, a cattle pastoralist phase from 2,500–1,000 BC, a horse period from 1,200 BC onwards, a ‘Libyco-Berber’ group from 200 BC–700 AD and a final ‘Arabo-Berber’ phase from 700 AD onwards (Mauny, 1954). While the oldest rock art, such as the paintings at Amogjar, could be more than 5,000 years old, it appears that most Mauritanian rock art probably post-dates 2,000 BC, with some, particularly that involving camels, made within the last 2,000 years. - sys: id: 4lUHWxICtWgQ0w6iy28iEI created_at: !ruby/object:DateTime 2015-11-26 13:07:10.157000000 Z updated_at: !ruby/object:DateTime 2015-11-26 13:07:10.157000000 Z content_type_id: chapter revision: 1 title_internal: 'Mauritania: country, chapter 8' body: 'Further evidence from the archaeological record and historical knowledge is helpful in ascribing dates and authorship to some of the rock art. The time period over which rock art was produced in Mauritania coincided with dramatic changes in the climate and the desertification of the Sahara, which settled at present levels of aridity following increased dry periods: around 1,500 BC in the North, and by the mid-1st Millenium AD in the South. There is some evidence for a combination of hunting and pastoral activity in the North-East prior to the desertification, with pastoralism becoming an important means of subsistence in the South after 2,000 BC.' - sys: id: 48cLDAbqdim44m0G0kAiMm created_at: !ruby/object:DateTime 2015-11-26 12:58:12.334000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:58:12.334000000 Z content_type_id: image revision: 1 image: sys: id: 6gZ1qhryX6EM26sQo4MWYQ created_at: !ruby/object:DateTime 2015-11-26 12:50:26.009000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:50:26.009000000 Z title: '2013,2034.12340' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6gZ1qhryX6EM26sQo4MWYQ/ffd1149106f1364f7e7c15130243b5cc/2013_2034.12340.jpg" caption: Crocodiles in pool below engraving site at M’Treoka with relict populations of crocodiles. Hodh el Garbi, Mauritania. 2013,2034.12340 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3646115&partId=1&searchText=2013,2034.12340&page=1 - sys: id: 2f2rsdCUH6yWQkC2y4i6aC created_at: !ruby/object:DateTime 2015-11-26 13:07:28.228000000 Z updated_at: !ruby/object:DateTime 2015-11-26 13:07:28.228000000 Z content_type_id: chapter revision: 1 title_internal: 'Mauritania: country, chapter 9' body: The first solid archaeological evidence for horses this far west is from about 600 AD. However, horses and chariots could have been introduced over a thousand years before, possibly by early Berber peoples from the North, who are thought to have made increased incursions from the 4th Millennium onwards, and with whom much of the rock art is usually associated. Chariot images can be reasonably assumed to date from the time we know chariots were in use in the Sahara – i.e. not earlier than 1,200 BC. - sys: id: 3bDBY7ve9GkIoEAeqCKe6M created_at: !ruby/object:DateTime 2015-11-26 13:07:55.785000000 Z updated_at: !ruby/object:DateTime 2015-11-26 13:07:55.785000000 Z content_type_id: chapter revision: 1 title: Interpretation title_internal: 'Mauritania: country, chapter 10' body: 'Generally, the study of Mauritanian rock art traditions has focused more on cataloguing the images and categorising them by style, technique and perceived age than investigating their potential cultural significance. The limitations in the ability to scientifically date these images, and the fact that they are not usually associated with other archaeological materials, hinders effective attempts at interpretation or ascribing authorship, beyond basic ‘Neolithic’ ‘pastoralist’, or ‘early Berber’. Even this may not be clear-cut or mutually exclusive: for example, incoming Berber peoples in the Adrar Plateau after 2,000 BC are thought to have been cattle pastoralists, as their non-Berber predecessors probably were. In addition, while the desertification process was definitive from this time on, fluctuations and regional microclimates made pastoralism viable relatively recently in some areas – in the Adrar there is still evidence of cattle rearing as late as 1,000 BC or after, and some areas of the Tagant region may have been able to support cattle as late as the 18th century. Thus subject matter alone is not necessarily indicative of date or authorship: depictions of cattle may be Berber or non-Berber, as old as the 4th millennium BC or as recent as the 1st, if not later.' - sys: id: 3j9ouDudwkk8qqEqqsOI4i created_at: !ruby/object:DateTime 2015-11-26 12:58:46.100000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:58:46.100000000 Z content_type_id: image revision: 1 image: sys: id: 4zNeoXAAesUaCGoaSic6qO created_at: !ruby/object:DateTime 2015-11-26 12:50:25.588000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:21:40.547000000 Z title: '2013,2034.12285' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3645983&partId=1&searchText=2013,2034.12285&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/4zNeoXAAesUaCGoaSic6qO/97398e8ebe5bd8be1adf57f450a72e08/2013_2034.12285.jpg" caption: Painted ‘bitriangular’ horse and rider with saddle, Guilemsi, Mauritania. 2013,2034.12285 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3645983&partId=1&searchText=2013%2c2034.12285&page=1 - sys: id: 5Rfj3BIjRugQEoOOwug8Qm created_at: !ruby/object:DateTime 2015-11-26 13:08:21.025000000 Z updated_at: !ruby/object:DateTime 2015-11-26 13:08:21.025000000 Z content_type_id: chapter revision: 1 title_internal: 'Mauritania: country, chapter 11' body: It is possible to make some more specific inferences based on style. Some of the more naturalistic cattle paintings from the Adrar have been compared in style to the Bovidian style paintings of the Tassili n’Ajjer in Libya, and some of the more geometric designs to others in Senegal and Mali. Links have also been suggested between some cattle and symbolic images and modern Fulani and Tuareg traditions and iconography. In terms of significance, changes to rock art style over time, from naturalistic to schematic, have been remarked upon as perhaps somehow reflecting environmental changes from savannah to steppe and desert. It has also been debated whether some of the geometric symbols and images of riders on horseback were the result of conflict, perhaps made by the victims of Berber invasions as catharsis or to ward off evil. - sys: id: 2NWh1MPulOkK4kQSgKuwyO created_at: !ruby/object:DateTime 2015-11-26 12:59:21.672000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:59:21.672000000 Z content_type_id: image revision: 1 image: sys: id: 6NlmQWPzJSiCWEIek2ySa8 created_at: !ruby/object:DateTime 2015-11-26 12:50:26.009000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:50:26.009000000 Z title: '2013,2034.12390' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6NlmQWPzJSiCWEIek2ySa8/f6454e19c8de0ed0ba409100bc3cd56b/2013_2034.12390.jpg" caption: Handprint, Guilemsi, Tagant, Mauritania.2013,2034.12390 © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3646185&partId=1&searchText=2013%2c2034.12390&page=1 - sys: id: 32ujQ27WmIokwSaq0g8y8E created_at: !ruby/object:DateTime 2015-11-26 13:08:35.046000000 Z updated_at: !ruby/object:DateTime 2015-11-26 13:08:35.046000000 Z content_type_id: chapter revision: 1 title_internal: 'Mauritania: country, chapter 12' body: At this point, however, such inferences are fragmentary and speculative, and it is clear that more comprehensive study of rock art in context in the region is desirable, as it potentially holds much interest for the study of the history and prehistory of Mauritania. It is also an endangered resource, due to a combination of environmental factors, such as extremes of temperature which damage and split the rocks, and human interference from looting and vandalism. citations: - sys: id: 4BBq4ePWQEC2Y2OmceCGgW created_at: !ruby/object:DateTime 2015-11-26 12:51:23.581000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:51:23.581000000 Z content_type_id: citation revision: 1 citation_line: |- <NAME>., 2010. *Mauritanian Rock Art: A New Recording*. Biblioteca Alexandrina, Alexandria <NAME>, 1954 *Gravures, peintures et inscriptions rupestres de l'Ouest africain*. Vol. 11. Institut français d'Afrique noire Monod, T., 1938. *Contributions à l’étude du Sahara Occidental. Gravures, Peintures et Inscriptions rupestres*. Publications du Comité d’études historiques et scientifiques de l’Afrique occidentale française, Paris <NAME>. 1993. *Préhistoire de la Mauritanie*. Centre Culturel Français A. de Saint Exupéry-Sépia, Nouakchott Vernet, R. & <NAME>. *Dictionnaire Archéologique de la Mauritanie*. CRIAA, Université de Nouakchott background_images: - sys: id: 5MkqJUXrj2o4e8SmweeoW2 created_at: !ruby/object:DateTime 2015-11-25 16:19:58.333000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:19:58.333000000 Z title: '2013,2034.12357' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5MkqJUXrj2o4e8SmweeoW2/92eeb35eb7e827596e213cd06cf9fe4a/2013_2034.12357.jpg" - sys: id: 1uRo8OtMas0sE0uiOUSIok created_at: !ruby/object:DateTime 2015-11-25 16:19:58.328000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:19:58.328000000 Z title: '2013,2034.12416' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1uRo8OtMas0sE0uiOUSIok/71ebc908be14899de348803b21cddc31/2013_2034.12416.jpg" - sys: id: 6uIYZ0iOROas4Uqo4u4UyW created_at: !ruby/object:DateTime 2015-11-25 16:19:51.669000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:19:51.669000000 Z title: '2013,2034.12382' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6uIYZ0iOROas4Uqo4u4UyW/3215c1e93f536598e0a14be6fcecfa82/2013_2034.12382.jpg" region: Northern / Saharan Africa ---<file_sep>/_coll_country_information/kenya-country-introduction.md --- contentful: sys: id: 142GjmRwVygmAiU6Q0AYmA created_at: !ruby/object:DateTime 2015-11-26 15:35:38.627000000 Z updated_at: !ruby/object:DateTime 2015-12-07 13:43:02.363000000 Z content_type_id: country_information revision: 2 title: 'Kenya: country introduction' chapters: - sys: id: 2sEl2XznyQ66Eg22skoqYu created_at: !ruby/object:DateTime 2015-11-26 15:28:45.582000000 Z updated_at: !ruby/object:DateTime 2015-12-11 11:51:02.714000000 Z content_type_id: chapter revision: 2 title: Introduction title_internal: 'Kenya: country, chapter 1' body: Rock art is distributed widely throughout Kenya, although historically rock art research has not been as extensive as in neighbouring countries such as Tanzania. Some of Kenya's various rock art traditions are attributed to or associated with the ancestors of modern regional cultural groups, and as such sites sometimes retain local religious importance. Both painted and engraved imagery tends towards the symbolic and geometric, with occasional depictions of schematic animals and people. It must be noted that there are still probably many Kenyan rock art sites which have not yet become known outside of their local communities, if they are known at all. - sys: id: 6nL6NLL93GQUyiQaWAgakG created_at: !ruby/object:DateTime 2015-11-26 15:23:16.663000000 Z updated_at: !ruby/object:DateTime 2017-01-13 16:02:48.785000000 Z content_type_id: image revision: 3 image: sys: id: 191BlqkgSUmU20ckCQqCyk created_at: !ruby/object:DateTime 2015-12-08 18:49:22.434000000 Z updated_at: !ruby/object:DateTime 2015-12-08 18:49:22.434000000 Z title: KENMTE0010018 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/191BlqkgSUmU20ckCQqCyk/72813bbadf5ed408fa5515940ff369f8/KENMTE0010018_1.jpg" caption: Painted panel with cattle. Kakapel, south of Mount Elgon 2013,2034.13640 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3699416&partId=1&searchText=2013,2034.13640&page=1 - sys: id: 2VIFeJyqys02i4Uc4wGmas created_at: !ruby/object:DateTime 2015-11-26 15:29:20.719000000 Z updated_at: !ruby/object:DateTime 2017-01-13 16:15:40.192000000 Z content_type_id: chapter revision: 3 title: Geography and rock art distribution title_internal: 'Kenya: country, chapter 2' body: Kenya covers about 569,140km², bordering Ethiopia and Somalia in the north and east and Tanzania and Uganda in the south and west. The country stretches from a low-lying eastern coastal strip, inland to highland regions in the west of the country. Kenya's western half is divided by the eastern section of the East African Rift, the long area of tectonic divergence which runs from the coasts of Djibouti, Eritrea and Somalia down through Ethiopia and Kenya and into Uganda, curving around the eastern edge of the Lake Victoria basin. There are a significant number of painted rock art sites throughout west-central and southern Kenya. - sys: id: 69Hu2xajVCWIyOCCI6cQuC created_at: !ruby/object:DateTime 2015-11-26 15:23:43.746000000 Z updated_at: !ruby/object:DateTime 2018-05-17 16:39:32.374000000 Z content_type_id: image revision: 4 image: sys: id: 4ZkoqzwyVaAuciGqmAUqwC created_at: !ruby/object:DateTime 2015-12-08 18:49:17.623000000 Z updated_at: !ruby/object:DateTime 2015-12-08 18:49:17.623000000 Z title: KENKAJ0010017 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/4ZkoqzwyVaAuciGqmAUqwC/240ce914ba1f5a1a6c05c71b1f587617/KENKAJ0010017_1.jpg" caption: 'View of the Rift Valley near Mount Suswa 2013,2034.12836 © <NAME>/TARA. ' col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3776423&partId=1 - sys: id: 54kNwI6Yq4wU88i6MoaM0K created_at: !ruby/object:DateTime 2015-11-26 15:30:05.512000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:30:05.512000000 Z content_type_id: chapter revision: 1 title: Research history title_internal: 'Kenya: country, chapter 3' body: 'Although researchers had been noting and investigating rock art in the neighbouring countries of Tanzania and Uganda from the early years of the 20th Century, the first published mention of Kenyan rock art appeared only in 1946, with <NAME>''s descriptions of engravings at Surima, in the northern Turkana region. It was in the 1960s that sustained academic attention began to be paid to other sites in the country. In 1961 <NAME> published an account of a rock shelter (now known as Kiptogot Cave) with painted images of cattle on the slopes of Mount Elgon near Kitale. Wright suggested potential parallels in style with some Ethiopian pastoralist rock art. In 1968 <NAME> was the first archaeologist to investigate the unique Namoratung’a burial sites to the east of Lake Turkana, with their engraved standing stones, the interpretation of which would be continued with the work of <NAME> and <NAME> in the 1970s. In the same decade significant painting sites at Lake Victoria, north of the lake near the Ugandan border, and in the far south were also reported on by <NAME>, <NAME> and <NAME>. Research and discovery has continued and is likely that many rock art sites in Kenya remain to be documented. As recently as 2005, 21 previously unknown rock art sites in the Samburu area of central Kenya were recorded during dedicated survey work organised by the British Institute in East Africa. ' - sys: id: 1VQjZKKOhCUCC0sMKmI2EG created_at: !ruby/object:DateTime 2015-11-26 15:24:16.333000000 Z updated_at: !ruby/object:DateTime 2017-01-13 17:16:53.891000000 Z content_type_id: image revision: 3 image: sys: id: 3o8IJEfzbWI4qiywkMu8WM created_at: !ruby/object:DateTime 2015-12-08 18:49:17.505000000 Z updated_at: !ruby/object:DateTime 2015-12-08 18:49:17.505000000 Z title: KENVIC0010004 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3o8IJEfzbWI4qiywkMu8WM/6c5d99356b89ab8e961c347207547889/KENVIC0010004_1.jpg" caption: Painted panel showing concentric circles and spirals. Kwitone Shelter, Mfangano Island. 2013,2034.14238 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3685727&partId=1&searchText=2013,2034.14238&page=1 - sys: id: 4t7LVO1JeES8agW2AK2Q0k created_at: !ruby/object:DateTime 2015-11-26 15:31:05.485000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:31:13.826000000 Z content_type_id: chapter revision: 2 title: Themes title_internal: 'Kenya: country, chapter 4' body: "Figurative imagery only features prominently in about 10% of the known rock art sites of Kenya. That which exists tends to consist of very schematic images of cattle, wild animals and people. The majority of both painted and engraved rock art iconography throughout Kenya comprises symbols, with common patterns including circles, sometimes concentric or containing crosses, spirals, parallel or cross-hatched lines and curvilinear shapes. Circular ground depressions in the rock surface, known as cupules, are also a common variant of rock art in Kenya, along with rock gongs, which show evidence of the use of natural rock formations as percussive instruments.\n\nInterpretation, cultural attribution and proposed dates for these works vary widely across technique and area, although there are common themes. It has been suggested that the schematic nature and similarities in the art may point to shared East African symbolic understandings common to different cultural groups, for example equating circular shapes (some of the most popular motifs in Eastern and Central African rock art in general) with chieftainship or the sun, or acting as navigation devices.\n\nGiven the variations in distance, age and nature of the sites, there is a danger of generalising, but there are factors which may contribute to more incisive interpretations of specific sites and symbols. One set of interpretations for geometric shapes in Kenyan rock art points to the similarities of certain of these symbols to cattle brands used by Nilotic peoples throughout Kenya, including the Turkana, Samburu and Masai groups. Although the engravings at Namoratung'a are not thought to have been made by ancestral Turkana people, Lynch and Robbins noted the similarities of some of the symbols found there to contemporary local Turkana cattle brands. \ These symbols are pecked on stones at graves containing mens’ remains and have been proposed to represent male lineages, as animal brands traditionally do in contemporary Nilotic ethnic groups. Further south, it is known that some more recent rock paintings representing brand and shield patterns were made by Masai and Samburu men, in shelters used for meat-feasting—a practice forbidden in their home compounds after their formal initiation as warriors—or as initiation sites. Actual representations of cattle are rare, with the vibrant paintings at Kakapel near the Ugandan border the most reknowned. Their creators are unknown although Masai and Samburu have been known to paint occasional schematic cattle in the past. \n" - sys: id: 2J6pAiklT2mgAqmGWYiKm4 created_at: !ruby/object:DateTime 2015-11-26 15:24:54.228000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:24:54.228000000 Z content_type_id: image revision: 1 image: sys: id: 6sJEag1degeScYa0IYY66a created_at: !ruby/object:DateTime 2015-11-26 15:19:31.878000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:19:31.878000000 Z title: '2013,2034.13567' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6sJEag1degeScYa0IYY66a/7b598c98a08f07a8af2290ee301c897d/KENLOK0040007.jpg" caption: Stone circles at Namoratung’a. 2013,2034.13567 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3660580&partId=1&searchText=2013,2034.13567&page=1 - sys: id: 2FBovUnIEU0om2mG2qCKAM created_at: !ruby/object:DateTime 2015-11-26 15:31:50.127000000 Z updated_at: !ruby/object:DateTime 2017-01-13 17:19:42.052000000 Z content_type_id: chapter revision: 3 title_internal: 'Kenya: country, chapter 5' body: Not all of Kenya's rock art is associated with pastoralists. Much of the symbolic art, particularly to the south and west, is attributed to the ’Batwa’, ancestors of modern Batwa and related, traditionally hunter-gatherer cultural groups living around the Great Lakes Region of East and Central Africa. Circular designs and “Sunburst” symbols are some of the most common motifs usually associated with the Batwa rock art tradition; it has been proposed that they may have been associated with fertility or rainmaking. Some rock art on Mfangano Island, in the Kenyan portion of Lake Victoria, has retained the latter association, having been used until the recent past by local Abasuba people for rainmaking purposes, despite their not having produced it originally. This re-use of symbolic sites in Kenya and the difficulty of dating further confuses the question of attribution for the art. The same rock art sites used by different cultural groups at different times and for different reasons. Such is the case at Kakapel for example, where it is posited that the earliest paintings may be hunter-gatherer in origin, with more recent cattle images added later, and Namoratung’a, with some engravings apparently hundreds of years old and others made within the last century. - sys: id: 1Rc5KyPQDS0KG8mY0g2CwI created_at: !ruby/object:DateTime 2015-11-26 15:25:30.561000000 Z updated_at: !ruby/object:DateTime 2017-01-13 17:20:10.830000000 Z content_type_id: image revision: 2 image: sys: id: 1rIqvHUlxCgqW2caioAo4I created_at: !ruby/object:DateTime 2015-11-26 15:18:52.034000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:22:07.193000000 Z title: '2013,2034.13018' description: url: "//downloads.ctfassets.net/xt8ne4gbbocd/1rIqvHUlxCgqW2caioAo4I/eaa5e32c3a5c09c5904157da0d3a9f0b/KENLAI0060017.jpg" caption: Ndorobo man observing Maa-speaker symbols, possibly representing cattle brands. Laikipia 2013,2034.13018 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3700186&partId=1&searchText=2013,2034.13018&page=1 - sys: id: 63k9ZNUpEW0wseK2kKmSS2 created_at: !ruby/object:DateTime 2015-11-26 15:32:19.445000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:32:19.445000000 Z content_type_id: chapter revision: 1 title_internal: 'Kenya: country, chapter 6' body: It is instructive to consider the use of rock art sites within their physical contexts as well as the rock art motifs themselves. Locality and landscape are significant, for example at Namoratung’a, where the engraved basalt pillars at a related nearby site have been posited to be positioned according to astronomical calculations, based on an ancient Cushitic calendar. There are various ways in which the creation and continued use of sites in Kenya may have been significantly interactive, such as in the ritual playing of rock gongs, or in the potential use of rows of cupules as gaming boards for forms of Mancala, a token game common through central and Southern Africa which was originally introduced to Kenya via Indian Ocean trade. It is not known if cupules were actually created for this purpose—it has been suggested for example that in some areas, cupules were formed for purely practical purposes, in the pulverising of food or materials for smelting activities. In Kenya, as elsewhere, what actually constitutes rock art is not always easy to identify. - sys: id: 473wFp8s7CKyuyuIW22KCs created_at: !ruby/object:DateTime 2015-11-26 15:26:01.650000000 Z updated_at: !ruby/object:DateTime 2017-01-23 16:01:02.004000000 Z content_type_id: image revision: 2 image: sys: id: 6CNVylYrKwUkk0YCcaYmE4 created_at: !ruby/object:DateTime 2015-11-26 15:20:17.930000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:20:17.930000000 Z title: '2013,2034.13694' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6CNVylYrKwUkk0YCcaYmE4/084ab0278a8863a0cbc3ac1f631eceea/KENNEP0020002.jpg" caption: Rock gong with cupules. Lewa Downs Conservancy, Kenya. 2013,2034.13694 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3701781&partId=1&searchText=2013,2034.13694&page=1 - sys: id: 24Sdya41Gk4migwmYa60SW created_at: !ruby/object:DateTime 2015-11-26 15:32:57.237000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:32:57.237000000 Z content_type_id: chapter revision: 1 title: Chronology title_internal: 'Kenya: country, chapter 7' body: "Rock art ascribed to Batwa peoples could be anywhere between 15,000-1,000 years old, while pastoralist art is more recent. Radiocarbon dating of rock art is difficult unless it is buried and associated with other uncontaminated organic remains and as such, scientifically dated rock art from Kenya is rare. \ Radiocarbon dates from human remains in graves at Namoratung’a South date from the mid-1st Century BC to the mid-1st Millennium AD, but as dates like these are not directly relatable to the rock art, researchers have tended to concentrate on assigning chronologies based on varying levels of patination and style, without being able to ascribe more than estimated production dates. \ \n\nThere are occasionally defining limits which aid in dating specific sites, for example, cattle did not arrive in Eastern Africa until about 2,000 BC, so representations of cattle must postdate this. In addition, in some cases, artworks known to have been associated with certain groups cannot have been produced prior to, or post, certain dates for political reasons. For example, Masai paintings at Lukenya Hill are known to have been painted prior to 1915, as Masai people were displaced from this area by European settlers after this date. \n\nThe diversity of Kenyan rock art in motif, distribution and cultural context so far frustrates any attempts for a cohesive chronology, but the continuing local engagement with rock art sites in Kenya can potentially serve as a useful dating and interpretive resource for researchers alongside continuing archaeological research." - sys: id: 5FBcxryfEQMUwYeYakwMSo created_at: !ruby/object:DateTime 2015-11-26 15:26:31.130000000 Z updated_at: !ruby/object:DateTime 2017-01-23 16:41:13.806000000 Z content_type_id: image revision: 4 image: sys: id: 4dt5Tw7AXeoiMOkAqGIoWa created_at: !ruby/object:DateTime 2015-12-08 18:49:43.959000000 Z updated_at: !ruby/object:DateTime 2015-12-08 18:49:43.959000000 Z title: KENTUR0010065 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/4dt5Tw7AXeoiMOkAqGIoWa/53ffe55ad755f4931e5651e84da47892/KENTUR0010065_1.jpg" caption: Engraved rock art showing giraffes and human figures. Turkana County, Lewa Downs Conservancy, Kenya. 2013,2034.13848 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3663256&partId=1&searchText=2013,2034.13848+&page=1 citations: - sys: id: 1r3TUrs7ziOaQ08iEOQ2gC created_at: !ruby/object:DateTime 2015-11-26 15:27:37.639000000 Z updated_at: !ruby/object:DateTime 2015-12-11 11:55:17.747000000 Z content_type_id: citation revision: 2 citation_line: | <NAME>. 1975. *Meat-feasting Sites and Cattle Brands: Patterns of Rock-shelter Utilization in East Africa*. Azania, Vol. 10, Issue 1, pp. 107-122 <NAME>. & <NAME>. 2011. *A re-consideration of the rock engravings at the burial site of Namoratung'a South, Northern Kenya and their relationship to modern Turkana livestock brands*. South African Archaeological Bulletin Vol. 66, Issue194, pp. 121-128 <NAME>. 1992. *Ethnographic Context of Rock Art Sites in East Africa in Rock Art and Ethnology*. AURA Occasional Papers, (5) pp. 67-70, Australian Rock Art Research Association, Melbourne <NAME>. 1974. *The Prehistoric rock art of the lake Victoria region*. Azania, IX, 1-50. ---<file_sep>/_coll_thematic/written-in-stone.md --- contentful: sys: id: 5QHjLLZ7gs846I0a68CGCg created_at: !ruby/object:DateTime 2015-11-25 17:59:00.673000000 Z updated_at: !ruby/object:DateTime 2015-12-11 12:29:03.345000000 Z content_type_id: thematic revision: 6 title: 'Written in stone: the Libyco-Berber scripts' slug: written-in-stone lead_image: sys: id: 5m9CnpjjOgEIeiaW6k6SYk created_at: !ruby/object:DateTime 2015-11-25 17:39:38.305000000 Z updated_at: !ruby/object:DateTime 2015-12-08 08:25:55.339000000 Z title: '2013,2034.4200' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5m9CnpjjOgEIeiaW6k6SYk/3dd6ae7d242722aa740c7229eb70d4e7/ALGDJA0040010.jpg" chapters: - sys: id: 3fpuPIJW9i2ESgqYsEMe02 created_at: !ruby/object:DateTime 2015-11-25 17:49:07.520000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:49:16.531000000 Z content_type_id: chapter revision: 2 title_internal: 'Libyco-Berber: thematic, chapter 1' body: 'A remarkable feature of North African rock art is the existence of numerous engraved or painted inscriptions which can be found throughout the Sahara Desert. These inscriptions, generically named Libyco-Berber, are found from the west of Egypt to the Canary Islands and from the Mediterranean Sea to the Sahel countries to the south. Together with Egyptian hieroglyphs, they show us one of the earliest written languages in Africa and represent a most interesting and challenging topic in North African history. They appear in two different formats: engraved on *stelae* (mainly on the Mediterranean coast and its hinterland) or on rock faces, either isolated or alongside rock art paintings or engravings of the later periods of rock art.' - sys: id: 6MFGcsOw2QYceK2eWSsGqY created_at: !ruby/object:DateTime 2015-11-25 17:43:10.618000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:32:20.694000000 Z content_type_id: image revision: 3 image: sys: id: 5m9CnpjjOgEIeiaW6k6SYk created_at: !ruby/object:DateTime 2015-11-25 17:39:38.305000000 Z updated_at: !ruby/object:DateTime 2015-12-08 08:25:55.339000000 Z title: '2013,2034.4200' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5m9CnpjjOgEIeiaW6k6SYk/3dd6ae7d242722aa740c7229eb70d4e7/ALGDJA0040010.jpg" caption: View of red wolf or lion with an spiral tail. A Libyco-Berber script has been written under the belly, and another one can be seen to the lower left of the photograph. Tin Aboteka, Tassili n'Ajjer, Algeria. 2013,2034.4200 ©TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3601330&partId=1&searchText=2013,2034.4200&page=1 - sys: id: TwRWy4YkkUmg2yMGIWOQw created_at: !ruby/object:DateTime 2015-11-25 17:49:54.544000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:33:58.483000000 Z content_type_id: chapter revision: 3 title_internal: 'Libyco-Berber: thematic, chapter 2' body: Libyco-Berber characters were identified as written language as early as the 17th century, when some inscriptions in the language were documented in the Roman city of Dougga (Tunisia). They were deciphered by <NAME> in 1843 through the comparison of personal names with equivalent Punic names in bilingual scenes, although a few characters still remain uncertain. Since the beginning of the 19th century onwards many different proposals have been made to explain the origin, expansion and translation of these alphabets. There are three main explanations of its origin - the most accepted theory considers that the Libyco-Berber alphabet and principles of writing were borrowed from the Phoenician script, with other symbols added locally. - sys: id: pfjxB9ZjI4c68SYYOcc6C created_at: !ruby/object:DateTime 2015-11-25 17:43:34.886000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:35:37.505000000 Z content_type_id: image revision: 3 image: sys: id: 1i0U2eePgyWQKE8WgOEuug created_at: !ruby/object:DateTime 2015-11-25 17:40:16.321000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:56:27.808000000 Z title: Libyco theme figure 2 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1i0U2eePgyWQKE8WgOEuug/03cf171fe9cde8389b055b4740f8d1fd/29-10-2015_11.05.jpg" caption: Half of a bilingual inscription written in Numidian, part of a monument dedicated to Ateban, a Numidian prince. Numidian is one of the languages written in Libyco-Berber alphabets. 1852,0305.1 ©Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=368104&partId=1&searchText=1852,0305.1&page=1 - sys: id: 2QHgN5FuFGK4aoaWUcKuG2 created_at: !ruby/object:DateTime 2015-11-25 17:50:30.377000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:50:30.377000000 Z content_type_id: chapter revision: 1 title_internal: 'Libyco-Berber: thematic, chapter 3' body: A second, recent proposal has defended an indigenous (autochthonous) origin deriving from a stock of ancient signs –tribal tattoos, marks of ownership, or even geometric rock art- which could have resulted in the creation of the alphabet. Finally, a mixture of both theories accepts the borrowing of the idea of script and some Phoenician signs, which would be complemented with indigenous symbols. Although none of these theories can be fully accepted or refuted at the present moment, the proposal of a Phoenician borrowing has a wider support among linguistics and archaeologists. - sys: id: 67cDVCAn3GMK8m2guKMeuY created_at: !ruby/object:DateTime 2015-11-25 17:44:09.415000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:37:11.219000000 Z content_type_id: image revision: 2 image: sys: id: 4kXC2w9xCwAASweyCgwg2O created_at: !ruby/object:DateTime 2015-11-25 17:40:34.619000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:40:34.619000000 Z title: '2013,2034.4996' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4kXC2w9xCwAASweyCgwg2O/4d864b520d505029c7c8b90cd9e5fde2/ALGTOD0050035.jpg" caption: Engraved panel full of camels and human figures, surrounded by Libyco-Berber graffiti. <NAME>, Tassili n’Ajjer, Algeria. 2013,2034.4996 ©TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3623989&partId=1&searchText=2013,2034.4996&page=1 - sys: id: 4UXtnuK0VGkYKMGyuqseKI created_at: !ruby/object:DateTime 2015-11-25 17:50:56.343000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:50:56.343000000 Z content_type_id: chapter revision: 1 title: title_internal: 'Libyco-Berber: thematic, chapter 4' body: 'How is the Libyco-Berber alphabet composed? In fact, we should talk about Libyco-Berber alphabets, as one of the main characteristics of these scripts is their variety. In the mid-20th century, two main groups (eastern and western) were proposed, but this division is not so evident, and some studies have identified up to 25 different groups (grouped in 5 major families); some of them show strong similarities while between others up to half of the alphabetic symbols may be different. However, all these variants share common features: Libyco-Berber alphabetic symbols tend to be geometric, consisting of straight lines, circles and dots combined in different ways.' - sys: id: 13CDv9voc48oCmC0wqG4AA created_at: !ruby/object:DateTime 2015-11-25 17:44:51.935000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:37:41.169000000 Z content_type_id: image revision: 2 image: sys: id: 5rTkM78qGckOKu2q4AIUAI created_at: !ruby/object:DateTime 2015-11-25 17:40:51.188000000 Z updated_at: !ruby/object:DateTime 2015-12-08 08:28:43.019000000 Z title: '2013,2034.9338' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5rTkM78qGckOKu2q4AIUAI/1868823d4c9b78591d8fd94d156a8afc/NIGEAM0040013.jpg" caption: View of Libyan warrior holding a spear, surrounded by Libyco-Berber scripts. Ibel, Niger. 2013,2034.9338 ©TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3641907&partId=1&searchText=2013,2034.9338&page=1 - sys: id: 1gWJWaxXZYc4IiUyiC8IkQ created_at: !ruby/object:DateTime 2015-11-25 17:51:32.328000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:51:32.328000000 Z content_type_id: chapter revision: 1 title_internal: 'Libyco-Berber: thematic, chapter 5' body: 'The study of Libyco-Berber script faces some huge challenges. In addition to its aforementioned variability, it is necessary to differentiate the ancient languages spoken and written in North Africa during the Classical Antiquity for which a generic term of Libyco-Berber is used. Furthermore, Tifinagh script, the modern script of Tuareg people shares some symbols with the Libyco-Berber alphabet, but otherwise is a quite different language. Contemporary Tuareg cannot understand the old Libyco-Berber inscriptions although they recognize some symbols. Chronology represents another challenge: although the first dated inscription on a *stela* is from 138 BC, some pottery sherds with Libyco-Berber symbols could date from the 3rd century BC. For some researchers the oldest date (as old as the 7th century BC) is believed to correspond to an engraving located in the Moroccan High Atlas, although that theory is still under discussion. Finally, the characteristics of the scripts present some problems: they are usually short, repetitive and in many cases incomplete. Moreover, Libyco-Berber can be written in different directions (from right to left, bottom to top), complicating the identification, transcription and translation of the inscriptions. ' - sys: id: 6K1hjSQHrGSmMIwyi4aEci created_at: !ruby/object:DateTime 2015-11-25 17:46:00.776000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:39:20.711000000 Z content_type_id: image revision: 4 image: sys: id: 373GOE3JagQYoyY2gySyMy created_at: !ruby/object:DateTime 2015-11-25 17:41:18.933000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:41:18.933000000 Z title: '2013,2034.5878' description: url: "//images.ctfassets.net/xt8ne4gbbocd/373GOE3JagQYoyY2gySyMy/75c096cc7f233cedc2f75f58b0b41290/Oukaimeden_adapted.jpg" caption: Panel with elephants and human figures superimposed by two Libyco-Berber inscriptions, which some consider one of the oldest written in this alphabet, enhanced for a better view of the symbols. Oukaïmeden, Morocco. 2013,2034.5878 ©TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3613939&partId=1&searchText=2013,2034.5878&page=1 - sys: id: 3ik84OMvkQaEu6yOAeCMS6 created_at: !ruby/object:DateTime 2015-11-25 17:51:51.719000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:51:51.719000000 Z content_type_id: chapter revision: 1 title_internal: 'Libyco-Berber: thematic, chapter 6' body: Considering all these problems, what do we know about Libyco-Berber scripts? First of all, they normally used only consonants, although due to the influence of Punic (the language used in areas controlled or influenced by Carthage) and Latin, vowels were added in some alphabet variants. The translation of Libyco-Berber scripts is complicated, since the existing texts are very short and can only be translated through comparison with equivalent texts in Punic or Latin. Most of the translated scripts are very simple and correspond to personal and site names, or fixed formulations as “X son of Y”, characteristics of funerary epigraphy, or others such as, “It’s me, X”. Perhaps surprisingly, some of the translated inscriptions have an amorous meaning, with expressions as “I, X, love Y”. As the known Libyco-Berber corpus of inscriptions grows, it seems possible that more and more inscriptions will be translated, leading to a better understanding of the languages. - sys: id: 1t5dVxKpiIqeqy82O4McOI created_at: !ruby/object:DateTime 2015-11-25 17:46:35.246000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:43:47.775000000 Z content_type_id: image revision: 3 image: sys: id: 7x2yrpGfGEKaUQgyuiOYwk created_at: !ruby/object:DateTime 2015-11-25 17:41:38.056000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:41:38.056000000 Z title: '2013,2034.3203' description: url: "//images.ctfassets.net/xt8ne4gbbocd/7x2yrpGfGEKaUQgyuiOYwk/27f613c48b37dbb1114df7b733465787/LIBMES0180013.jpg" caption: Panel depicting cattle, giraffes and Libyco-Berber graffiti. In Galgiwen, Libya. 2013,2034.3203 ©TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3589647&partId=1&searchText=2013,2034.3203&page=1 - sys: id: 3Ju6IkGoneueE2gYQKaAQm created_at: !ruby/object:DateTime 2015-11-25 17:52:16.445000000 Z updated_at: !ruby/object:DateTime 2015-12-11 12:27:17.030000000 Z content_type_id: chapter revision: 2 title_internal: 'Libyco-Berber: thematic, chapter 7' body: Of course, the Libyco-Berber scripts evolved through time, although discussion is still going on about the chronologies and rhythms of this process. After the adoption and development of the alphabet, the Libyco-Berber reached a consideration of “official language” in the Numidian kingdom, which flourished in the north-western coast of Africa during the two latest centuries BC. The kingdom was highly influenced by Carthage and Rome, resulting in the existence of bilingual inscriptions that were the key to the translation of Libyco-Berber scripts. After Roman conquest, Libyco-Berber was progressively abandoned as a written language in the area, but inscriptions in the Sahara were still common until an unknown moment in the first millennium BC (the scripts sometimes receiving the name of Tifinagh). The Berber language, however, has been preserved and a new alphabet was developed in the 1960s to be used by Berber people. - sys: id: 1fPVVfXalmoKy2mUUCQQOw created_at: !ruby/object:DateTime 2015-11-25 17:47:18.568000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:44:36.059000000 Z content_type_id: image revision: 2 image: sys: id: 2GLzuqBeIMgoUW0wqeiiKY created_at: !ruby/object:DateTime 2015-11-25 17:41:59.073000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:41:59.073000000 Z title: '2013,2034.4468' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2GLzuqBeIMgoUW0wqeiiKY/0ec84dd4272a7227215c45d16f1451c5/ALGDJA0100009.jpg" caption: Raid scene on a camel caravan, with several interspersed Libyco-Berber inscriptions. Tassili plateau, Djanet, Algeria. 2013,2034.4468 ©TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3602846&partId=1&searchText=2013,2034.4468&page=1 - sys: id: 5GOzFzswmcs8qgiqQgcQ2q created_at: !ruby/object:DateTime 2015-11-25 17:52:52.167000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:52:52.167000000 Z content_type_id: chapter revision: 1 title_internal: 'Libyco-Berber: thematic, chapter 8' body: The many challenges that surround the study of Libyco-Berber scripts have led to a complex crossroads of terms, chronologies and theories which sometimes are contradictory and confusing. For the Rock Art Image Project, a decision had to be made to define the painted or engraved scripts in the collection and the chosen term was Libyco-Berber, as most of the images are associated with paintings of the Horse and Camel periods and thus considered to be up to 3,000 years old. Using the term Tifinagh could lead to misunderstandings with more modern scripts and the alphabet currently used by Berber peoples throughout North Africa. - sys: id: 6qjMP5OeukCMEiWWieE4O8 created_at: !ruby/object:DateTime 2015-11-25 17:47:52.571000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:46:54.999000000 Z content_type_id: image revision: 2 image: sys: id: FGpTfysHqEay4OMO66YSE created_at: !ruby/object:DateTime 2015-11-25 17:42:18.963000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:42:18.963000000 Z title: '2013,2034.2792' description: url: "//images.ctfassets.net/xt8ne4gbbocd/FGpTfysHqEay4OMO66YSE/c735c56a5dff7302beb58cec0e35bc85/LIBMES0040160.jpg" caption: Libyco-Berber inscription engraved near a cow. Wadi Mathendous, Libya. 2013,2034.2792 ©TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3584843&partId=1&searchText=2013,2034.2792&page=1 - sys: id: NeG74FoyYuOowaaaUYgQq created_at: !ruby/object:DateTime 2015-11-25 17:53:11.586000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:53:11.586000000 Z content_type_id: chapter revision: 1 title_internal: 'Libyco-Berber: thematic, chapter 9' body: Undoubtedly, the deciphering of forgotten languages captures the imagination and is one of the most exciting challenges in the study of ancient cultures. However, it is usually a difficult enterprise, as extraordinary finds which aid translation such as the Rosetta Stone are fairly exceptional and most of the time the transcription and translation of these languages is a long and difficult process in which the meaning of words and grammar rules is slowly unravelled. Although there are no shortcuts to this method, there are some initiatives that help to ease the task. One of them is making available catalogues of high quality images of inscriptions which can be studied and analysed by specialists. In that sense, the Libyco-Berber inscriptions present in the Rock Art Image Project catalogue can be truly helpful for all those interested in one of the most fascinating languages in the world; a language, which albeit modified has endured in different forms for hundreds of years. citations: - sys: id: 4r54ew5pNSwQ8ckQ8w8swY created_at: !ruby/object:DateTime 2015-11-25 17:48:24.656000000 Z updated_at: !ruby/object:DateTime 2015-12-11 12:28:59.132000000 Z content_type_id: citation revision: 2 citation_line: | <NAME>. 2012. Rock Art, Scripts and proto-scripts in Africa: the Libyco-berber example. In: Delmas, A. and Penn, P. (eds.), *Written Culture in a Colonial Context: Africa and the Americas 1500 – 1900*. Brill Academic Publishers, Boston, pp. 3-29. <NAME>. 2007. Origin and Development of the Libyco-Berber Script. Berber Studies 15. Rüdiger Köppe Verlag, Köln. [http://lbi-project.org/](http://lbi-project.org/) background_images: - sys: id: 4kXC2w9xCwAASweyCgwg2O created_at: !ruby/object:DateTime 2015-11-25 17:40:34.619000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:40:34.619000000 Z title: '2013,2034.4996' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4kXC2w9xCwAASweyCgwg2O/4d864b520d505029c7c8b90cd9e5fde2/ALGTOD0050035.jpg" - sys: id: 2GLzuqBeIMgoUW0wqeiiKY created_at: !ruby/object:DateTime 2015-11-25 17:41:59.073000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:41:59.073000000 Z title: '2013,2034.4468' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2GLzuqBeIMgoUW0wqeiiKY/0ec84dd4272a7227215c45d16f1451c5/ALGDJA0100009.jpg" ---<file_sep>/_coll_country/uganda.md --- contentful: sys: id: 68lvzyn1Reiwe04eaAqYa4 created_at: !ruby/object:DateTime 2015-11-26 18:45:48.318000000 Z updated_at: !ruby/object:DateTime 2018-05-17 16:57:15.328000000 Z content_type_id: country revision: 14 name: Uganda slug: uganda col_url: http://www.britishmuseum.org/research/collection_online/search.aspx?people=197356&place=27047 map_progress: true intro_progress: true image_carousel: - sys: id: 6LAhyXtnagaeiiYcyqAUS8 created_at: !ruby/object:DateTime 2015-12-11 15:54:00.944000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:47:44.145000000 Z title: '2013,2034.15198' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3690931&partId=1&searchText=UGAVIC0010001&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/6LAhyXtnagaeiiYcyqAUS8/06fee85996cb2e9625cbfd6b7a6a07dc/UGAVIC0010001_1.jpg" - sys: id: 1PIG4cOXQg4GYcssAoIcgE created_at: !ruby/object:DateTime 2015-11-30 14:16:31.945000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:48:49.387000000 Z title: '2013,2034.14850' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3673353&partId=1&searchText=UGATES0020029&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/1PIG4cOXQg4GYcssAoIcgE/128ac1905e76484c13aa53c4356475b9/UGATES0020029_jpeg.jpg" featured_site: sys: id: 3crZmFK8Vyy0MGMoEwEaMS created_at: !ruby/object:DateTime 2015-11-25 14:47:12.403000000 Z updated_at: !ruby/object:DateTime 2015-12-07 20:52:00.749000000 Z content_type_id: featured_site revision: 3 title: Nyero, Uganda slug: nyero chapters: - sys: id: 2qMVT4qlruk8WAAWEwaC6u created_at: !ruby/object:DateTime 2015-11-25 14:38:38.847000000 Z updated_at: !ruby/object:DateTime 2017-01-24 15:16:47.887000000 Z content_type_id: chapter revision: 3 title_internal: 'Uganda: featured site, chapter 1' body: |- First documented in 1913 (in the Teso Report&dagger;), the geometric paintings at Nyero are among the most important and well documented rock art sites in Uganda, and are on the Tentative list of UNESCO World Heritage sites&Dagger;. Nyero is located in eastern Uganda in the Kumi District, about 200 km from the capital city Kampala. It comprises six rock shelters in total, but initially only three were recorded and referred to as shrines by local communities, who had no knowledge of the origins of the paintings. The authorship of the paintings remains in some debate. Initially, the rock art was thought to be the work of San&#124;Bushmen of southern Africa. However, archaeological, genetic and ethnographic evidence has subsequently attributed the paintings to the ancestors of Batwa people, hunter-gatherers who are descendants of ancient aboriginal groups once spread across East and Central Africa and most probably the original inhabitants of this landscape. Today they live in small groups near the Rwanda/Uganda border. - sys: id: 37xiS8FWYwgqYYscQg24OW created_at: !ruby/object:DateTime 2015-11-25 14:28:33.065000000 Z updated_at: !ruby/object:DateTime 2017-01-24 15:18:23.508000000 Z content_type_id: image revision: 3 image: sys: id: 1UsysL5u3ioSim8YKyQ4mS created_at: !ruby/object:DateTime 2015-12-11 16:05:57.381000000 Z updated_at: !ruby/object:DateTime 2015-12-11 16:05:57.381000000 Z title: UGATES0010002 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1UsysL5u3ioSim8YKyQ4mS/56c1505f1a1d24e85ba055421b1c0383/UGATES0010002_1.jpg" caption: Site of Nyero 1. 2013,2034.14796 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3671587&partId=1&searchText=2013,2034.14796&page=1 - sys: id: 2At2H2doaAceQKO2gi0WyO created_at: !ruby/object:DateTime 2015-11-25 14:39:27.080000000 Z updated_at: !ruby/object:DateTime 2015-11-25 14:39:27.080000000 Z content_type_id: chapter revision: 1 title_internal: 'Uganda: featured site, chapter 2' body: |- More recent studies have proposed that the rock art was the work of settled human groups and not early hunter-gatherers. It has been proposed that rock shelters were used by semi-nomadic peoples devoted to animal herding, and used as reference points in the landscape. Generally positioned away from flat land, they may have served to direct herders of cattle and/or goats towards paths and water. The unknown identity of the rock artists makes dating problematic, but some of the paintings may be up to 12,000 years old. Notwithstanding the problems associated with attribution and chronology, many of the rock paintings in Uganda show serious damage due to long exposure to the elements. At Nyero 2, the paintings are partially covered with mineral salts, while at Nyero 5 the paintings have been destroyed or are obscured by rain wash-off. The physical condition of the paintings is testament to their antiquity. - sys: id: 1DnRQQLvIgWcYyWOeweAoC created_at: !ruby/object:DateTime 2015-11-25 14:29:09.297000000 Z updated_at: !ruby/object:DateTime 2017-01-24 15:19:01.643000000 Z content_type_id: image revision: 4 image: sys: id: 4TmZuqmyM8UukoEmU6kUcY created_at: !ruby/object:DateTime 2015-12-11 16:05:57.367000000 Z updated_at: !ruby/object:DateTime 2015-12-11 16:05:57.367000000 Z title: UGATES0020007 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/4TmZuqmyM8UukoEmU6kUcY/1fb5255968afbd1a3f022f8e8142a5ff/UGATES0020007_1.jpg" caption: Nyero 2 showing rock art obscured by mineral salts leaching out from the rock face. 2013,2034.14828 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3671630&partId=1&searchText=2013,2034.14828&page=1 - sys: id: 2QBfTBIQlG6muuGs2CyQMe created_at: !ruby/object:DateTime 2015-11-25 14:39:54.020000000 Z updated_at: !ruby/object:DateTime 2017-01-24 15:20:18.146000000 Z content_type_id: chapter revision: 3 title_internal: 'Uganda: featured site, chapter 3' body: | __Nyero Rock Art sites:__ __Nyero 1__ This is a small rock shelter on the outer edge of the outcrop and comprises six sets of concentric circles with a central image of a ‘floral motif’ and a so-called ‘acacia pod’ shape. The geometrics in this shelter are all painted in white. __Nyero 2__ This is the main shelter, the overhang of which is formed by an enormous boulder (estimated to weigh at least 20,000 tons) which has broken away; a vertical rock against the back wall measures 10m in height. The panel at Nyero 2 consists of more than forty images such as vertical divided sausage shapes, so-called ‘canoes‘, unidentified faint markings, ‘U’ shapes, lines and dots, with evidence of superimposition; but is dominated by concentric circles. A unique feature of the paintings are the so-called ‘canoes’ or parts of ‘canoes’, so-called because of their resemblance in form. The depictions are all painted in shades of red. - sys: id: i4OzTdyoO4MaaSWYEw44a created_at: !ruby/object:DateTime 2015-11-25 14:30:29.951000000 Z updated_at: !ruby/object:DateTime 2017-01-24 15:20:45.228000000 Z content_type_id: image revision: 3 image: sys: id: 55q7QQMYVacGSCOEqOMq2q created_at: !ruby/object:DateTime 2015-12-11 16:05:57.370000000 Z updated_at: !ruby/object:DateTime 2015-12-11 16:05:57.370000000 Z title: UGATES0020019 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/55q7QQMYVacGSCOEqOMq2q/cbe87e9b47e1b735a6ea4ed5709af86a/UGATES0020019_1.jpg" caption: Paintings at Nyero 2. 2013,2034.14840 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3671647&partId=1&searchText=2013,2034.14840&page=1 - sys: id: 2coobYQw4gccSA44SGY2og created_at: !ruby/object:DateTime 2015-11-25 14:31:19.584000000 Z updated_at: !ruby/object:DateTime 2017-01-24 15:21:14.609000000 Z content_type_id: image revision: 3 image: sys: id: 7yIW3zRgn6SEKuyWSW4ao0 created_at: !ruby/object:DateTime 2015-12-11 16:05:57.385000000 Z updated_at: !ruby/object:DateTime 2015-12-11 16:05:57.385000000 Z title: UGATES0020030 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/7yIW3zRgn6SEKuyWSW4ao0/abca8da930f88993859b431aa0487356/UGATES0020030_1.jpg" caption: Close up of concentric circles and large canoe shaped object design. 2013,2034.14851 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3671768&partId=1&searchText=2013,2034.14851&page=1 - sys: id: 3NJ4Oz0UY8Yiao0WKKYsKk created_at: !ruby/object:DateTime 2015-11-25 14:40:37.018000000 Z updated_at: !ruby/object:DateTime 2015-11-25 14:40:37.018000000 Z content_type_id: chapter revision: 1 title_internal: 'Uganda: featured site, chapter 4' body: | The paintings are protected from direct rain by the overhang and rocks to the front and sides protect the paintings from the sun, which is likely to have contributed to their preservation. Early users of the shelter placed ritual gifts on its south-eastern side; the tradition of using this space to place money either before or after receiving help from ancestral spirits is continued by the local community. As well as the rock art, a bone incised with three concentric circles and four parallel lines, and pieces of prepared ochre were excavated from this site in 1945. These are the only evidence of prehistoric portable art so far found in Uganda. __Nyero 3__ Located about eight minutes’ walk from Nyero 2, this shelter is formed by a large boulder perched on supporting rocks. Paintings consist of white concentric circles; the outer circles surrounded by double curved designs, between which are double lines divided into small compartments. - sys: id: 1TFcUtPntaamu6iAGw0Yu6 created_at: !ruby/object:DateTime 2015-11-25 14:36:03.085000000 Z updated_at: !ruby/object:DateTime 2017-01-24 15:21:39.949000000 Z content_type_id: image revision: 3 image: sys: id: qpeXjLAjUOK6GGOeE8iQK created_at: !ruby/object:DateTime 2015-12-11 16:05:57.362000000 Z updated_at: !ruby/object:DateTime 2015-12-11 16:05:57.362000000 Z title: UGATES0030001 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/qpeXjLAjUOK6GGOeE8iQK/d8caeb2c1a67f044f488183b926536e7/UGATES0030001_1.jpg" caption: White concentric circle at Nyero 3. 2013,2034.14888 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3673770&partId=1&searchText=2013,2034.14889&page=1 - sys: id: 4uHJ60KmQ88eK0eGI2eqqi created_at: !ruby/object:DateTime 2015-11-25 14:41:05.035000000 Z updated_at: !ruby/object:DateTime 2015-11-25 14:41:05.035000000 Z content_type_id: chapter revision: 1 title_internal: 'Uganda: featured site, chapter 5' body: | __Nyero 4__ This is a small shelter on the south-western side of the hill where there are a few traces of red finger-painted concentric circles, two conical shapes and lines. __Nyero 5__ Situated on the western side of the hill, this shelter has a red geometric motif composed of a combination of circular and linear shapes made with both a brush and a finger. However, the images are quite difficult to distinguish as they are damaged by natural water erosion. - sys: id: 1i0uRJ0CsIS6skI4CSeICy created_at: !ruby/object:DateTime 2015-11-25 14:36:38.229000000 Z updated_at: !ruby/object:DateTime 2017-01-24 15:22:17.715000000 Z content_type_id: image revision: 3 image: sys: id: 66GiQKzNokmUKWM6IKSOeC created_at: !ruby/object:DateTime 2015-12-11 16:05:57.384000000 Z updated_at: !ruby/object:DateTime 2015-12-11 16:05:57.384000000 Z title: UGATES0050011 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/66GiQKzNokmUKWM6IKSOeC/5a861c2c47d32c7a5a2271c4f824e0c0/UGATES0050011_1.jpg" caption: Nyero 5 showing paintings damaged by water erosion. 2013,2034.14954 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3673887&partId=1&searchText=2013,2034.14954&page=1 - sys: id: 6kXL90PRsciwo4kcwm4qs4 created_at: !ruby/object:DateTime 2015-11-25 14:41:27.841000000 Z updated_at: !ruby/object:DateTime 2015-11-25 14:41:27.841000000 Z content_type_id: chapter revision: 1 title_internal: 'Uganda: featured site, chapter 6' body: | __Nyero 6__ Situated on the top of the hill, this shelter has a good view of the landscape. This site features two red finger-painted outlines of small oval shapes and a slanting L-shape as well as an outlined cross with a small circle below. The painted surface is now subject to severe exfoliation as it is open to the rain and morning sun. The sites at Nyero are believed locally to have been sacred ancestral places where, in the past, people would have travelled long distances to make offerings of food, beer and money in times of drought, misfortune and for child birth. Nyero was also regarded as a magical place where rain ceremonies were held. Oral histories have recorded strong attachments to the site and individual and community prayers were held seasonally. The antiquity of the images and their association with long-forgotten peoples may serve to enhance Nyero as a special and sacred place for local communities. citations: - sys: id: 1JbeHTVApauCyUYOGKCa0W created_at: !ruby/object:DateTime 2015-11-25 14:37:22.101000000 Z updated_at: !ruby/object:DateTime 2015-11-25 14:44:11.347000000 Z content_type_id: citation revision: 4 citation_line: |+ <NAME>. 2010. *Surrogate Surfaces: A contextual interpretive approach to the rock art of Uganda*. Unpublished PhD Thesis. Johannesburg: University of Witwatersrand <NAME> and <NAME> (eds). 2014. *Uganda Rock Art Sites: A Vanishing Heritage of Lake Victoria Region*. Kampala: National Museum of Uganda &dagger; An annual report submitted by each region to the Governor of Uganda during British colonial rule. &Dagger; A Tentative List is an inventory of those properties considered to be of cultural and/or natural heritage of outstanding universal value and therefore suitable for inscription on the World Heritage List. background_images: - sys: id: 51UNpKVSAEu6kkScs6uoOS created_at: !ruby/object:DateTime 2015-11-25 14:26:21.477000000 Z updated_at: !ruby/object:DateTime 2015-11-25 14:26:21.477000000 Z title: '2013,2034.14840' description: url: "//images.ctfassets.net/xt8ne4gbbocd/51UNpKVSAEu6kkScs6uoOS/21f12a22f47abbc0a67a1552a0fcf045/UGATES0020019.jpg" - sys: id: gVjIO1sqY06wAO8oIewkM created_at: !ruby/object:DateTime 2015-11-25 14:27:30.672000000 Z updated_at: !ruby/object:DateTime 2015-11-25 14:27:30.672000000 Z title: '2013,2034.14954' description: url: "//images.ctfassets.net/xt8ne4gbbocd/gVjIO1sqY06wAO8oIewkM/304d628709a396506a486f96c78f6fa0/UGATES0050011.jpg" key_facts: sys: id: APkeqYuyooE8eUAEgSscc created_at: !ruby/object:DateTime 2015-11-27 10:55:47.577000000 Z updated_at: !ruby/object:DateTime 2015-11-27 15:26:07.478000000 Z content_type_id: country_key_facts revision: 2 title_internal: 'Uganda: key facts' image_count: 863 images date_range: c.12,000 to 1,000 years ago. main_areas: Concentrated in the east and south east of the country in and around Lake Victoria and also in north-eastern Uganda. techniques: Mostly painted in red and white pigment, with some engravings. main_themes: Geometric designs in red and white pigment follow a basic and recurring repertoire of shapes including circular, rectangular, elongated ovals (or sausage-shaped), dots and lines. famous_for: Concentric circles with emanating rays are a unique feature of Ugandan rock art. thematic_articles: - sys: id: 2ULickNOv688OaGigYCWYm created_at: !ruby/object:DateTime 2018-05-09 15:26:39.131000000 Z updated_at: !ruby/object:DateTime 2018-05-09 15:28:31.662000000 Z content_type_id: thematic revision: 2 title: Landscapes of Rock Art slug: landscapes-of-rock-art lead_image: sys: id: 62Htpy9mk8Gw28EuUE6SiG created_at: !ruby/object:DateTime 2015-11-30 16:58:24.956000000 Z updated_at: !ruby/object:DateTime 2015-11-30 16:58:24.956000000 Z title: SOADRB0050042_1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/62Htpy9mk8Gw28EuUE6SiG/9cd9572ea1c079f4814104f40045cfb6/SOADRB0050042.jpg" chapters: - sys: id: Ga9XxWBfqwke88qwUKGc2 - sys: id: 5NCw7svaw0IoWWK2uuYEQG - sys: id: 7ng9hfsvLi2A0eWU6A0gWe - sys: id: 4ptu3L494cEYqk6KaY40o4 - sys: id: 5C3yAo4w24egO2O46UCCQg - sys: id: 5FmuBPI2k0o6aCs8immMWQ - sys: id: 6cU5WF1xaEUIiEEkyoWaoq - sys: id: 1YZyNsFTHWIoYegcigYaik - sys: id: 6fhRJ1NiO4wSwSmqmSGEQA - sys: id: 6EhIOeplUA6ouw2kiOcmWe - sys: id: 2g0O5GIiaESIIGC2OOMeuC - sys: id: 4Zj7sd5KJW4Eq2i4aSmQSS - sys: id: 5I9qkMsO5iqI0s6wqQkisk - sys: id: 6WsItqVm8wawokCiCgE4Gu - sys: id: 1631tf7fv4QUwei0IIEk6I - sys: id: 6ycsEOIb0AgkqoQ4MUOMQi - sys: id: 2aa2jzRtPqwK8egGek6G6 - sys: id: 47L9Y10YHmWY04QWCmI4qe - sys: id: 175X82dwJgqGAqkqCu4CkQ - sys: id: 5CGHVFKSUEA0oqY0cS2Cgo - sys: id: 60mUuKWzEkUMUeg4MEUO68 - sys: id: 5AvLn9pvKoeYW2OKqwkUgQ citations: - sys: id: 5z9VWU8t2MeaiAeQWa0Ake background_images: - sys: id: 1yhBeyGEMYkuay2osswcyg created_at: !ruby/object:DateTime 2018-05-09 15:16:49.135000000 Z updated_at: !ruby/object:DateTime 2018-05-09 15:16:49.135000000 Z title: SOANTC0030004 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1yhBeyGEMYkuay2osswcyg/7cab20823cbc01ae24ae6456d6518dbd/SOANTC0030004.jpg" - sys: id: 1rRAJpaj6UMCs6qMKsGm8K created_at: !ruby/object:DateTime 2018-05-09 15:14:41.480000000 Z updated_at: !ruby/object:DateTime 2018-05-09 15:14:41.480000000 Z title: SOANTC0050054 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1rRAJpaj6UMCs6qMKsGm8K/f92d2174d4c5109237ab00379c2088b7/SOANTC0050054.jpg" - sys: id: 6h9anIEQRGmu8ASywMeqwc created_at: !ruby/object:DateTime 2015-11-25 17:07:20.920000000 Z updated_at: !ruby/object:DateTime 2015-12-07 20:49:54.244000000 Z content_type_id: thematic revision: 4 title: Geometric motifs and cattle brands slug: geometric-motifs lead_image: sys: id: 5yD7fOuAdU4cemkewCqCMO created_at: !ruby/object:DateTime 2015-11-25 16:56:44.778000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:56:44.778000000 Z title: '2013,2034.12976' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5yD7fOuAdU4cemkewCqCMO/4d203afb0318bee69decb23327864c79/2013_2034.12976.jpg" chapters: - sys: id: 5plObOxqdq6MuC0k4YkCQ8 created_at: !ruby/object:DateTime 2015-11-25 17:02:35.234000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:05:34.964000000 Z content_type_id: chapter revision: 3 title_internal: 'Geometric motifs: thematic, chapter 1' body: |- The rock art of eastern Africa is characterised by a wide range of non-figurative images, broadly defined as geometric. Occurring in a number of different patterns or designs, they are thought to have been in existence in this region for thousands of years, although often it is difficult to attribute the art to particular cultural groups. Geometric rock art is difficult to interpret, and designs have been variously associated with sympathetic magic, symbols of climate or fertility and altered states of consciousness (Coulson and Campbell, 2010:220). However, in some cases the motifs painted or engraved on the rock face resemble the same designs used for branding livestock and are intimately related to people’s lives and world views in this region. First observed in Kenya in the 1970s with the work of Gramly (1975) at <NAME> and Lynch and Robbins (1977) at Namoratung’a, some geometric motifs seen in the rock art of the region were observed to have had their counterparts on the hides of cattle of local communities. Although cattle branding is known to be practised by several Kenyan groups, Gramly concluded that “drawing cattle brands on the walls of rock shelters appears to be confined to the regions formerly inhabited by the Maa-speaking pastoralists or presently occupied by them”&dagger;(Gramly, 1977:117). - sys: id: 71cjHu2xrOC8O6IwSmMSS2 created_at: !ruby/object:DateTime 2015-11-25 16:57:39.559000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:06:07.592000000 Z content_type_id: image revision: 2 image: sys: id: 5yD7fOuAdU4cemkewCqCMO created_at: !ruby/object:DateTime 2015-11-25 16:56:44.778000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:56:44.778000000 Z title: '2013,2034.12976' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5yD7fOuAdU4cemkewCqCMO/4d203afb0318bee69decb23327864c79/2013_2034.12976.jpg" caption: White symbolic designs possibly representing Maa clans and livestock brands, Laikipia, Kenya. 2013,2034.12976 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3693276&partId=1&searchText=2013,2034.12976&page=1 - sys: id: 36QhSWVHKgOeMQmSMcGeWs created_at: !ruby/object:DateTime 2015-11-25 17:03:05.920000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:03:05.920000000 Z content_type_id: chapter revision: 1 title: title_internal: 'Geometric motifs: thematic, chapter 2' body: In the case of Lukenya Hill, the rock shelters on whose walls these geometric symbols occur are associated with meat-feasting ceremonies. Meat-feasting shelters exist from northern Tanzania through Kenya to Lake Turkana, and are places where Maa-speaking initiated men, who are not permitted to eat meat in their homes, gather to kill and feast on animals, predominantly cattle. During or after feasting, symbols of the animals that had been eaten were painted on the shelter ceiling in white or less often red. Maa speakers brand their cattle and camels with symbols that signify the lineage of their owners, but may also indicate if an animal has been treated for a particular disease. Different symbols may be used for male and female animals. - sys: id: 4t76LZy5zaSMGM4cUAsYOq created_at: !ruby/object:DateTime 2015-11-25 16:58:35.447000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:07:35.181000000 Z content_type_id: image revision: 2 image: sys: id: 1lBqQePHxK2Iw8wW8S8Ygw created_at: !ruby/object:DateTime 2015-11-25 16:56:44.764000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:56:44.764000000 Z title: '2013,2034.12846' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1lBqQePHxK2Iw8wW8S8Ygw/68fffb37b845614214e96ce78879c0b0/2013_2034.12846.jpg" caption: View of the long rock shelter below the waterfall showing white abstract Maasai paintings made probably quite recently during meat feasting ceremonies, Enkinyoi, Kenya. 2013,2034.12846 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3694558&partId=1&searchText=2013,2034.12846&page=1 - sys: id: 3HGWtlhoS424kQCMo6soOe created_at: !ruby/object:DateTime 2015-11-25 17:03:28.158000000 Z updated_at: !ruby/object:DateTime 2016-05-19 07:35:38.155000000 Z content_type_id: chapter revision: 2 title_internal: 'Geometric motifs: thematic, chapter 3' body: The sites of Namoratung’a near Lake Turkana in northern Kenya showed a similar visible relationship. The southernmost site is well known for its 167 megalithic stones marking male burials on which are engraved hundreds of geometric motifs. Some of these motifs bear a striking resemblance to the brand marks that the Turkana mark on their cattle, camels, donkeys and other livestock in the area, although local people claim no authorship for the funerary engravings (Russell, 2013:4). - sys: id: kgoyTkeS0oQIoaOaaWwwm created_at: !ruby/object:DateTime 2015-11-25 16:59:05.484000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:08:12.169000000 Z content_type_id: image revision: 2 image: sys: id: 19lqDiCw7UOomiMmYagQmq created_at: !ruby/object:DateTime 2015-11-25 16:56:44.756000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:56:44.756000000 Z title: '2013,2034.13006' description: url: "//images.ctfassets.net/xt8ne4gbbocd/19lqDiCw7UOomiMmYagQmq/6f54d106aaec53ed9a055dc7bf3ac014/2013_2034.13006.jpg" caption: Ndorobo man with bow and quiver of arrows kneels at a rock shelter adorned with white symbolic paintings suggesting meat-feasting rituals. Laikipia, Kenya. 2013,2034.13006 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3700172&partId=1&searchText=2013,2034.13006&page=1 - sys: id: 2JZ8EjHqi4U8kWae8oEOEw created_at: !ruby/object:DateTime 2015-11-25 17:03:56.190000000 Z updated_at: !ruby/object:DateTime 2016-05-19 07:35:15.319000000 Z content_type_id: chapter revision: 2 title_internal: 'Geometric motifs: thematic, chapter 4' body: Recent research (Russell, 2013) has shown that at Namoratung’a the branding of animals signifies a sense of belonging rather than a mark of ownership as we understand it in a modern farming context; all livestock, cattle, camel, goats, sheep and donkeys are branded according to species and sex (Russell, 2013:7). Ethnographic accounts document that clan membership can only be determined by observing someone with their livestock (Russell, 2013:9). The symbol itself is not as important as the act of placing it on the animal’s skin, and local people have confirmed that they never mark rock with brand marks. Thus, the geometric motifs on the grave markers may have been borrowed by local Turkana to serve as identity markers, but in a different context. In the Horn of Africa, some geometric rock art is located in the open landscape and on graves. It has been suggested that these too are brand or clan marks, possibly made by camel keeping pastoralists to mark achievement, territory or ownership (Russell, 2013:18). Some nomadic pastoralists, further afield, such as the Tuareg, place their clan marks along the routes they travel, carved onto salt blocks, trees and wells (Mohamed, 1990; Landais, 2001). - sys: id: 3sW37nPBleC8WSwA8SEEQM created_at: !ruby/object:DateTime 2015-11-25 16:59:47.649000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:59:47.649000000 Z content_type_id: image revision: 1 image: sys: id: 5yUlpG85GMuW2IiMeYCgyy created_at: !ruby/object:DateTime 2015-11-25 16:56:44.766000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:56:44.766000000 Z title: '2013,2034.13451' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5yUlpG85GMuW2IiMeYCgyy/a234f96f9931ec3fdddcf1ab54a33cd9/2013_2034.13451.jpg" caption: Borana cattle brands. Namoratung’a, Kenya. 2013,2034.13451. © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3660359&partId=1&searchText=2013,2034.13451&page=1 - sys: id: 6zBkbWkTaEoMAugoiuAwuK created_at: !ruby/object:DateTime 2015-11-25 17:04:38.446000000 Z updated_at: !ruby/object:DateTime 2016-05-19 07:34:17.646000000 Z content_type_id: chapter revision: 3 title_internal: 'Geometric motifs: thematic, chapter 5' body: "However, not all pastoralist geometric motifs can be associated with meat-feasting or livestock branding; they may have wider symbolism or be symbolic of something else (Russell, 2013:17). For example, informants from the Samburu people reported that while some of the painted motifs found at Samburu meat-feasting shelters were of cattle brands, others represented female headdresses or were made to mark an initiation, and in some Masai shelters there are also clear representations of warriors’ shields. In Uganda, a ceremonial rock in Karamoja, shows a dung painting consisting of large circles bisected by a cross which is said to represent cattle enclosures (Robbins, 1972). Geometric symbols, painted in fat and red ochre, on large phallic-shaped fertility stones on the Mesakin and Korongo Hills in south Sudan indicate the sex of the child to whom prayers are offered (Bell, 1936). A circle bisected by a line or circles bisected by two crosses represent boys. Girls are represented by a cross (drawn diagonally) or a slanting line (like a forward slash)(Russell, 2013: 17).\n\nAlthough pastoralist geometric motifs are widespread in the rock art of eastern Africa, attempting to find the meaning behind geometric designs is problematic. The examples discussed here demonstrate that motifs can have multiple authors, even in the same location, and that identical symbols can be the products of very different behaviours. \n" citations: - sys: id: 2oNK384LbeCqEuSIWWSGwc created_at: !ruby/object:DateTime 2015-11-25 17:01:10.748000000 Z updated_at: !ruby/object:DateTime 2016-05-19 07:33:26.748000000 Z content_type_id: citation revision: 3 citation_line: |- <NAME>. 1936. ‘Nuba fertility stones’, in *Sudan Notes and Records* 19(2), pp.313–314. Gramly R 1975. ‘Meat-feasting sites and cattle brands: Patterns of rock-shelter utilization in East Africa’ in *Azania*, 10, pp.107–121. <NAME>. 2001. ‘The marking of livestock in traditional pastoral societies’, *Scientific and Technical Review of the Office International des Epizooties* (Paris), 20 (2), pp.463–479. <NAME>. and <NAME>. 1977. ‘Animal brands and the interpretation of rock art in East Africa’ in *Current Anthropology *18, pp.538–539. Robbins LH (1972) Archaeology in the Turkana district, Kenya. Science 176(4033): 359–366 <NAME>. 2013. ‘Through the skin: exploring pastoralist marks and their meanings to understand parts of East African rock art’, in *Journal of Social Archaeology* 13:1, pp.3-30 &dagger; The term Maa relates to a group of closely related Eastern Nilotic languages, which historically dominated the east African hinterland; and today is spoken by around a million people. background_images: - sys: id: 1TDQd4TutiKwIAE8mOkYEU created_at: !ruby/object:DateTime 2015-12-07 19:16:42.825000000 Z updated_at: !ruby/object:DateTime 2015-12-07 19:16:42.825000000 Z title: KENLOK0030053 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1TDQd4TutiKwIAE8mOkYEU/718ff84615930ddafb1f1fdc67b5e479/KENLOK0030053.JPG" - sys: id: 2SCvEkDjAcIewkiu6iSGC4 created_at: !ruby/object:DateTime 2015-12-07 19:16:42.845000000 Z updated_at: !ruby/object:DateTime 2015-12-07 19:16:42.845000000 Z title: KENKAJ0030008 description: url: "//images.ctfassets.net/xt8ne4gbbocd/2SCvEkDjAcIewkiu6iSGC4/b2e2e928e5d9a6a25aca5c99058dfd76/KENKAJ0030008.jpg" country_introduction: sys: id: 3DbhHAYYD6icYiuK62SY2w created_at: !ruby/object:DateTime 2015-11-26 18:47:24.211000000 Z updated_at: !ruby/object:DateTime 2015-12-07 13:43:10.697000000 Z content_type_id: country_information revision: 3 title: 'Uganda: country introduction' chapters: - sys: id: 5yJzv38jjG6o0u4Q4ISYeM created_at: !ruby/object:DateTime 2015-11-26 18:35:01.243000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:35:01.243000000 Z content_type_id: chapter revision: 1 title: Introduction title_internal: 'Uganda: country, chapter 1' body: Rock art in Uganda is mostly concentrated in the eastern part of the country, but more broadly sits within a regional belt of geometric rock art spanning East and Central Africa. It is mainly geometric in nature and includes both paintings (red and white being the most common pigment) and engravings; it comprises a basic and recurring repertoire of shapes including circular, rectangular, sausage, dot and lines. Concentric circles with rays emanating from them are a unique feature of Ugandan rock art. - sys: id: 4TrHjE4Umk8eoscoQUaMWC created_at: !ruby/object:DateTime 2015-11-27 14:21:57.842000000 Z updated_at: !ruby/object:DateTime 2017-01-24 15:05:24.474000000 Z content_type_id: image revision: 3 image: sys: id: 40ezg2Ddosc4yYM0Myes8U created_at: !ruby/object:DateTime 2015-12-11 15:53:35.421000000 Z updated_at: !ruby/object:DateTime 2015-12-11 15:53:35.421000000 Z title: UGANGO0020031 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/40ezg2Ddosc4yYM0Myes8U/7d118bce5cf73e7a0fd8b7953a604bcd/UGANGO0020031_1.jpg" caption: Circular motifs.Ngora, Eastern Province, Uganda. 2013,2034.14768 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3691105&partId=1&searchText=2013%2c2034.14768&page=1 - sys: id: 4fHCnfKB5Ymqg4gigEIm0g created_at: !ruby/object:DateTime 2015-11-26 18:35:36.716000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:35:36.716000000 Z content_type_id: chapter revision: 1 title_internal: 'Uganda: country, chapter 2' body: One of the most well-known sites is at Nyero, a large granite outcrop situated between Mbale and Soroti in the east of the country. Nyero consists of a cluster of six sites and is on the Tentative List of UNESCO World Heritage sites&dagger;. All of the paintings found here are geometric in design and have been attributed to the ancestral Batwa, and dated to before 1250 AD. - sys: id: 5BePUMaSPKsSiUweSq2yyG created_at: !ruby/object:DateTime 2015-11-26 18:36:04.177000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:36:04.177000000 Z content_type_id: chapter revision: 1 title: Geography title_internal: 'Uganda: country, chapter 3' body: Uganda is located in East Africa, comprises an area of 236,040 km² and shares borders with Kenya to the east, South Sudan in the north, Democratic Republic of Congo in the west, and Rwanda and Tanzania in the south. It sits in the heart of the Great Lakes region, flanked by Lake Edward, Lake Albert and Lake Victoria, the latter being the second largest inland freshwater lake in the world, containing numerous islands. While much of its border is lakeshore, the country is landlocked. Predominantly plateau, Uganda is cradled by mountains with Margherita peak (5,199m) on Mount Stanley the third highest point in Africa. - sys: id: 3IwOIf4phe6KkoEu24goAw created_at: !ruby/object:DateTime 2015-11-27 14:22:43.586000000 Z updated_at: !ruby/object:DateTime 2017-01-24 15:07:19.503000000 Z content_type_id: image revision: 3 image: sys: id: 6LAhyXtnagaeiiYcyqAUS8 created_at: !ruby/object:DateTime 2015-12-11 15:54:00.944000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:47:44.145000000 Z title: '2013,2034.15198' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3690931&partId=1&searchText=UGAVIC0010001&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/6LAhyXtnagaeiiYcyqAUS8/06fee85996cb2e9625cbfd6b7a6a07dc/UGAVIC0010001_1.jpg" caption: Large boulder containing painted rock art overlooking Lake Victoria. 2013,2034.15198 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3690931&partId=1&searchText=2013%2c2034.15198&page=1 - sys: id: xTETlLO8WkqiiuYO0cgym created_at: !ruby/object:DateTime 2015-11-26 18:36:58.092000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:36:58.092000000 Z content_type_id: chapter revision: 1 title: Research History title_internal: 'Uganda: country, chapter 4' body: |- The first documentation of rock art in Uganda occurred in 1913 (Teso Report) at Nyero, a painted rock shelter of the Later Iron Age period. After its initial recording the site was subsequently cited in a 1945 excavation report (Harwich, 1961) and meticulously noted by <NAME> during the 1950s. Only a small number of studies of Ugandan rock art rock art have been published (Wayland 1938; Lawrance 1953; Posnansky 1961; Morton 1967; Chaplin 1974), with early analyses being predominantly descriptive and highly speculative. The first major publications on Ugandan rock art emerged in the 1960s (Posnansky 1961; Morton 1967; Chaplin 1974) with rock art researchers proposing that the geometric and non-representational depictions served a documentary purpose of identifying cultural groups such as hunter-gatherers, cultivators or pastoralists. During this decade researchers attempted to place the rock art in a chronological framework, tying it to broader archaeological sequences. Political instability greatly impeded research during the 1970s and 1980s, although Chaplin’s thesis and in-depth survey on prehistoric rock art of Lake Victoria was published posthumously in 1974. - sys: id: 3z8AAdZC2sEWOOqc4kcESq created_at: !ruby/object:DateTime 2015-11-27 14:24:00.757000000 Z updated_at: !ruby/object:DateTime 2017-01-24 15:09:06.452000000 Z content_type_id: image revision: 3 image: sys: id: 2FHA4qasM0YkYeY20OK20e created_at: !ruby/object:DateTime 2015-12-11 15:54:11.681000000 Z updated_at: !ruby/object:DateTime 2015-12-11 15:54:11.681000000 Z title: UGAVIC0060056 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/2FHA4qasM0YkYeY20OK20e/8dc76eadeb33620beaeedbba6b04399b/UGAVIC0060056_1.jpg" caption: Painted ceiling of a rock shelter attributed to the BaTwa. Lolui Island, Eastern Province, Uganda. 2013,2034.15306 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3691242&partId=1&searchText=2013%2c2034.15306&page=1 - sys: id: 17HHIh3cvwkm8eMqIaYi4e created_at: !ruby/object:DateTime 2015-11-26 18:37:14.262000000 Z updated_at: !ruby/object:DateTime 2015-12-11 12:43:31.000000000 Z content_type_id: chapter revision: 2 title_internal: 'Uganda: country, chapter 5' body: Much of the interpretation of the rock art in the region was based on the assumption that the art was attributable to the so-called “Bushmen” of southern Africa, using these explanations to understand the rock art of Uganda. C<NAME>’s (2010) recent doctoral thesis on rock art in Uganda has opened up these debates, “tackling the more slippery issues of attribution, interpretation and understanding of rock art” (Namono, 2010:40). - sys: id: 49Hty9jIlWSeoOi2uckwwg created_at: !ruby/object:DateTime 2015-11-26 18:37:41.691000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:37:41.691000000 Z content_type_id: chapter revision: 1 title: Chronologies/Styles title_internal: 'Uganda: country, chapter 6' body: "__Paintings__\n\nThe geometric rock art that predominates in Uganda is attributed to the Batwa cultural group. Modern Batwa are descendants of ancient aboriginal forest-dwelling hunter-gatherer groups based in the Great Lakes region of central Africa. Their rock art has been divided into two traditions: firstly, the red animal tradition that comprises finely painted representations of animals in red pigment painted in a figurative style. These are all in the far north-eastern corner of Uganda. Antelope are the most common animals depicted, but this imagery also includes elephant, rhino, lion, leopard, giraffe, hyena, warthog, wild pig, ostrich and buffalo. \n" - sys: id: rehKUDcDviQGqmiwAikco created_at: !ruby/object:DateTime 2015-11-27 14:24:31.625000000 Z updated_at: !ruby/object:DateTime 2017-01-24 15:09:53.569000000 Z content_type_id: image revision: 3 image: sys: id: 6Rp8Jyx6Tu8CagewSGkKaG created_at: !ruby/object:DateTime 2015-12-11 15:53:35.413000000 Z updated_at: !ruby/object:DateTime 2015-12-11 15:53:35.413000000 Z title: UGAMOR0010021 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6Rp8Jyx6Tu8CagewSGkKaG/8425bc465938ddae5cfed284f96a6e6f/UGAMOR0010021_1.jpg" caption: Painted red cattle and figures holding bows. Kanamugeot, Northern Province, Uganda, 2013,2034.14633 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3690004&partId=1&searchText=2013%2c2034.14633&page=1 - sys: id: 2KG09KRWisSWmogUWA4sGQ created_at: !ruby/object:DateTime 2015-11-26 18:38:08.326000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:38:08.326000000 Z content_type_id: chapter revision: 1 title_internal: 'Uganda: country, chapter 7' body: "While some of the animals are remarkably naturalistic in their portrayal, the majority are highly distorted and difficult to identify to species level, and are associated with rows of dots superimposing the animal forms. The second tradition, the red geometrics include images painted in red and applied with the fingertip; the most common motifs comprise concentric circles, concentric circles with radiating lines, dots, U-shapes, dotted, straight, horizontal and vertical lines and interlinked lines. Other motifs and shapes are described as ‘acacia pod’, ‘canoes’, and ‘dumbbell’; a testament to the problems researchers face when attempting to use descriptive terms in identifying complex designs. \n\n__Engravings__\n\nGeometric engravings occur in and around Lake Victoria and also in north-eastern Uganda. Motifs comprise concentric circles, grids, concentric circles with internal radiating spokes, lines and dots. Proportionally, there are fewer engravings than paintings but as Namono (2010) has observed this may reflect a research bias rather than an actual disparity.\n" - sys: id: 6re1Gh7nxe4YK4MmumWu4m created_at: !ruby/object:DateTime 2015-11-27 14:25:05.494000000 Z updated_at: !ruby/object:DateTime 2017-01-24 15:10:31.191000000 Z content_type_id: image revision: 3 image: sys: id: 4TE2BAQkM8S0640ECkYayA created_at: !ruby/object:DateTime 2015-12-11 15:53:43.648000000 Z updated_at: !ruby/object:DateTime 2015-12-11 15:53:43.648000000 Z title: UGANAS0002 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/4TE2BAQkM8S0640ECkYayA/3a5a54bd23c2ecaa637d19e132e40263/UGANAS0002_1.jpg" caption: Engraved rock with concentric circle motif. Kampala, Uganda. 2013,2034.14710 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3690111&partId=1&searchText=2013%2c2034.14710&page=1 - sys: id: 6qgdyPfErKwIISIUuWEsMU created_at: !ruby/object:DateTime 2015-11-26 18:38:44.670000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:38:44.670000000 Z content_type_id: chapter revision: 1 title_internal: 'Uganda: country, chapter 8' body: Another common type of engraving is small cupules aligned in rows, found predominantly on hilltops or large rock slabs near water sources. None have been found on vertical rock faces or in rock shelters. They are known locally as *omweso* (a traditional board game of Uganda) as there are similarities between these and the traditional *mancala* game, originally introduced to Africa with the Indian Ocean trade. - sys: id: 2fzT5T0btesSgMyuyUqAu0 created_at: !ruby/object:DateTime 2015-11-27 14:25:46.047000000 Z updated_at: !ruby/object:DateTime 2017-01-24 15:11:49.658000000 Z content_type_id: image revision: 3 image: sys: id: 2kLCq0ponGEOemeycuauI2 created_at: !ruby/object:DateTime 2015-12-11 15:53:48.341000000 Z updated_at: !ruby/object:DateTime 2015-12-11 15:53:48.341000000 Z title: UGAMUK0050001 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/2kLCq0ponGEOemeycuauI2/55631bb48e53718bd799a7e8799f7439/UGAMUK0050001_1.jpg" caption: Large rock with grid of small carved cupules. Kimera, Central Province, Uganda. 2013,2034.14676 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3690085&partId=1&searchText=2013%2c2034.14676&page=1 - sys: id: 6waesLr6j6I24eySaQO2Q6 created_at: !ruby/object:DateTime 2015-11-26 18:39:35.319000000 Z updated_at: !ruby/object:DateTime 2015-12-11 12:44:11.747000000 Z content_type_id: chapter revision: 2 title: Dating title_internal: 'Uganda: country, chapter 9' body: |- Attempts to understand the chronology of Ugandan rock in the 1960s were based on sequences focusing on pigments used in paintings. Lawrance proposed that yellow paintings were the oldest; followed by orange, red, purple, red and white; white and dirty white were the latest in the sequence. It is highly problematic developing sequences based on pigments because of the ways in which they chemically react with particular surfaces, other pigments and the natural elements, which can compromise the integrity of the pigment. However, there appears to be a consistency (across East and Central Africa) that suggests red and white geometric paintings are the oldest and have been in existence for millennia. Initially thought to be the work of San Bushmen of southern Africa, archaeological, genetic and ethnographic evidence has subsequently attributed the paintings to the Batwa people, a cultural group who are today found in small groups near the Rwanda/Uganda border. If it is accepted that the geometric imagery was made by these hunter-gatherers then the rock art of Uganda probably dates from between 12,000 to 1,000 years ago. - sys: id: 5eNs55lpIWoiCM2W6iwGkM created_at: !ruby/object:DateTime 2015-11-27 14:26:33.741000000 Z updated_at: !ruby/object:DateTime 2017-01-24 15:12:35.188000000 Z content_type_id: image revision: 3 image: sys: id: 7awPQKadFK2k6mMegimuIE created_at: !ruby/object:DateTime 2015-12-11 15:53:43.661000000 Z updated_at: !ruby/object:DateTime 2015-12-11 15:53:43.661000000 Z title: UGATES0030003 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/7awPQKadFK2k6mMegimuIE/0b3a8c2a03bcc34f8821f30bf0cf1367/UGATES0030003_1.jpg" caption: Complex white motif comprising six concentric circles surrounded by curvilinear tentacles. Nyero, Eastern Province, Uganda. 2013,2034.14892 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3673779&partId=1&searchText=2013%2c2034.14892&page=1 - sys: id: UOkpq4WM6qoYMUky2Ws4e created_at: !ruby/object:DateTime 2015-11-26 18:39:56.176000000 Z updated_at: !ruby/object:DateTime 2015-12-11 12:44:55.317000000 Z content_type_id: chapter revision: 3 title_internal: 'Uganda: country, chapter 10' body: However, more recent studies have proposed that these were the work of settled human groups and not early hunter-gatherers. Radiocarbon dating at Nyero (and another site at Kakoro) has dated the paintings to between 5,000 and 1,600 years ago. It has been proposed that rock shelters were used by semi-nomadic peoples engaged in animal herding, which they used as reference points in the landscape. Generally positioned away from flat land, they may have served to direct herders of cattle and/or goats towards paths and water. - sys: id: 3HOpYjRGGciiYMS24EcSqO created_at: !ruby/object:DateTime 2015-11-26 18:40:20.558000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:40:20.558000000 Z content_type_id: chapter revision: 1 title: Interpretation title_internal: 'Uganda: country, chapter 11' body: A recent comprehensive study (Namono, 2010) of the potential meaning of geometric art in Uganda looked at the ways in which the geometric shapes in the rock art can be associated with the ethnographies of hunter-gatherers of the region. The approach proposed that the symbolism of geometric rock art derives from a gendered forest worldview. The forest is pivotal to hunter/gatherer cosmology in this region, whereby it plays a central role in cultural production and reproduction over time and is regarded as both male and female. The forest is not only a source of subsistence and well-being but informs their identity and the rock art reflects these complex concepts. - sys: id: 3qOC0kMyiQQOKgc2k2aICQ created_at: !ruby/object:DateTime 2015-11-27 14:27:14.840000000 Z updated_at: !ruby/object:DateTime 2017-01-24 15:13:32.803000000 Z content_type_id: image revision: 3 image: sys: id: 5gAcaHufAso60GKYiKsei2 created_at: !ruby/object:DateTime 2015-12-11 15:53:48.306000000 Z updated_at: !ruby/object:DateTime 2015-12-11 15:53:48.306000000 Z title: UGANGO0010001 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/5gAcaHufAso60GKYiKsei2/b93cc028065d4f5c5dbe953558d1a4bb/UGANGO0010001_1.jpg" caption: View looking towards the forested location of a painted rock art site. Ngora, Eastern Province, Uganda. 2013,2034.14711 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3690354&partId=1&searchText=2013,2034.14711&page=1 - sys: id: 4r8ruNjScUCigsS6kWe6Yg created_at: !ruby/object:DateTime 2015-11-26 18:40:41.970000000 Z updated_at: !ruby/object:DateTime 2015-12-11 12:45:09.119000000 Z content_type_id: chapter revision: 2 title_internal: 'Uganda: country, chapter 12' body: It is difficult to determine when rock art sites were last used, and in some cases, such as at Nyero, sites are still in use by local peoples with offerings being made and sites associated with rain-making rituals. However, the advent of colonialism influenced such traditions bringing a change in the way the forest was venerated, used and conceptualised. citations: - sys: id: R9NAlFnoYuGyywYgIccK created_at: !ruby/object:DateTime 2015-11-26 18:42:30.538000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:42:30.538000000 Z content_type_id: citation revision: 1 citation_line: | &dagger; A Tentative List is an inventory of those properties considered to be of cultural and/or natural heritage of outstanding universal value and therefore suitable for inscription on the World Heritage List. <NAME>. 1974. ‘The Prehistoric Art of the Lake Victoria Region’, in *Azania* 9, pp: 1-50. <NAME>. 1961. *Red Dust: Memories of the Uganda Police* 1935-1955. London: Vincent Stuart Ltd. <NAME>. 1953. ‘Rock Paintings in Teso’, in *Uganda Journal* 17, pp: 8-13. <NAME>. 1967. ‘Rock Engravings from Loteteleit, Karamoja’, in *Uganda Journal* 19, p:90. <NAME>. 2010. Surrogate Surfaces: *A contextual interpretive approach to the rock art of Uganda*. Unpublished PhD Thesis. Johannesburg: University of Witwatersrand <NAME>. 1961. ‘Rock Paintings on Lolui Island, Lake Victoria’ in *Uganda Journal*, 25, pp: 105-11. <NAME>. 1938. ‘Note on Prehistoric Inscription in Ankole Uganda’, in *Uganda Journal* 5, pp: 252 – 53. background_images: - sys: id: 3x2PiewS1i8ou4ik4Oe0eI created_at: !ruby/object:DateTime 2015-11-30 14:16:24.740000000 Z updated_at: !ruby/object:DateTime 2015-11-30 14:16:24.740000000 Z title: UGAVIC0050009 jpeg description: url: "//images.ctfassets.net/xt8ne4gbbocd/3x2PiewS1i8ou4ik4Oe0eI/d14a880ca6ff92cd2017f57426a08d83/UGAVIC0050009_jpeg.jpg" - sys: id: 1PIG4cOXQg4GYcssAoIcgE created_at: !ruby/object:DateTime 2015-11-30 14:16:31.945000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:48:49.387000000 Z title: '2013,2034.14850' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3673353&partId=1&searchText=UGATES0020029&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/1PIG4cOXQg4GYcssAoIcgE/128ac1905e76484c13aa53c4356475b9/UGATES0020029_jpeg.jpg" - sys: id: 3QpNCcuYEUaGiSisY0Qeoc created_at: !ruby/object:DateTime 2015-11-27 14:15:13.492000000 Z updated_at: !ruby/object:DateTime 2015-11-27 14:15:13.492000000 Z title: '2013,2034.14633' description: url: "//images.ctfassets.net/xt8ne4gbbocd/3QpNCcuYEUaGiSisY0Qeoc/769a299227cfaaace934a1b79e09e4b9/UGAMOR0010021.jpg" region: Eastern and central Africa ---<file_sep>/_coll_country/malawi/namzeze.md --- breadcrumbs: - label: Countries url: "../../" - label: 'Malawi ' url: "../" layout: featured_site contentful: sys: id: 5C6UTnDXt6A4q6ggIcYMmu created_at: !ruby/object:DateTime 2016-07-27 07:45:11.921000000 Z updated_at: !ruby/object:DateTime 2016-07-27 08:51:26.975000000 Z content_type_id: featured_site revision: 5 title: 'Namzeze, Malawi ' slug: namzeze chapters: - sys: id: 5kJvUt9jLqo0GuIoWskUgA created_at: !ruby/object:DateTime 2016-07-27 07:45:24.101000000 Z updated_at: !ruby/object:DateTime 2016-07-27 08:32:20.393000000 Z content_type_id: chapter revision: 2 title_internal: 'Malawi: featured site, chapter 1' body: 'Namzeze, one of the most emblematic sites in the Chongoni rock art area, is currently one of the three that can be visited and is open to the public. Unlike many of the other sites, which are grouped together, the Namzeze shelter is isolated in the centre of the protected area. Located in a position overlooking the valley towards the Chongoni Hill, the impressive rock face of Namzeze contains some of the best examples of both traditions of Malawian rock art, the red schematic and white paintings. The site also has a strong symbolism for the Chewa people who still inhabit the area and for whom the white paintings of the later period still have deep spiritual implications. ' - sys: id: MUbQnik9qKECmGamGEkKa created_at: !ruby/object:DateTime 2016-07-27 07:45:24.019000000 Z updated_at: !ruby/object:DateTime 2017-01-24 16:33:30.093000000 Z content_type_id: image revision: 3 image: sys: id: 1IFNGAi4IkScieYwOmGiMA created_at: !ruby/object:DateTime 2016-07-27 07:46:38.189000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:38.189000000 Z title: MALDED0060001 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1IFNGAi4IkScieYwOmGiMA/c57b23e18a40a00a63f25361a859805e/MALDED0060001.jpg" caption: View of the landscape from Namzeze, with two signs indicating the presence of rock art paintings and codes of behaviour in the foreground. 2013,2034.19844 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3730077&partId=1 - sys: id: 5R7b3Vb7H2UueCms0uC6Cy created_at: !ruby/object:DateTime 2016-07-27 07:45:23.819000000 Z updated_at: !ruby/object:DateTime 2017-01-24 16:34:17.661000000 Z content_type_id: image revision: 3 image: sys: id: 3mGBPrPBdYqWW4MUUissms created_at: !ruby/object:DateTime 2016-07-27 07:46:38.998000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:38.998000000 Z title: MALDED0060017 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3mGBPrPBdYqWW4MUUissms/0989042b0914b15d42be755ae787f5de/MALDED0060017.jpg" caption: Rock art panel with red and white depictions. Namzeze. 2013,2034.19860 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3730116&partId=1 - sys: id: 1DWS9OfqHuK6Sca6IMYEEU created_at: !ruby/object:DateTime 2016-07-27 07:45:23.189000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:45:23.189000000 Z content_type_id: chapter revision: 1 title_internal: 'Malawi: featured site, chapter 2' body: "The superimpositions in the panel above show that the red, schematic paintings covering most of the rock face are undoubtedly older than those made in white. \ Representations include a multitude of geometric signs: series of parallel lines, grid-style shapes, concentric ovals and circular shapes made with series of dots. In some cases the red signs were infilled with series of tiny white dots, a feature uncommon in the red schematic rock art depictions but with the best examples represented here in Namzeze. Its interpretation, as with most geometric depictions, is a challenging issue, but these types of paintings have been traditionally related to ancestors of Batwa people, hunter-gatherers, who inhabited the region until the 1800s. Studies of Batwa ethnography and cosmology point to these places as related to fertility and rainmaking ceremonies. \ It is difficult to establish the chronology. The oldest occupation documented in the region is dated to the mid-first millennium BC, and the red images precede the arrival of the Chewa people in the 2nd millennium AD, responsible for the white paintings style, but there is no datable evidence for the paintings. \n" - sys: id: 1sxQJiwCfecQeO88iQiQgm created_at: !ruby/object:DateTime 2016-07-27 07:45:23.173000000 Z updated_at: !ruby/object:DateTime 2017-01-24 16:34:50.814000000 Z content_type_id: image revision: 2 image: sys: id: 26hf0yyVDWY6MAGWQeiaMY created_at: !ruby/object:DateTime 2016-07-27 07:46:39.075000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:39.075000000 Z title: MALNAM0010015 description: url: "//images.ctfassets.net/xt8ne4gbbocd/26hf0yyVDWY6MAGWQeiaMY/d24ebe749ebd39df56c7587ec2ab9825/MALNAM0010015.jpg" caption: Detail of red geometric sign infilled with white dots. Namzeze. 2013,2034. 20283 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3730246&partId=1 - sys: id: 4NKmod8inm0CKoKWeIE4CW created_at: !ruby/object:DateTime 2016-07-27 07:45:23.031000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:45:23.031000000 Z content_type_id: chapter revision: 1 title_internal: 'Malawi: featured site, chapter 3' body: The second type of painting found in Namzeze is radically different and depicts mainly quadrupeds and birds, as well as some geometric symbols and a car, proof of a relatively recent date for some of these paintings. Quadrupeds have a very characteristic rectangular body and hooves that in some cases are represented as feet. The technique is very different too, consisting of white clay daubed on the wall with the fingers. These white figures usually appear surrounding the previous depictions, in some rare occasions overlapping them. In this case, the authorship, chronology and interpretation of the paintings are more straightforward. Researchers agree that these types of paintings have been made by the Chewa, a group of farmers that arrived to the region around the 16th century and have maintained rock art painting traditions until the 20th century (as the car represented in this shelter proves). - sys: id: 5LnKSbFOfuiEwG4gKk2muG created_at: !ruby/object:DateTime 2016-07-27 07:45:22.972000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:45:22.972000000 Z content_type_id: image revision: 1 image: sys: id: 1AdufAw4d6U6ioCOEiQyye created_at: !ruby/object:DateTime 2016-07-27 07:46:39.002000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:39.002000000 Z title: MALDED0060019 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1AdufAw4d6U6ioCOEiQyye/d6ab356b64107c958388d56ebc74a7e9/MALDED0060019.jpg" caption: Rock art panel with red geometric signs and white animal-like figures, Namzeze. 2013,2034.19862 © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3730114&partId=1 - sys: id: 4b9kxjjlvWgowy6QaKISeM created_at: !ruby/object:DateTime 2016-07-27 07:45:22.920000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:45:22.920000000 Z content_type_id: chapter revision: 1 title_internal: 'Malawi: featured site, chapter 4' body: 'Regarding the interpretation of the paintings, they are directly related to the *nyau*, a secret society of the Chewa and other neighbouring groups in Malawi, Zambia and Mozambique which plays a significant role in funerary and girl’s initiation ceremonies. The *nyau* rituals include dancing and rely heavily on the use of masks, including face masks as well as other mobile structures carried by one or two people. These masks are central for the *nyau* secret society and are kept in secret, hidden from non-initiates. The white paintings of Namzeze and many other sites have been interpreted as representations of masks, depicted during initiation ceremonies that took place in these isolated shelters where secrets of the *nyau* were explained to the new initiates. ' - sys: id: 10PySD1RyuIycESgkSC6wc created_at: !ruby/object:DateTime 2016-07-27 07:45:22.859000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:45:22.859000000 Z content_type_id: image revision: 1 image: sys: id: 7iE4ypc2QwGUOmSAscwqC8 created_at: !ruby/object:DateTime 2016-07-27 07:46:39.077000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:39.077000000 Z title: MALNAM0010035 description: url: "//images.ctfassets.net/xt8ne4gbbocd/7iE4ypc2QwGUOmSAscwqC8/2e085aba2bd10c62941a32016835323c/MALNAM0010035.jpg" caption: White animal-like figures related to the Nyau rituals. Namzeze. 2013,2034.19892 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3730149&partId=1 - sys: id: 7oK266GlZ6uWwAyIQU2Ka2 created_at: !ruby/object:DateTime 2016-07-27 07:45:22.733000000 Z updated_at: !ruby/object:DateTime 2016-07-27 09:05:31.732000000 Z content_type_id: chapter revision: 2 title_internal: 'Malawi: featured site, chapter 5' body: "In fact, some of the more than 100 types of masks can be easily identified in the rock shelters. The most common is the *kasiyamaliro*, a big structure representing an antelope, with a rectangular shape and meant to be carried by two people (an [excellent example](http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=472359&partId=1) can be seen in Room 25 in the British Museum), but others, such as the *Galimoto* (a car structure) and birds are also documented. Some of the features of the animals depicted in this panel corroborate with this interpretation: the shape of the hooves which is more similar to feet, and the fact that in some cases the feet of the forelegs and the hind legs are facing each other, as if they corresponded to two different people. Some researchers have interpreted this feature as a pictorial tool to teach people the proper way of wearing and using the structure to avoid stumbling, which would expose the men hidden in the structure and thus the secret of the mask would be revealed. \n" - sys: id: 3aGsr1Cs7Ccqu2AeSqo6GI created_at: !ruby/object:DateTime 2016-07-27 07:45:22.151000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:45:22.151000000 Z content_type_id: image revision: 1 image: sys: id: 3oM6s0shy0UgQe8MAgy0GK created_at: !ruby/object:DateTime 2016-07-27 07:46:39.101000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:39.101000000 Z title: MALNAM0010036 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3oM6s0shy0UgQe8MAgy0GK/f85d336dfd78d4665fb96b6010db6682/MALNAM0010036.jpg" caption: Detail of a white animal with the legs facing each other, interpreted as a costume for a Nyau masquerade, Namzeze. 2013,2034.20304 © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3730272&partId=1 - sys: id: 1XMXz5051iESkU004EmQsi created_at: !ruby/object:DateTime 2016-07-27 07:45:22.173000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:45:22.173000000 Z content_type_id: image revision: 1 image: sys: id: 2hJ1GBmp4cgOsaYWaCU684 created_at: !ruby/object:DateTime 2016-07-27 07:46:38.309000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:38.309000000 Z title: 17-03-2016 171 description: url: "//images.ctfassets.net/xt8ne4gbbocd/2hJ1GBmp4cgOsaYWaCU684/bc96220c1a95462408c1b72f33fbc183/17-03-2016_171.jpg" caption: 'Costume for Nyau masquerade in form of an animal construction (kasiyamaliro). Af1993,09.150 ' col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=472359&partId=1 - sys: id: 4uCXTRqJMQeYuogAgOWY8Y created_at: !ruby/object:DateTime 2016-07-27 07:45:22.059000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:45:22.059000000 Z content_type_id: chapter revision: 1 title_internal: 'Malawi: featured site, chapter 6' body: "Paintings associated to the *nyau* secret society were used during a very specific period of time (before that other styles of white paintings were used), when the secret society was persecuted first by Ngoni invaders in the 19th century, then by missionaries and colonial governments in the 20th century. With their traditional practices and places forbidden, the members of this society had to look for alternative ways to teach the secrets of the secret society secrets, with the paintings starting to represent *nyau* objects, to be used as a didactic tool. The Namzeze paintings show very explicitly the adaptability of societies to their different challenges and historical contexts. Either as a tool to summon the rain or as a coded message to transmit sacred secrets, the painted symbols depicted in Namzeze show the incredible complexity of rock art meanings throughout time, and their importance for the communities that painted them. \n" citations: - sys: id: 43haKDmJdC0QCSgEkw0gyW created_at: !ruby/object:DateTime 2016-07-27 07:45:22.058000000 Z updated_at: !ruby/object:DateTime 2016-07-27 10:01:31.562000000 Z content_type_id: citation revision: 2 citation_line: '<NAME>. 2001. ''Forbidden Images: Rock Paintings and the Nyau Secret Society of Central Malawi and Eastern Zambia''. *African Archaeological Review, 18 (4)* pp. 187-212' background_images: - sys: id: 7iE4ypc2QwGUOmSAscwqC8 created_at: !ruby/object:DateTime 2016-07-27 07:46:39.077000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:39.077000000 Z title: MALNAM0010035 description: url: "//images.ctfassets.net/xt8ne4gbbocd/7iE4ypc2QwGUOmSAscwqC8/2e085aba2bd10c62941a32016835323c/MALNAM0010035.jpg" - sys: id: 26hf0yyVDWY6MAGWQeiaMY created_at: !ruby/object:DateTime 2016-07-27 07:46:39.075000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:39.075000000 Z title: MALNAM0010015 description: url: "//images.ctfassets.net/xt8ne4gbbocd/26hf0yyVDWY6MAGWQeiaMY/d24ebe749ebd39df56c7587ec2ab9825/MALNAM0010015.jpg" ---<file_sep>/_coll_country/nigeria/ikom-monoliths .md --- breadcrumbs: - label: Countries url: "../../" - label: Nigeria url: "../" layout: featured_site contentful: sys: id: 3pCjM8ACHeyCo28Kuye6Oa created_at: !ruby/object:DateTime 2017-12-12 03:41:45.814000000 Z updated_at: !ruby/object:DateTime 2017-12-12 03:41:45.814000000 Z content_type_id: featured_site revision: 1 title: Ikom Monoliths, Cross River State, Nigeria slug: 'ikom-monoliths ' chapters: - sys: id: 6tTnRXJY5O4oiMcUIg2e6w created_at: !ruby/object:DateTime 2017-12-12 01:00:49.285000000 Z updated_at: !ruby/object:DateTime 2017-12-12 01:00:49.285000000 Z content_type_id: chapter revision: 1 title_internal: 'Nigeria: featured site, chapter 1' body: The Ikom Monoliths, originally consisting of around 400-450 engraved standing stones and distributed around thirty communities in the Ikom area of Cross River State, Nigeria, are thought to be up to 1500 years old. In more recent years, threatened by fire, theft, vandalism and neglect, there are now estimated to be less than 250. - sys: id: 5WVd1xtyCW8IkIm8MkyqoA created_at: !ruby/object:DateTime 2017-12-12 01:03:19.623000000 Z updated_at: !ruby/object:DateTime 2017-12-12 01:03:19.623000000 Z content_type_id: image revision: 1 image: sys: id: 6ndlBNzj4kC4IyysaSk20Y created_at: !ruby/object:DateTime 2017-12-12 01:02:00.372000000 Z updated_at: !ruby/object:DateTime 2017-12-12 01:02:00.372000000 Z title: NIGCRM0040011 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6ndlBNzj4kC4IyysaSk20Y/a9e3b2d35c3e0ee55a93cef88d92b9e3/NIGCRM0040011.jpg" caption: Monolith from Nnaborakpa with village elder standing in the background. 2013,2034.24046 © <NAME>/TARA - sys: id: 3wE6yzisV22Cq6S266Q8CO created_at: !ruby/object:DateTime 2017-12-12 01:13:13.390000000 Z updated_at: !ruby/object:DateTime 2017-12-12 01:13:13.390000000 Z content_type_id: chapter revision: 1 title_internal: 'Nigeria: featured site, chapter 2' body: 'The majority of the stones are skilfully carved in hard, medium-textured basaltic rock, with a few carved in sandstone and shelly limestone. Varying in height from 0.91-1.83m (3-6 feet) and sculpted into a phallus-shape, the stones share common decorative features. They depict stylised human features comprising two eyes, an open mouth, a head crowned with rings, a pointed beard, an elaborately marked navel, two hands with five fingers, a nose and a variety of facial markings. Emphasis is placed on the head while the rest of the body tapers into the base of the phallus’ shaped monolith, with limbs and legs suggested. They are also linearly inscribed with complex geometric motifs, which have been compared to the rock arts of Tanzania in that the meanings of the symbols are known to only the artists (UNESCO, 2007). ' - sys: id: 5Ep1vP8VXOi2se8O6qIY2q created_at: !ruby/object:DateTime 2017-12-12 01:46:21.095000000 Z updated_at: !ruby/object:DateTime 2017-12-12 01:46:21.095000000 Z content_type_id: image revision: 1 image: sys: id: 3EPsiq8TFKE0omSUGy2OiW created_at: !ruby/object:DateTime 2017-12-12 01:44:18.764000000 Z updated_at: !ruby/object:DateTime 2017-12-12 01:44:18.764000000 Z title: NIGCRM0090006 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3EPsiq8TFKE0omSUGy2OiW/920454e1f1e3b5ed3e7c24108a6c46ee/NIGCRM0090006.jpg" caption: Monolith from Agba. 2013,2034.24215© <NAME>/TARA - sys: id: 4fEnlxdHhSc4gUcGMyaegi created_at: !ruby/object:DateTime 2017-12-12 01:50:43.447000000 Z updated_at: !ruby/object:DateTime 2017-12-12 01:50:43.447000000 Z content_type_id: image revision: 1 image: sys: id: 1FTDyPet3WiyQYiq2UYEeu created_at: !ruby/object:DateTime 2017-12-12 01:49:44.361000000 Z updated_at: !ruby/object:DateTime 2017-12-12 01:49:44.361000000 Z title: NIGCRM0020001 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1FTDyPet3WiyQYiq2UYEeu/5691015503e7f726f99676e2976ef569/NIGCRM0020001.jpg" caption: Monolith from Njemetop. 2013,2034.23963 © <NAME>/TARA - sys: id: 21hKs1bzN6imgeCkiouquo created_at: !ruby/object:DateTime 2017-12-12 01:51:41.445000000 Z updated_at: !ruby/object:DateTime 2017-12-12 01:51:41.445000000 Z content_type_id: chapter revision: 1 title_internal: 'Nigeria: featured site, chapter 3' body: The effects of weathering has resulted in erosion and deterioration, and as such in 2007 were added to the World Monuments Fund’s list of sites in danger and are being considered for inclusion into UNESCO’s World Heritage Site list. Furthermore, it is estimated that the total numbers of monoliths is now thought to be less than 250, with many having been distributed among major museums throughout the world. - sys: id: 5Lj0qQJbj2eUyGsMEUegiG created_at: !ruby/object:DateTime 2017-12-12 01:54:04.301000000 Z updated_at: !ruby/object:DateTime 2017-12-12 01:54:04.301000000 Z content_type_id: image revision: 1 image: sys: id: 1wBaFXQ6iY2igSUc0Qwm02 created_at: !ruby/object:DateTime 2017-12-12 01:52:33.766000000 Z updated_at: !ruby/object:DateTime 2017-12-12 01:52:33.766000000 Z title: NIGCRM0070021 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1wBaFXQ6iY2igSUc0Qwm02/9bf58633776be1e68afbcc3a2bdf0279/NIGCRM0070021.jpg" caption: Moss and lichen growing on one of the monoliths occluding facial feaures, Nikirigom. 2013,2034.24103 © <NAME>/TARA - sys: id: 5IN3UXWyqswwO0qu4q6Ukc created_at: !ruby/object:DateTime 2017-12-12 01:55:42.020000000 Z updated_at: !ruby/object:DateTime 2017-12-12 01:55:42.020000000 Z content_type_id: image revision: 1 image: sys: id: 4GxwIaZP680CyIGeQ4YesO created_at: !ruby/object:DateTime 2017-12-12 01:54:53.364000000 Z updated_at: !ruby/object:DateTime 2017-12-12 01:54:53.364000000 Z title: NIGCRM0100031 description: url: "//images.ctfassets.net/xt8ne4gbbocd/4GxwIaZP680CyIGeQ4YesO/1a6e720fb39268f67947f11e6a496cce/NIGCRM0100031.jpg" caption: Fallen monolith that has been damaged by fire, Edamkono. 2013,2034.24278 © <NAME>/TARA - sys: id: 5UGVq9x89UIaMYwOmaCWYq created_at: !ruby/object:DateTime 2017-12-12 02:03:17.080000000 Z updated_at: !ruby/object:DateTime 2017-12-12 02:03:17.080000000 Z content_type_id: chapter revision: 1 title_internal: 'Nigeria: featured site, chapter 4' body: Known as Akwasnshi or Atal among the local Ejagham people of Cross River, the monoliths can be found in the centre of the village or in the central meeting place of the village elders, but also in the uncultivated forest outside the villages. In each village in which they are found, the upright stones are positioned in circles, sometimes perfect circles, facing each other. Some are slightly carved as very low reliefs, while others are inscribed engravings. - sys: id: 7afrXxiCmAmIq2Ae8CEMsQ created_at: !ruby/object:DateTime 2017-12-12 02:04:55.030000000 Z updated_at: !ruby/object:DateTime 2017-12-12 02:04:55.030000000 Z content_type_id: image revision: 1 image: sys: id: 4Rzr1W9YZ2yecY6MGkQ8Y8 created_at: !ruby/object:DateTime 2017-12-12 02:04:07.843000000 Z updated_at: !ruby/object:DateTime 2017-12-12 02:04:07.843000000 Z title: NIGCRM0010062 description: url: "//images.ctfassets.net/xt8ne4gbbocd/4Rzr1W9YZ2yecY6MGkQ8Y8/b45ad7ea3470fdabaea542144334b4f2/NIGCRM0010062.jpg" caption: View of five standing stones and one fallen stone in a clearing, Alok. 2013,2034.23933 © <NAME>/TARA - sys: id: 2mMylBVqvaQ6gIgoAiO6MU created_at: !ruby/object:DateTime 2017-12-12 02:05:49.581000000 Z updated_at: !ruby/object:DateTime 2017-12-12 02:05:49.581000000 Z content_type_id: chapter revision: 1 title_internal: 'Nigeria: featured site, chapter 5' body: Whilst the stones seem to share common features, each monolith is unique in its design and execution, and are thought to “bear a complex codified iconography and an ancient writing, communication and graphic system composed in a complex traditional design configuration” (UNESCO 2007). - sys: id: 20UEFUXCJOO6ki86sMi6q2 created_at: !ruby/object:DateTime 2017-12-12 03:35:55.321000000 Z updated_at: !ruby/object:DateTime 2017-12-12 03:35:55.321000000 Z content_type_id: chapter revision: 1 title: Interpretation title_internal: 'Nigeria: featured site, chapter 6' body: | Local ethnographies about the Ikom monoliths are based in oral traditions and as such there are numerous meanings associated with the stones. For example, stone circles are used as places of sacrifice and community meeting places. They were created as memorials of departed heroes or beloved family members and represent powerful ancestral spirits to whom offerings are still made (Esu and Ukata, 2012:112). In addition local community leaders also ascribed religious significance of the stones whereby particular stone are dedicated to the god of harvest, the god of fertility and the god of war (Esu and Ukata, 2012:113). The local communities in the area value the monoliths in their traditional practices, beliefs and rituals, such as being ceremonially painted at the time of the [Yam festival](http://africanrockart.org/news/monoliths-cross-river-state-nigeria "monoliths cross river state"). - sys: id: 5Azwtj3SEgoEweaESQUY0e created_at: !ruby/object:DateTime 2017-12-12 03:39:23.421000000 Z updated_at: !ruby/object:DateTime 2017-12-12 03:39:23.421000000 Z content_type_id: image revision: 1 image: sys: id: rOeKzKuGw8EMG08MyM02Q created_at: !ruby/object:DateTime 2017-12-12 03:38:21.345000000 Z updated_at: !ruby/object:DateTime 2017-12-12 03:38:21.345000000 Z title: NIGCRM0010081 description: url: "//images.ctfassets.net/xt8ne4gbbocd/rOeKzKuGw8EMG08MyM02Q/a8e500a01a2d3f45d2c761aeb181d904/NIGCRM0010081.jpg" caption: 'Monoith being opainted in orange, blue and white by local woman. Standing to the left is Chief Silvanus Akong of Alok village. 2013,2034.23952 © David Coulson/TARA ' - sys: id: 47U5H0p6yQUWagCwYauyci created_at: !ruby/object:DateTime 2017-12-12 03:40:23.912000000 Z updated_at: !ruby/object:DateTime 2017-12-12 03:40:23.912000000 Z content_type_id: chapter revision: 1 title_internal: 'Nigeria: featured site, chapter 7' body: 'Recent criticism has focused on ways in which scholars have situated these sculptural forms within Western/European anthropological and archaeological discourse that has reduced them to “mere artefacts and monuments” rather than attending to their “artistic attributes, content and context” (Akpang, 2014:67-68). ' citations: - sys: id: 5XzFExCZYA4mKGY0ua6Iwc created_at: !ruby/object:DateTime 2017-12-12 00:54:17.136000000 Z updated_at: !ruby/object:DateTime 2017-12-12 00:54:17.136000000 Z content_type_id: citation revision: 1 citation_line: "<NAME>. 2014. ‘Beyond Anthropological and Associational discourse- interrogating the minimalism of Ikom Monoliths as concept and found object art’, in \n*Global Journal of Arts Humanities and Social Sciences*, Vol.2, Issue 1, pp.67-84.\n\nAllison P. 1967. *Cross River State Monoliths*. Lagos: Department of Antiquities, Federal Republic of Nigeria.\n\nEsu, <NAME>. and Ukata, S. 2012. ‘Enhancing the tourism value of Cross River state monoliths and stone circles through geo-mapping and ethnographic study (part 1)’, in *Journal of Hospitality Management and Tourism*, Vol. 3(6), pp. 106-116.\n\nLe Quellec, J-L. 2004. *Rock Art in Africa: Mythology and Legend*. Paris: Flammarion.\n\nMangut, J. and Mangut, <NAME>. 2012. ‘Harnessing the Potentials of Rock Art Sites in Birnin Kudu, Jigawa State, Nigeria for Tourism Development’, in *Journal of Tourism and Heritage*, Vol.1 No. 1 pp: 36-42.\n\nShaw, T. 1978. *Nigeria its Archaeology and Early History*. London: Thames and\nHudson.\n\nUNESCO. 2007. ‘Alok Ikom Monoliths’ UNESCO [Online], Available at: http://whc.unesco.org/en/tentativelists/5173/\n\nVaughan J. H. 1962. ‘Rock paintings and Rock gong among the Marghi of\nNigeria’ in *Man*, 62, pp:49-52.\n\n\n" background_images: - sys: id: 3EPsiq8TFKE0omSUGy2OiW created_at: !ruby/object:DateTime 2017-12-12 01:44:18.764000000 Z updated_at: !ruby/object:DateTime 2017-12-12 01:44:18.764000000 Z title: NIGCRM0090006 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3EPsiq8TFKE0omSUGy2OiW/920454e1f1e3b5ed3e7c24108a6c46ee/NIGCRM0090006.jpg" - sys: id: rOeKzKuGw8EMG08MyM02Q created_at: !ruby/object:DateTime 2017-12-12 03:38:21.345000000 Z updated_at: !ruby/object:DateTime 2017-12-12 03:38:21.345000000 Z title: NIGCRM0010081 description: url: "//images.ctfassets.net/xt8ne4gbbocd/rOeKzKuGw8EMG08MyM02Q/a8e500a01a2d3f45d2c761aeb181d904/NIGCRM0010081.jpg" ---<file_sep>/_coll_country_information/zimbabwe-country-introduction.md --- contentful: sys: id: 57nTuvCZRm2kQIWosYeEQq created_at: !ruby/object:DateTime 2016-09-12 11:58:22.969000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:58:22.969000000 Z content_type_id: country_information revision: 1 title: 'Zimbabwe: country introduction' chapters: - sys: id: 7wG2jigwgw4cGsusgAeCGc created_at: !ruby/object:DateTime 2016-09-12 11:53:52.433000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:53:52.433000000 Z content_type_id: chapter revision: 1 title: Introduction - Geography and rock art distribution title_internal: 'Zimbabwe: country, chapter 1' body: 'Zimbabwe is a landlocked country surrounded by Mozambique, Zambia, Botswana and South Africa, occupying a large, granitic high plateau between the Zambezi and Limpopo river systems, with a tropical climate moderated by altitude. The highest part of the country is the eastern Highlands; a north-south mountain range reaching altitudes of 2,500 m. Rock art is located in two main areas, the northern region of Mashonaland and the south-western area of Matabeleland. These areas are full of granite hills and boulders that provide excellent shelters for the paintings. The Matobo hills in Matabeleland constitute one of the most outstanding examples of rock art in Southern Africa. The total number of Zimbabwean rock art sites is unknown, but estimations made point to thousands of sites throughout the country, with more being discovered annually. ' - sys: id: 1vTYjbXbXuoWIu8Og2Ga6u created_at: !ruby/object:DateTime 2016-09-12 11:58:16.773000000 Z updated_at: !ruby/object:DateTime 2019-02-12 00:40:06.610000000 Z content_type_id: image revision: 2 image: sys: id: 40o6cuVD1mg0GcouA8Iaym created_at: !ruby/object:DateTime 2016-09-12 12:06:48.519000000 Z updated_at: !ruby/object:DateTime 2016-09-12 12:06:48.519000000 Z title: ZIMMSL0280001 description: url: "//images.ctfassets.net/xt8ne4gbbocd/40o6cuVD1mg0GcouA8Iaym/32da0eecea127afbf2c5f839534485da/ZIMMSL0280001.jpg" caption: Rocky outcrop in Mashonaland, Zimbabwe. 2013,2034.23240 ©TARA/<NAME> col_link: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3775899&partId=1&searchText=2013,2034.23240&page=1 - sys: id: 2P8CUhzioUcQ2WQUCmy4eK created_at: !ruby/object:DateTime 2016-09-12 11:53:52.382000000 Z updated_at: !ruby/object:DateTime 2016-09-12 18:50:57.591000000 Z content_type_id: chapter revision: 2 title: History of the research title_internal: 'Zimbabwe: country, chapter 2' body: 'Zimbabwean rock art was first reported by Europeans in 1927, when Miles Burkitt visited southern Africa, but is especially linked to <NAME>, one of the most renowned researchers in the first decades of the 20th century. <NAME> travelled to the region in 1928 with a German team and thoroughly documented numerous paintings, identifying many of the most characteristic features of Zimbabwean rock art. However, he failed in identifying the authors of the paintings, ascribing them to external influences of “high civilizations” instead to the local communities who made them. Subsequently, work was continued by <NAME>, who for forty years documented rock art paintings constituting a huge corpus of tracings, but without developing an interpretative framework for them. In the 1950s, another historic researcher, the <NAME> Breuil, visited Zimbabwe and studied the paintings, again suggesting an Egyptian or Minoan origin. It wasn’t until the 1960s and 1970s when a more objective approach to the study of rock art started, with <NAME> the most prominent figure in research from the 1980s onwards. Garlake wrote the first comprehensive books on Zimbabwean rock art (Garlake 1987), integrating it within the general framework of southern Africa and raising awareness about the importance of these archaeological expressions. In 2003 the Matobo Hills were included in the World Heritage List acknowledging the relevance of Zimbabwean rock art for African heritage. ' - sys: id: cUUCZ3TJ1mmO48egCGE2k created_at: !ruby/object:DateTime 2016-09-12 11:58:33.564000000 Z updated_at: !ruby/object:DateTime 2019-02-12 00:41:14.221000000 Z content_type_id: image revision: 2 image: sys: id: 2fUMJJmhu0gAW4Kkoscw2i created_at: !ruby/object:DateTime 2016-09-12 11:58:30.277000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:58:30.277000000 Z title: ZIMMSL0070001 description: url: "//images.ctfassets.net/xt8ne4gbbocd/2fUMJJmhu0gAW4Kkoscw2i/6c0c5908e2526dae2378c771a641e1f0/ZIMMSL0070001.jpg" caption: Yellow elephant calf painted on the roof of a shelter. Mashonaland, Zimbabwe. 2013,2034.22675 ©TARA/<NAME> col_link: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3775294&partId=1&searchText=2013,2034.22675&page=1 - sys: id: 1GwWneVcV2OGekOmYsisAk created_at: !ruby/object:DateTime 2016-09-12 11:53:52.340000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:53:52.340000000 Z content_type_id: chapter revision: 1 title: Themes title_internal: 'Zimbabwe: country, chapter 3' body: The rock art of Zimbabwe is some of the richest in Africa both in variety and complexity, the vast majority being painted figures infilled or outlined usually with just one colour, although bichrome examples are also known. The human figure is the most often represented engaged in different activities -hunting, walking, dancing- either isolated or in groups of up to forty people. The figures are depicted in different styles, from the very schematic to relatively naturalistic outlines, with men far more represented than women, and usually depicted carrying bows and arrows. In some cases, these figures are part of very complex scenes including animals and geometric symbols, some of which have been interpreted as trance-like scenes similar to those in South Africa with figures bleeding from their noses, crouching or dancing in groups or sharing animal traits. A very specific type of depiction is human figures with hugely distended abdomens, a trait that is associated either with fertility or mystic potency concepts. - sys: id: 7cZfHMXB84oouoceeswCUQ created_at: !ruby/object:DateTime 2016-09-12 11:58:40.649000000 Z updated_at: !ruby/object:DateTime 2019-02-12 00:42:32.233000000 Z content_type_id: image revision: 3 image: sys: id: 51wED0wl4cSWQAWcEqAKek created_at: !ruby/object:DateTime 2016-09-12 11:58:45.461000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:58:45.461000000 Z title: ZIMMSL0230014 description: url: "//images.ctfassets.net/xt8ne4gbbocd/51wED0wl4cSWQAWcEqAKek/7e367c5c29de4def2fd4fbc4f81b7dd1/ZIMMSL0230014.jpg" caption: Complex scene of human figures and antelopes. Mashonaland, Zimbabwe. 2013,2034.23055 ©TARA/<NAME> col_link: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3775708&partId=1&searchText=2013,2034.23055&page=1 - sys: id: 2JiGtVlFnOqOUEqWcOyCms created_at: !ruby/object:DateTime 2016-09-12 11:53:52.331000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:53:52.331000000 Z content_type_id: chapter revision: 1 title_internal: 'Zimbabwe: country, chapter 4' body: 'Along with human figures, animals are widely represented in Zimbabwean rock art, with kudu depictions dominating, but also with zebra, tsessebe and sable antelopes commonly represented. Surprisingly, other antelopes such as eland, waterbucks or wildebeest are very rarely represented, while other animals (lions, cheetah, birds, ant bears, porcupines, baboons or warthogs) are very scarce. Fish and crocodiles are relatively common, the latter represented as if seen from above or below. There seems to be a preference for the depiction of females rather than males, especially in the case of antelopes or elephants. Regardless of the type of animal, the depictions seem to have a deep symbolism far beyond the representation of animals just hunted and consumed, often being surrounded by dots, flecks or networks of lines. That symbolism is especially important in the case of the elephant, which is often depicted being hunted by groups of men. ' - sys: id: 60AofQXYWsUsusmsKwaGyS created_at: !ruby/object:DateTime 2016-09-12 11:58:54.647000000 Z updated_at: !ruby/object:DateTime 2019-02-12 00:43:25.464000000 Z content_type_id: image revision: 2 image: sys: id: 37IO99TlpSsMKoCoOskwyO created_at: !ruby/object:DateTime 2016-09-12 11:58:59.626000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:58:59.626000000 Z title: ZIMMSL0210014 description: url: "//images.ctfassets.net/xt8ne4gbbocd/37IO99TlpSsMKoCoOskwyO/5156a40344d65934a2c8bdf86d3f78b9/ZIMMSL0210014.jpg" caption: Group of human figures and different types of animals including giraffes, antelopes and warthogs. 2013,2034.22962 ©TARA/<NAME> col_link: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3775615&partId=1&searchText=2013,2034.22962&page=1 - sys: id: 36YlRmgg8EIiueMgCamy6e created_at: !ruby/object:DateTime 2016-09-12 11:53:52.275000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:53:52.275000000 Z content_type_id: chapter revision: 1 title_internal: 'Zimbabwe: country, chapter 5' body: 'Human figures and animals are accompanied by many geometric symbols, usually related to trance-like contexts and include dots, wavy lines or stripes. One of the most original types of symbols known as ‘formlings’, are oblong figures divided in clusters and frequently combining several colours. These are difficult to interpret but could be associated with complex ideas related to trance states, although some other interpretations, such as their relating to beehives, have been suggested (Garlake 1995: 97).' - sys: id: 5icNtVo3wWOg2EA62yK0gI created_at: !ruby/object:DateTime 2016-09-12 11:59:08.602000000 Z updated_at: !ruby/object:DateTime 2019-02-12 00:44:25.781000000 Z content_type_id: image revision: 2 image: sys: id: nRXWoI9Gk8uy2go42GomE created_at: !ruby/object:DateTime 2016-09-12 11:59:12.467000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:59:12.467000000 Z title: ZIMMTB0060005 description: url: "//images.ctfassets.net/xt8ne4gbbocd/nRXWoI9Gk8uy2go42GomE/2bb4e21572df0610dfa429bb8b6f4bf2/ZIMMTB0060005.jpg" caption: Depiction of a formling surrounding by animals. Matabeleland, Zimbabwe. 2013,2034.23465 ©TARA/<NAME> col_link: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3763606&partId=1&searchText=2013,2034.23465&page=1 - sys: id: 5RnaGufDxeImKGM0msMOs6 created_at: !ruby/object:DateTime 2016-09-12 11:53:52.292000000 Z updated_at: !ruby/object:DateTime 2016-09-12 22:03:55.089000000 Z content_type_id: chapter revision: 6 title_internal: 'Zimbabwe: country, chapter 6' body: |- Traditionally, the themes expressed in Zimbabwean rock art have been identified as the same as those of the San&#124;Bushmen¹ from South Africa and in many cases are undoubtedly related, and provide key hints for their interpretation. However, there are also differences, such as the emphasis given to different animals, the higher presence of trees and plants in Zimbabwe or the smaller presence of trance scenes in the north compared to that of the Drakensberg. Moreover, the lack of ethnographic information for Zimbabwean paintings and their older chronology make it difficult to establish the same type of associations as those made for other areas with more direct connections rock art to known cultures, as happens in South Africa. Although in a minority, rock art of a later chronology can be attributed to Iron Age farmers, characterized by more schematic figures, usually white and painted thickly with the finger or the hand. As is the case in other areas in Central Africa, some of these later depictions are related to rain making and initiation ceremonies. ¹ San&#124;Bushmen is a collective term used to describe the many different hunter-gatherer-fisher groups living in southern Africa who have related languages and cultural traditions. Both 'San' and 'Bushmen' are considered offensive terms by some members of these groups, although others have positively adopted them. - sys: id: 62IspwBATCWA6aAe2Ymya8 created_at: !ruby/object:DateTime 2016-09-12 11:59:32.651000000 Z updated_at: !ruby/object:DateTime 2019-02-12 00:45:17.976000000 Z content_type_id: image revision: 2 image: sys: id: 4sy93JCmHKCso2muMWoOc0 created_at: !ruby/object:DateTime 2016-09-12 11:59:28.407000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:59:28.407000000 Z title: ZIMMSL0120052 description: url: "//images.ctfassets.net/xt8ne4gbbocd/4sy93JCmHKCso2muMWoOc0/ac69dd7a46cecd5c4ca9663931e915ed/ZIMMSL0120052.jpg" caption: Iron Age painting depicting a zebra. Mashonaland, Zimbabwe. 2013,2034.22780 ©TARA/<NAME> col_link: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3775418&partId=1&searchText=2013,2034.22780&page=1 - sys: id: 1ovLRkQ1IMUeuGQMoEaymO created_at: !ruby/object:DateTime 2016-09-12 11:53:51.470000000 Z updated_at: !ruby/object:DateTime 2016-09-12 19:02:39.778000000 Z content_type_id: chapter revision: 3 title: Chronology title_internal: 'Zimbabwe: country, chapter 6' body: "As with much rock art, the dating of Zimbabwe paintings is a challenging subject, although there is a consensus about them being significantly older than those of the Drakensberg and probably dated at before 2,000 years ago. The lack of any type of agriculture-related images in the paintings, which was established by the 1st millennium AD, sets a relative dating for the depictions, while the scarcity of sheep (introduced by the second half of the first millennium BC in the area) points to a time period in which these animals were still uncommon. These hints and the fact that, unlike in other areas there are not historical subjects represented in the paintings, seems to indicate that Zimbabwean paintings are at least 1,000 years old. However, archaeological evidence (Walker 2012: 44) suggests that rock art could be significantly older than that, at least several thousands of years old. \n\n" - sys: id: 6j6wS0WtRmsKI20YK80AKC created_at: !ruby/object:DateTime 2016-09-12 11:59:48.982000000 Z updated_at: !ruby/object:DateTime 2019-02-12 00:46:14.971000000 Z content_type_id: image revision: 3 image: sys: id: 6J08sWPtfOs88AmM20u02u created_at: !ruby/object:DateTime 2016-09-12 12:00:29.957000000 Z updated_at: !ruby/object:DateTime 2016-09-12 12:00:29.957000000 Z title: ZIMMSL0220013 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6J08sWPtfOs88AmM20u02u/a3611f2b43b406427bd87003e5341612/ZIMMSL0220013.jpg" caption: Sable antelope, crocodile or lizard and human figure. Mashonaland, Zimbabwe. 2013,2034.23028 ©TARA/<NAME> col_link: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3775685&partId=1&searchText=2013,2034.23028&page=1 citations: - sys: id: MXZ2L6VLmU2KqsWqcqO2u created_at: !ruby/object:DateTime 2016-09-12 11:54:06.696000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:54:06.696000000 Z content_type_id: citation revision: 1 citation_line: "<NAME>. (1995): The hunter's vision: the prehistoric art of Zimbabwe. British Museum Press, London.\n\n<NAME>. (1987): The painted caves: an introduction to the prehistoric art of Zimbabwe. Modus Publications, Harare. \n\n<NAME>. & <NAME> (1959): Prehistoric rock art of the Federation of Rhodesia & Nyasaland. National Publications Trust, Rhodesia and Nyasaland, Salisbury [Harare].\n\nWalker, N. (2012): The Rock Art of the Matobo Hills, Zimbabwe. Adoranten: 38-59\n" ---<file_sep>/_coll_country/chad/niola-doa.md --- breadcrumbs: - label: Countries url: "../../" - label: Chad url: "../" layout: featured_site contentful: sys: id: 3l1e5Bn0NOggigQsmiGG8q created_at: !ruby/object:DateTime 2015-11-25 16:45:15.719000000 Z updated_at: !ruby/object:DateTime 2015-12-07 20:52:38.130000000 Z content_type_id: featured_site revision: 3 title: Niola Doa, Chad slug: niola-doa chapters: - sys: id: 2HKVwIp55eweW6WcioyIAg created_at: !ruby/object:DateTime 2015-11-25 16:42:21.650000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:42:21.650000000 Z content_type_id: chapter revision: 1 title_internal: 'Chad: featured site, chapter 1' body: The Ennedi Plateau is a mountainous region in the north-eastern corner of Chad, an impressive sandstone massif eroded by wind and temperature changes into series of terraces, gorges, cliffs and outliers. Although it is part of the Sahara, the climate of the Ennedi Plateau is much more suitable for human habitation than most of the desert, with regular rain during summer, wadis (seasonal rivers) flowing once or twice a year, and a relatively large range of flora and fauna – including some of the few remaining populations of Saharan crocodiles west of the Nile. Throughout the caves, canyons and shelters of the Ennedi Plateau, thousands of images – dating from 5000 BC onwards – have been painted and engraved, comprising one of the biggest collections of rock art in the Sahara and characterised by a huge variety of styles and themes. - sys: id: 5fxX9unUx2i8G6Cw0II2Qk created_at: !ruby/object:DateTime 2015-11-25 16:39:08.235000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:39:08.235000000 Z content_type_id: image revision: 1 image: sys: id: 3x13gapfeoswomWyA0gyWS created_at: !ruby/object:DateTime 2015-11-25 16:38:31.707000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:38:31.707000000 Z title: '2013,2034.6150' description: url: "//images.ctfassets.net/xt8ne4gbbocd/3x13gapfeoswomWyA0gyWS/25cf96fec447ce7f0bf93d75ac2efa7f/2013_2034.6150.jpg" caption: View of the second main group of engraved human figures. Ennedi Plateau. 2013,2034.6150 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3637019&partId=1&people=197356&museumno=2013,2034.6150&page=1 - sys: id: 5JEd4uYIEMAQsCKkKIeWIK created_at: !ruby/object:DateTime 2015-11-25 16:42:38.368000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:42:38.368000000 Z content_type_id: chapter revision: 1 title_internal: 'Chad: featured site, chapter 2' body: 'Within this kaleidoscope, a series of engravings have become especially renowned for their singularity and quality: several groups of life-sized human figures depicted following very regular stylistic conventions. They were first reported internationally in the early 1950s; during the following decades more sites were discovered, almost all of them around Wadi Guirchi, and especially near a site known as <NAME>. To date, six sites have been documented, totalling about 40 depictions. Most of the figures were engraved on big, vertical boulders, in groups, although occasionally they appear isolated. They follow a very regular pattern: most of them are life-sized or even bigger and are represented upright facing right or left, with one arm bent upwards holding a stick resting over the neck or shoulder and the other arm stretched downwards. In some cases, the figures have an unidentified, horizontal object placed at the neck, probably an ornament. Interspersed among the bigger figures, there are smaller versions which are slightly different, some of them with the arms in the same position as the others but without sticks, and some facing forwards with hands on hips. In general, figures seem to be naked, although in some cases the smaller figures are depicted with skirts.' - sys: id: 6mkGfHTaJaqiAgiQYQqIYW created_at: !ruby/object:DateTime 2015-11-25 16:40:06.201000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:40:06.201000000 Z content_type_id: image revision: 1 image: sys: id: 1EOAe1GFKQSG2oWYiKSIYI created_at: !ruby/object:DateTime 2015-11-25 16:38:31.745000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:11:12.941000000 Z title: '2013,2034.6164' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3637058&partId=1&searchText=Niola+Doa&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/1EOAe1GFKQSG2oWYiKSIYI/15c83103aa2766992fd90414a29ea01b/2013_2034.6164.jpg" caption: Detail of the first main group of engraved human figures, where the standardized position of the arms and the stick can be observed. Ennedi Plateau. 2013,2034.6164 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3637058&partId=1&people=197356&museumno=2013,2034.6164&page=1 - sys: id: 6HD9yuFPckYYWOaWeQmA4Y created_at: !ruby/object:DateTime 2015-11-25 16:42:56.088000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:42:56.088000000 Z content_type_id: chapter revision: 1 title_internal: 'Chad: featured site, chapter 3' body: Another characteristic feature of these images is their abnormally wide buttocks and thighs, which have been interpreted as steatopygia (a genetic condition resulting in an accumulation of fat in and around the buttocks). Although the best documented examples of steatopygia (both in rock art and contemporary groups) correspond to southern Africa, steatopygic depictions occur elsewhere in North African rock art, with examples in other parts of the Ennedi Plateau, but also in Egypt and Sudan, where they occasionally appear incised in pottery. - sys: id: 3Nd1QIszi8wcWsm4W2CGw8 created_at: !ruby/object:DateTime 2015-11-25 16:40:36.716000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:40:36.716000000 Z content_type_id: image revision: 1 image: sys: id: 4r9HybjNjOaMU2wI44IUWw created_at: !ruby/object:DateTime 2015-11-25 16:38:31.713000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:38:31.713000000 Z title: '2013,2034.6175' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4r9HybjNjOaMU2wI44IUWw/dd398573be19287063d1427947409e9d/2013_2034.6175.jpg" caption: Close-up of figure from the first main group. Note the schematic birds depicted at the waist –the only known example of zoomorphic pattern in these figures. Ennedi Plateau. 2013,2034.6175 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3637066&partId=1&people=197356&museumno=2013,2034.6175&page=1 - sys: id: 5N8CCXZw5OCGiUGMQ8Sw8s created_at: !ruby/object:DateTime 2015-11-25 16:43:21.226000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:43:21.226000000 Z content_type_id: chapter revision: 1 title_internal: 'Chad: featured site, chapter 4' body: |- In addition, almost all the figures are decorated with intricate geometric patterns (straight and wavy lines, squares, meanders and, in one case, schematic birds), which could be interpreted as garments, tattoos, scarifications or body paintings. In some cases, figures appear simply outlined, but these very rare cases were probably left unfinished. The decorative patterns extend to the ears, which are always depicted with geometric designs, and to the head, where these designs could correspond to hairstyles. The decorative richness of the Niola Doa engravings has led to their interpretation as ritual scenes, probably special occasions when body decoration was part of a more complex set of activities with dancing or singing. On some occasions, comparisons have been established between the geometric designs of Niola Doa and different types of body decorations (body painting, scarifications). Scarifications, in particular, have a long tradition within some African cultures and in many cases parallels have been documented between this kind of body decoration and material culture (i.e. pottery, pipes, wood sculptures or clothes). The relative proximity of groups with well-known traditions of scarifications and body painting has led to comparisons which, although suggested, cannot be wholly proved. - sys: id: 2clJsITj8kM8uSE6skaYae created_at: !ruby/object:DateTime 2015-11-25 16:41:04.916000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:41:16.496000000 Z content_type_id: image revision: 2 image: sys: id: 3UndBeXLYs8mK4Y4OWkMU8 created_at: !ruby/object:DateTime 2015-11-25 16:38:31.717000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:38:31.717000000 Z title: Af,B1.25 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3UndBeXLYs8mK4Y4OWkMU8/be1053ea6e513ce14b92a736f6da52cf/Af_B1.25.jpg" caption: 'Scarification on upper back and shoulder of an adult. Sudan, early 20th century. Photograph: © British Museum Af,B1.25' col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=1412934&partId=1&people=197356&museumno=Af,B1.25&page=1 - sys: id: 5fnEMAOYzSs8quyaQiiUUA created_at: !ruby/object:DateTime 2015-11-25 16:43:40.154000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:43:40.154000000 Z content_type_id: chapter revision: 1 title_internal: 'Chad: featured site, chapter 5' body: 'Regarding their chronology, as with most rock art depictions the Niola Doa figures are difficult to date, although they undoubtedly belong to the older periods of Chadian rock art. Some parallels have been made with the Round Head-style figures of the Tassili n’Ajjer (Simonis et al 1994). However, the Round Head figures of Algeria have a very old chronology (up to 9000 years ago), while the rock art at the Ennedi Plateau is assumed to be much newer, up to the 5th or 4th millennium BC. These engravings could, therefore, correspond to what has been called the Archaic Period in this area, although a Pastoral Period chronology has also been proposed. In several other sites around the Ennedi Plateau, similar images have been painted, although whether these images are contemporary with those of Niola Doa or correspond to a different period is unclear. Regardless of their chronology, what is undeniable is the major impact these depictions had on later generations of people living in the area: even now, the engravings at one of the sites are known as the ‘Dancing Maidens’, while the name of Niola Doa means ‘The place of the girls’ in the local language.' citations: - sys: id: 2SoR8lQCF2SkAQAyGIYMc8 created_at: !ruby/object:DateTime 2015-11-25 16:41:51.721000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:41:51.721000000 Z content_type_id: citation revision: 1 citation_line: "<NAME> (1997). *Art rupestre en Ennedi. Looking for rock paintings and engravings in the Ennedi Hills*, Sépia, Saint-Maur.\n \nSimonis, R., <NAME>. and <NAME>. (1994) *<NAME>, ‘il luogo delle fanciulle’ (Ennedi, Ciad)*, Sahara 6, pp.51-63." background_images: - sys: id: 1EOAe1GFKQSG2oWYiKSIYI created_at: !ruby/object:DateTime 2015-11-25 16:38:31.745000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:11:12.941000000 Z title: '2013,2034.6164' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3637058&partId=1&searchText=Niola+Doa&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/1EOAe1GFKQSG2oWYiKSIYI/15c83103aa2766992fd90414a29ea01b/2013_2034.6164.jpg" - sys: id: 4BGLzXecpqKOsuwwiIaM6K created_at: !ruby/object:DateTime 2015-12-07 20:31:44.334000000 Z updated_at: !ruby/object:DateTime 2015-12-07 20:31:44.334000000 Z title: CHANAS0103 description: url: "//images.ctfassets.net/xt8ne4gbbocd/4BGLzXecpqKOsuwwiIaM6K/a4318baa413e590cc6fb087d62888382/CHANAS0103.jpg" ---<file_sep>/_coll_country_information/libya-country-introduction.md --- contentful: sys: id: 5v13g3YNLUGuGwMgSI0e6s created_at: !ruby/object:DateTime 2015-11-26 12:35:54.777000000 Z updated_at: !ruby/object:DateTime 2015-12-07 13:42:46.961000000 Z content_type_id: country_information revision: 2 title: 'Libya: country introduction' chapters: - sys: id: 4WfnZcehd66ieoiASe6Ya2 created_at: !ruby/object:DateTime 2015-11-26 12:29:44.896000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:29:44.896000000 Z content_type_id: chapter revision: 1 title: Introduction title_internal: 'Libya: country, chapter 1' body: 'Rock art occurs in two main areas in Libya: the Tadrart Acacus and the Messak Plateau. The oldest works of rock art, from the Acacus Mountains, are engravings of mammals from the Wild Fauna Period (Early Hunter Period) and could be up to 12,000 years old. Thousands of paintings dating from up to 8,000-9,000 years ago show a diversity of imagery and include scenes of hunting, pastoralism, daily life, dancing and a variety of wild and domesticated animals. The Messak Plateau is home to tens of thousands of engravings, and only a few paintings have been located in this region to date. The area is best known for larger-than-life-size engravings of animals such as elephants, rhino and bubalus (a now extinct buffalo), and some of the most iconic depictions in Saharan rock art, such as the ‘Fighting Cats’ scene.' - sys: id: 4VNJEMI25aagoiEuoUckqg created_at: !ruby/object:DateTime 2015-11-26 12:26:30.631000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:26:30.631000000 Z content_type_id: image revision: 1 image: sys: id: 16a6qAimaaWYqcwqUqMKIm created_at: !ruby/object:DateTime 2015-11-26 12:25:03.860000000 Z updated_at: !ruby/object:DateTime 2017-12-15 14:15:08.336000000 Z title: '2013,2034.420' description: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3580676 url: "//images.ctfassets.net/xt8ne4gbbocd/16a6qAimaaWYqcwqUqMKIm/35056fde196c5ae13894c78ed1b5fe17/2013_2034.420.jpg" caption: Painted rock art with figures and animals from the Acacus Mountains, Fezzan District, Libya. 2013,2034.420 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3580676&partId=1&images=true&people=197356&museumno=2013,2034.420&page=1 - sys: id: 6vqAmqiuY0AIEyUGOcAyQC created_at: !ruby/object:DateTime 2015-11-26 12:30:08.049000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:30:08.049000000 Z content_type_id: chapter revision: 1 title: Geography title_internal: 'Libya: country, chapter 2' body: The fourth largest country in Africa, Libya is located in the Maghreb region of North Africa, bordered on the west by Tunisia and Algeria, Egypt to the east, and the Mediterranean Sea to the north. Except for the narrow strip along the coast, where 80% of the population resides, Libya lies entirely within the Sahara Desert. The main areas of rock art lie in the south-western corner of the country, with the Tadrart Acacus continuing into south-eastern Algeria, where they are simply known as the Tadrart. The Acacus in Libya and the Tadrart in Algeria are now listed and combined as a trans-frontier World Heritage Site by UNESCO, linking these two geographically divided sites into a cultural whole. - sys: id: 1icEVGCcP2Um64EkAs0OAg created_at: !ruby/object:DateTime 2015-11-26 12:27:03.984000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:27:03.984000000 Z content_type_id: image revision: 1 image: sys: id: YbgSaS84Eu0gE8yKEcI48 created_at: !ruby/object:DateTime 2015-11-26 12:25:07.208000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:25:07.208000000 Z title: '2013,2034.1012' description: url: "//images.ctfassets.net/xt8ne4gbbocd/YbgSaS84Eu0gE8yKEcI48/c3cf27b1581df5b3cfed28e53439b4f8/2013_2034.1012.jpg" caption: Tadrart Acacus, Libya. 2013,2034.1012 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3588542&partId=1&images=true&people=197356&museumno=2013,2034.1012&page=1 - sys: id: 2HfBZlyHUA4MCEuqma8QeC created_at: !ruby/object:DateTime 2015-11-26 12:30:46.023000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:30:46.023000000 Z content_type_id: chapter revision: 1 title: Research history title_internal: 'Libya: country, chapter 3' body: The Messak rock art has been known to Europeans since Heinrich Barth’s expedition in 1850, although it was not until 1932 that the engravings were methodically studied by Leo Frobenius. Some initial interpretative hypotheses about the rock art in the Acacus were formulated in the late 1930s by Italian archaeologist <NAME>. Subsequently, the region became the subject of systematic investigation by <NAME>, another Italian archaeologist, who also published the first scientific papers on Libyan rock art in the 1960s. Since then, consistent surveying has continued in this region and stratigraphic excavations of archaeological deposits have established a cultural sequence dating back to the Holocene Period. - sys: id: 5LSSbrA6FqIKi86kuWC0w0 created_at: !ruby/object:DateTime 2015-11-26 12:31:13.353000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:31:13.353000000 Z content_type_id: chapter revision: 1 title: Chronology and early rock art title_internal: 'Libya: country, chapter 4' body: |- Rock art chronology in North Africa is based largely on the combination of stylistic features, superimposition, subject matter and the degree of weathering or patina. While not an exact science, chronological periods are recognisable in the depictions, which generally correspond to climatic and environmental phases. Some of the oldest images are found on the Messak plateau and represent a Sahara that was significantly wetter and more fertile than today, exemplified by representations of large mammals – some of which are aquatic species – incised into the rock faces. The chronology of the Tadrart Acacus during the Holocene has been established more firmly through the excavation and dating of archaeological sites. Based on this evidence, these earliest images may coincide with the first Holocene occupation of the area by specialised hunter-gatherers – known as the 'Early Acacus' Period – which some researchers date to around 11,000 years ago. - sys: id: 3UZhGFp3eosaOSOaUGwEOs created_at: !ruby/object:DateTime 2015-11-26 12:27:31.261000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:27:31.261000000 Z content_type_id: image revision: 1 image: sys: id: 4eOnyF3wVymkGMgOkmQsYm created_at: !ruby/object:DateTime 2015-11-26 12:25:07.169000000 Z updated_at: !ruby/object:DateTime 2017-12-15 14:28:23.158000000 Z title: '2013,2034.3106' description: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3586141 url: "//images.ctfassets.net/xt8ne4gbbocd/4eOnyF3wVymkGMgOkmQsYm/ef9fa1bb02dc7c8ddb0ced9c9fcaa85e/2013_2034.3106.jpg" caption: Engraved image of a crocodile, <NAME>, <NAME>tafet. 2013,2034.3106 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3586141&partId=1&images=true&people=197356&museumno=2013,2034.3106&page=1 - sys: id: 4FFgcDY7xucWsKmsiUQa8E created_at: !ruby/object:DateTime 2015-11-26 12:31:36.221000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:31:36.221000000 Z content_type_id: chapter revision: 1 title: Round Head Period title_internal: 'Libya: country, chapter 5' body: From around 9,000 years ago, the archaeological record in the Acacus changes; sites are larger, featuring more formalised stone structures with heavy grinding equipment and large pots. Subsistence strategies based on hunting and gathering remain, but archaeological evidence suggests the presence of corralling Barbary sheep and the storage of wild cereals. Fragments of grinding stones with traces of colour from the Takarkori rock shelter, dating from between 6,800–5,400 BC, may have been used as palettes for rock or body painting, and have been connected chronologically to the Round Head Period. A large proportion of paintings in this period portray very large figures with round, featureless heads and can often be depicted in ‘floating’ positions; women often have their hands raised, interpreted as postures of supplication. - sys: id: 5zzGfyoQUw00yqkeuYuQ4M created_at: !ruby/object:DateTime 2015-11-26 12:28:01.442000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:28:01.442000000 Z content_type_id: image revision: 1 image: sys: id: 2diYKwS63u0MYs8eC4aesU created_at: !ruby/object:DateTime 2015-11-26 12:25:07.217000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:25:07.217000000 Z title: '2013,2034.899' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2diYKwS63u0MYs8eC4aesU/699e9277d3628340b4719c18a1f57ec4/2013_2034.899.jpg" caption: Round Head Period painting radiocarbon-dated to 8590±390 BP. Uan Tamuat, Acacus Mountains. 2013,2034.899 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3587474&partId=1&images=true&people=197356&museumno=2013,2034.899&page=1 - sys: id: 1UNszL8ap2g6CqEi60aUGC created_at: !ruby/object:DateTime 2015-11-26 12:32:06.214000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:32:06.214000000 Z content_type_id: chapter revision: 1 title: Pastoral Period title_internal: 'Libya: country, chapter 6' body: The introduction of domesticates into the region has been identified archaeologically at around 8,000 years ago, although full exploitation of cattle for dairying is much later at around 6,000 years ago. The development to full pastoral systems in the region is complex and prolonged, so it is challenging to track any changes from the rock art itself, but the painting of large herds must be connected to a full pastoral society. - sys: id: 65IyLhOxpecyEUyiQOaSe4 created_at: !ruby/object:DateTime 2015-11-26 12:28:36.906000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:28:36.906000000 Z content_type_id: image revision: 1 image: sys: id: 3EDRZDxlckISY0Gc0c44QK created_at: !ruby/object:DateTime 2015-11-26 12:25:03.853000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:25:03.853000000 Z title: '2013,2034.734' description: url: "//images.ctfassets.net/xt8ne4gbbocd/3EDRZDxlckISY0Gc0c44QK/9d3d834b088da6e1d5b97a8d01254d82/2013_2034.734.jpg" caption: Herders and cattle, Wadi Tanshal, Acacus Mountains. 2013,2034.734 © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3586048&partId=1&images=true&people=197356&museumno=2013,2034.734&page=1 - sys: id: 1qfXWyJGO0SAIM40qw4aa4 created_at: !ruby/object:DateTime 2015-11-26 12:32:47.033000000 Z updated_at: !ruby/object:DateTime 2017-01-09 14:42:33.634000000 Z content_type_id: chapter revision: 2 title: Horse and Camel Periods title_internal: 'Libya: country, chapter 7' body: |- Historical records have tended to date the introduction of both the horse and the camel in northern Africa rather than the archaeological record. Yet, in terms of rock art research in this region, less attention has been given to these styles; the reason for this may be that the earliest rock art attracted more scholarly consideration than the later depictions. However, their representation certainly demonstrates the changing natural and cultural environment and associated human responses and adaptations. The rock art of Libya is a visual testament to the changing fortunes of this part of the Sahara and the cultural groups who have occupied and navigated the area over thousands of years. The engravings and paintings act as a legacy, tracing the environmental effects of climate change, how people have adapted to that change and the cultural worlds they have created. - sys: id: 33lGJfCTG0iWmcaMS8Miqy created_at: !ruby/object:DateTime 2015-11-26 12:29:09.712000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:29:09.712000000 Z content_type_id: image revision: 1 image: sys: id: 4ShhlHTP4A08k6Ck0WmCme created_at: !ruby/object:DateTime 2015-11-26 12:25:03.861000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:25:03.861000000 Z title: '2013,2034.1450' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4ShhlHTP4A08k6Ck0WmCme/c88441d7390ce9362b6ef2ab371070e9/2013_2034.1450.jpg" caption: Engraved figures on horseback. Awis, Acacus Mountains. 2013,2034.1450 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3592680&partId=1&images=true&people=197356&museumno=2013,2034.1450&page=1 citations: - sys: id: 51iLulV0KkWce0SIkgewo created_at: !ruby/object:DateTime 2015-11-26 12:25:53.864000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:25:53.864000000 Z content_type_id: citation revision: 1 citation_line: |- <NAME>., <NAME>, <NAME>, <NAME>, M.Legrand, <NAME> and <NAME>. 2005. *The Climate-Environment-Society Nexus in the Sahara from Prehistoric Times to the Present Day*. The Journal of North African Studies, Vol. 10, No 3-4, pp. 253-292 <NAME>. and <NAME>. 2001. *African Rock Art*. New York: <NAME> di Lernia, S. 2012. Thoughts on the rock art of the Tadrart Acacus Mts., SW Libya. Adoranten pp. 19-37 <NAME>. 2004. *Sahara: Histoire de l’art rupestre libyen*. Grenoble: J<NAME> Le Quellec, J. 1998. *Art rupestre et préhistoire du Sahara: le Messak Libyen*. Paris: Payot & Rivages ---<file_sep>/_coll_country_information/morocco-country-introduction.md --- contentful: sys: id: 6aJoaZnAAMsKUGGaAmkYIe created_at: !ruby/object:DateTime 2015-11-26 12:42:41.014000000 Z updated_at: !ruby/object:DateTime 2015-12-07 13:41:48.166000000 Z content_type_id: country_information revision: 3 title: 'Morocco: country introduction' chapters: - sys: id: 3PqAqA0X0cKoOKsc2ciiae created_at: !ruby/object:DateTime 2015-11-26 12:43:14.313000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:43:14.313000000 Z content_type_id: chapter revision: 1 title: Introduction title_internal: 'Morocco: country, chapter 1' body: 'Morocco is located at the north-western corner of Africa, in a unique area forming a link between the Mediterranean Sea, the Atlantic Ocean, Europe and Africa. More than 300 rock art sites have been documented in the country so far, mainly located in two areas: the High Atlas Mountains, and the Sahara desert region to the south and east. They comprise mainly engravings, which could be up to 5,000 years old, and include domestic and wild animals, warriors, weapons and scenes of battles and hunting. Antelope and cattle are the most represented animals in Moroccan rock art, although elephants and rhinoceros are common too.' - sys: id: 4htOF13DGEcYas2yAUI6oI created_at: !ruby/object:DateTime 2015-11-26 12:39:31.073000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:39:31.073000000 Z content_type_id: image revision: 1 image: sys: id: 4Jt8P55Z56SkEegOMO6euY created_at: !ruby/object:DateTime 2015-11-26 12:38:42.713000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:38:42.713000000 Z title: '2013,2034.5277' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4Jt8P55Z56SkEegOMO6euY/698f587066b8b4fa30b14b0badf55817/2013_2034.5277.jpg" caption: Engraved rock art of a rhinoceros and an oval shape, from Ait Ouazik, Draa valley, Ouazarzate province, Morocco. 2013,2034.5277 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3603526&partId=1&images=true&people=197356&place=40983&page=2 - sys: id: 2UTNFDWbM4wCMAA2weoWUw created_at: !ruby/object:DateTime 2015-11-26 12:39:56.904000000 Z updated_at: !ruby/object:DateTime 2017-01-06 15:32:33.859000000 Z content_type_id: image revision: 2 image: sys: id: 46fV0mfFKMUYyywY0iUGYK created_at: !ruby/object:DateTime 2015-11-26 12:38:42.713000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:38:42.713000000 Z title: '2013,2034.5654' description: url: "//images.ctfassets.net/xt8ne4gbbocd/46fV0mfFKMUYyywY0iUGYK/5341c01a6cc0cc3baed490b90509e26f/2013_2034.5654.jpg" caption: Southern Morocco landscape, with the Anti-Atlas mountains in the background. 2013,2034.5654 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3605659&partId=1&images=true&people=197356&place=40983&museumno=2013,2034.5654&page=1 - sys: id: 4Dc0V6fW8wWcquEyqkemKK created_at: !ruby/object:DateTime 2015-11-26 12:44:00.368000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:44:00.368000000 Z content_type_id: chapter revision: 1 title: Geography and rock art distribution title_internal: 'Morocco: country, chapter 2' body: Morocco has a very variable geography, with the Atlas Mountains crossing the country from the southwest to the northeast and separating the coastal plains to the west from the Sahara Desert that runs to the east and south. The distribution of rock art in the country is very irregular, with some zones crowded with sites and others almost devoid of depictions. The two main areas of rock art sites are the High Atlas zone and the area to the east and south of the Atlas Mountains. The first area groups more than seven thousand engravings around the Oukaïmeden valley, the Yagour plateau and the Jebel Rat site. They are at high altitude (more than 2000 metres above sea level), and mainly represent weapons, cattle and anthropomorphic figures, along with numerous geometric symbols. - sys: id: 1ZpASVa0UcU4EEagkAm4MQ created_at: !ruby/object:DateTime 2015-11-26 12:40:26.929000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:40:26.929000000 Z content_type_id: image revision: 1 image: sys: id: 6AO1Pff4UowYQMsYU444qS created_at: !ruby/object:DateTime 2015-11-26 12:38:47.431000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:38:47.432000000 Z title: '2013,2034.5866' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6AO1Pff4UowYQMsYU444qS/63b08d76fe217ca864a582ef1b634b1f/2013_2034.5866.jpg" caption: Circular engravings in the valley of Oukaïmeden, High Atlas. 2013,2034.5866 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3613845&partId=1&images=true&people=197356&place=40983&museumno=2013,2034.5866+&page=1 - sys: id: 30E1RdstwIuyse04A6sAUE created_at: !ruby/object:DateTime 2015-11-26 12:44:21.467000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:44:21.467000000 Z content_type_id: chapter revision: 1 title_internal: 'Morocco: country, chapter 3' body: The second main zone, an arid region where the majority of Moroccan rock art sites are situated, contains the oldest engravings in the country, some of them linked to the Saharan styles. The variety of themes depicted is wide, from abundant scenes of riders to isolated animals or complex geometric symbols. This collection comprises about seven hundred images, most of them corresponding to the southern area of Morocco around the Draa valley and the town of Tata, although a High Atlas (Oukaïmeden) site is also included. - sys: id: 1GwI61s72o2AgsESI8kkCI created_at: !ruby/object:DateTime 2015-11-26 12:44:44.525000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:44:44.525000000 Z content_type_id: chapter revision: 1 title: Research history title_internal: 'Morocco: country, chapter 4' body: 'European audiences began studying the rock art in Morocco decades after the study of rock art in Algeria and Libya, with the first news of rock art coming from French and German travellers late in the 19th century. The most significant boost came after the Treaty of Fes in 1912, when the presence of the colonial authorities led indirectly to an increasing knowledge of rock art sites, as Spanish and French officers started to show interest in the engravings. However, it was not until after Moroccan independence in 1956 that systematic research began throughout the country. Since then, archaeological information has progressively grown, although regional syntheses are still scarce: only the Atlas (Malhomme, Rodrigue) and part of southern Morocco (Simoneau) have exhaustive catalogues of sites. The first comprehensive study of Moroccan rock art was made in 2001 (Searight), when for the first time, a global approach to Moroccan rock art areas, themes and chronology was undertaken.' - sys: id: 4Rkp5dL3BegaOyGkisoMwg created_at: !ruby/object:DateTime 2015-11-26 12:45:02.929000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:45:02.929000000 Z content_type_id: chapter revision: 1 title: Themes title_internal: 'Morocco: country, chapter 5' body: 'As in most countries, mammals are the most frequent depictions, especially cattle, horses and different types of antelope. Many other animals, such as giraffes, elephants, rhinoceros, dromedaries or lions are depicted, if more scarcely. The second main theme is human figures, especially in the south of the country, where depictions of Libyan-Berber riders are very common. In the High Atlas area they are usually depicted isolated, surrounded by weapons, which are another big theme in Moroccan rock art: a panoply of these can be seen, including daggers, bows and arrows, spears, shields, axes and halberds.' - sys: id: ZigzuAFbcOgC8IEGkwEQi created_at: !ruby/object:DateTime 2015-11-26 12:40:59.047000000 Z updated_at: !ruby/object:DateTime 2017-01-06 15:36:19.352000000 Z content_type_id: image revision: 2 image: sys: id: 2iKZIRebewsGGQiKiOgQq created_at: !ruby/object:DateTime 2015-11-26 12:38:42.729000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:04:25.512000000 Z title: '2013,2034.5558' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3605427&partId=1&searchText=2013,2034.5558&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/2iKZIRebewsGGQiKiOgQq/7a6ea71bedef21c05b78d13fe9883716/2013_2034.5558.jpg" caption: 'Antelope engravings, Tazina style. 2013,2034.5558 © TARA/<NAME> ' col_link: http://bit.ly/2jbUc4v - sys: id: 2XErL5q2oE6yg4sYSseM8C created_at: !ruby/object:DateTime 2015-11-26 12:45:24.616000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:45:24.616000000 Z content_type_id: chapter revision: 1 title: Chronology title_internal: 'Morocco: country, chapter 6' body: A consensus has yet to be achieved about Moroccan rock art chronology between the supporters of a long chronology, starting around 4000 BC, and those that defend a short one, from 2500 BC onwards. The oldest engravings represented in Moroccan rock art correspond to the Tazina and Pecked Cattle styles, depicting mainly mammals. From the second half of the second millennium BC onwards, depictions of human figures start to appear in the High Atlas, associated with daggers and shields, defining the so-called Dagger/Halberd/Anthropomorph style. During the first millennium BC, Libyan-Berber hunting and battle scenes start to appear in southern Morocco; riders, infantrymen and animals depicted in a very schematic style. The last period of Moroccan rock art, as in the rest of the Sahara, is the so-called Camel Period, characterized by the appearance of dromedaries. - sys: id: 6wwVooOVZSw6SyKQ6eooma created_at: !ruby/object:DateTime 2015-11-26 12:41:29.715000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:41:29.715000000 Z content_type_id: image revision: 1 image: sys: id: 2nR1MWquOoWQiikYooK22Q created_at: !ruby/object:DateTime 2015-11-26 12:38:42.719000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:38:42.719000000 Z title: '2013,2034.5776' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2nR1MWquOoWQiikYooK22Q/3db626f582b41622c7a89a91ff6a6d12/2013_2034.5776.jpg" caption: Pecked cattle-style engravings. 2013,2034.5776 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3619818&partId=1&people=197356&museumno=2013,2034.5776&page=1 citations: - sys: id: UN3bodv8KAWYgsEuyCM2E created_at: !ruby/object:DateTime 2015-11-26 12:42:11.373000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:42:11.373000000 Z content_type_id: citation revision: 1 citation_line: |+ <NAME>. 1959. *Corpus des gravures rupestres du Grand Atlas*, vol. 1. Marrakech, Publications du Service des Antiquités du Maroc 13 Malhomme, J. 1961. *Corpus des gravures rupestres du Grand Atlas*, vol. 2. Marrakech, Publications du Service des Antiquités du Maroc 14 <NAME>. 1999. *L'art rupestre du Haut Atlas Marocain*. Paris, L'Harmattan <NAME>. 1977. *Catalogue des sites rupestres du Sud-Marocain*. Rabat, Ministere d'Etat charge des Affaires Culturelles ---<file_sep>/_coll_country/namibia.md --- contentful: sys: id: 3H6uujNlVmUMacouyayE4K created_at: !ruby/object:DateTime 2015-12-08 11:20:50.406000000 Z updated_at: !ruby/object:DateTime 2018-05-17 16:50:16.809000000 Z content_type_id: country revision: 10 name: Namibia slug: namibia col_url: http://www.britishmuseum.org/research/collection_online/search.aspx?people=197356&place=17546 map_progress: true intro_progress: true image_carousel: - sys: id: 4uVUj08mRGOCkmK64q66MA created_at: !ruby/object:DateTime 2016-09-26 14:46:35.956000000 Z updated_at: !ruby/object:DateTime 2019-02-12 02:01:17.553000000 Z title: '2013,2034.20476' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3730556&partId=1&searchText=NAMDMT0010010&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/4uVUj08mRGOCkmK64q66MA/c1c895d4f72a2260ae166ab9c2148daa/NAMDMT0010010.jpg" - sys: id: 5cgvtbKg2IkkMsWAOeIqi0 created_at: !ruby/object:DateTime 2016-09-26 14:46:58.320000000 Z updated_at: !ruby/object:DateTime 2019-02-12 02:02:14.734000000 Z title: '2013,2034.21988' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3769890&partId=1&searchText=NAMDMO0040022&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/5cgvtbKg2IkkMsWAOeIqi0/4bbb296a22b981820312dd4c63a44073/NAMDMO0040022.jpg" - sys: id: 3HjTzHykAUWMwwMMu4e2AE created_at: !ruby/object:DateTime 2016-09-26 14:47:11.723000000 Z updated_at: !ruby/object:DateTime 2019-02-12 02:03:06.352000000 Z title: '2013,2034.22444' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3770077&partId=1&searchText=NAMSNH0030045&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/3HjTzHykAUWMwwMMu4e2AE/c1518319d2e20eeed9103daab8fe948d/NAMSNH0030045.jpg" - sys: id: 5U3At7fjr2GoEEUycA6m46 created_at: !ruby/object:DateTime 2016-09-26 14:47:19.504000000 Z updated_at: !ruby/object:DateTime 2019-02-12 02:03:51.111000000 Z title: '2013,2034.21922' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3768143&partId=1&searchText=NAMDMO0020013&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/5U3At7fjr2GoEEUycA6m46/ebda186cdcfc4c68f5b0af80470c7d87/NAMDMO0020013.jpg" - sys: id: 47PCoKDlCM6AmwuS6kUkwY created_at: !ruby/object:DateTime 2016-09-26 14:47:27.715000000 Z updated_at: !ruby/object:DateTime 2019-02-12 02:04:53.158000000 Z title: '2013,2034.21288' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3768617&partId=1&searchText=NAMBRH0010005&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/47PCoKDlCM6AmwuS6kUkwY/b834d60849bdb03e767cba886d4edb9d/NAMBRH0010005.jpg" - sys: id: 1EmDxtbZEMmgucUegiQCSE created_at: !ruby/object:DateTime 2016-09-26 14:47:36.968000000 Z updated_at: !ruby/object:DateTime 2019-02-12 02:05:46.811000000 Z title: '2013,2034.22316' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3772012&partId=1&searchText=NAMSNA0020005&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/1EmDxtbZEMmgucUegiQCSE/0e849a3b48819bdffea0079fe8442578/NAMSNA0020005.jpg" featured_site: sys: id: 2KwE2LvwScQG6CmU4eM2uw created_at: !ruby/object:DateTime 2016-09-26 14:56:44.920000000 Z updated_at: !ruby/object:DateTime 2016-09-26 14:56:44.920000000 Z content_type_id: featured_site revision: 1 title: Twyfelfontein, Namibia slug: twyfelfontein chapters: - sys: id: 8m8JIwGB9YyiOoIaeIsS2 created_at: !ruby/object:DateTime 2016-09-26 14:54:19.760000000 Z updated_at: !ruby/object:DateTime 2016-09-26 14:54:19.760000000 Z content_type_id: chapter revision: 1 title_internal: 'Namibia: featured site, chapter 1' body: 'The proliferation of rock engravings at Twyfelfontein | /Ui-//aes in the north-west of central Namibia, forms the largest single grouping of ancient engraved images in southern Africa. Covering about 57 hectares in the core area and home to over 2,000 engravings, the rock art sites are situated near a small but permanent spring. The site was first formally noted by <NAME> in a 1921 report to the Administrator of South West Africa, following a report to him from a surveyor named Volkmann mentioning the engravings, near a spring Volkmann named as Uais (/Ui-//aes= place among rocks or jumping waterhole in Khoekhoegowab, the language of the local Damara people). Later, the land came into the use of farmer <NAME>, whose concern over the survival of the spring led ultimately to its being referred to as Twyfelfontein (‘doubtful spring’ in Afrikaans). In 1963 <NAME> visited the site as part of his work to record rock art sites throughout South West Africa. Scherz documented around 2,500 images in the wider valley area, while a 2005 survey of the core site found 2,075 individual images on 235 separate rock surfaces. ' - sys: id: guZseTx3LaEuKOia8Yuei created_at: !ruby/object:DateTime 2016-09-26 14:54:31.866000000 Z updated_at: !ruby/object:DateTime 2018-05-10 13:43:41.409000000 Z content_type_id: image revision: 2 image: sys: id: 4CdBm63EZaG0uscOGAOimI created_at: !ruby/object:DateTime 2016-09-26 14:54:28.378000000 Z updated_at: !ruby/object:DateTime 2016-09-26 14:54:28.378000000 Z title: '1' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4CdBm63EZaG0uscOGAOimI/e0f06c9a18388056521cd57dc8e096aa/1.jpg" caption: Engravings of animals including giraffe, elephant and rhinoceros showing the surrounding sandstone. Twyfelfontein | /Ui-//aes, Namibia. 2013,2034.23755 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3772379&partId=1&searchText=2013,2034.23755&page=1 - sys: id: 6vS54wtOMwQ0Ce4w2s0Wa0 created_at: !ruby/object:DateTime 2016-09-26 14:54:37.644000000 Z updated_at: !ruby/object:DateTime 2016-09-26 14:54:37.644000000 Z content_type_id: chapter revision: 1 title_internal: 'Namibia: featured site, chapter 2' body: The engravings are found in several loose conglomerations, on sandstone surfaces at the base of a hill scarp within the basin of the ephemeral Huab River, while the few painted panels in the area are found on the underside of sandstone rock overhangs. The engraved images are pecked and/or ground/polished and are made in a variety of styles, with ubiquitous geometric patterns of cross-hatched, looped and linear forms, as well as circles and polished depressions and cupules. In addition there are numerous depictions of animals, ranging in style from more naturalistic to stylised and distorted. Chief among the animal images is the giraffe, which is most numerous. Also common are images of rhinoceroses, zebra, gemsbok antelope and ostriches. There are occasional depictions of cattle but images of human beings are almost absent. Also featured are images of human footprints and animal spoor (hoof and paw prints). - sys: id: 5AxeKFL1lYm4Oqm2wG2eow created_at: !ruby/object:DateTime 2016-09-26 14:54:49.830000000 Z updated_at: !ruby/object:DateTime 2018-05-10 13:44:40.593000000 Z content_type_id: image revision: 2 image: sys: id: 4TZJHdTWc0kgOOEqek4OUs created_at: !ruby/object:DateTime 2016-09-26 14:54:46.709000000 Z updated_at: !ruby/object:DateTime 2016-09-26 14:54:46.709000000 Z title: NAMDMT0010096 description: url: "//images.ctfassets.net/xt8ne4gbbocd/4TZJHdTWc0kgOOEqek4OUs/f55aa0aabccb385ac37c124564f330e7/NAMDMT0010096.jpg" caption: 'Engraved giraffes showing a pecked shading technique. Twyfelfontein | /Ui-//aes, Namibia. 2013,2034.22118 © TARA/<NAME> ' col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3763224&partId=1&searchText=2013,2034.22118&page=1 - sys: id: 6gb3MFviE0sMWWy4s2UQGi created_at: !ruby/object:DateTime 2016-09-26 14:55:05.395000000 Z updated_at: !ruby/object:DateTime 2016-09-30 17:03:01.797000000 Z content_type_id: chapter revision: 3 title_internal: 'Namibia: featured site, chapter 3' body: The figurative images in the engraved art feature several different distinct styles, ranging from very naturalistic outlines of animals such as giraffes and rhinoceroses, through carefully delineated but stylised or distorted renditions of these animals with exaggerated extremities, to very schematic pecked outlines. One particular aspect of style is a form of relief engraving, whereby in some deeply pecked figures' muscle masses are delineated. In others, the infill pecking is graded and sparser in the centre of a figure, giving the impression of shading. A few of the engravings are highly polished. Perhaps most renowned among these is the “dancing kudu” image, a stylised image of a kudu antelope cow rendered atop a flat slab of rock and surrounded by geometric shapes. - sys: id: 5sBqpeSh9uUUosCg2IikCu created_at: !ruby/object:DateTime 2016-09-26 14:55:17.975000000 Z updated_at: !ruby/object:DateTime 2016-09-26 14:55:17.975000000 Z content_type_id: image revision: 1 image: sys: id: XPX1r31GCsUmOaAIIMQy8 created_at: !ruby/object:DateTime 2016-09-26 14:55:14.554000000 Z updated_at: !ruby/object:DateTime 2016-09-26 14:55:14.554000000 Z title: NAMDMT0010076 description: url: "//images.ctfassets.net/xt8ne4gbbocd/XPX1r31GCsUmOaAIIMQy8/c9899e3e4af9424a8bec265ed775b558/NAMDMT0010076.jpg" caption: Highly polished engraved kudu cow with geometric engravings. Twyfelfontein | /Ui-//aes, Namibia. 2013,2034.22098 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3763207&partId=1&searchText=+2013,2034.22098&page=1 - sys: id: 16KMXlLrLAiU2mqWAscMCo created_at: !ruby/object:DateTime 2016-09-26 14:55:26.702000000 Z updated_at: !ruby/object:DateTime 2016-09-26 14:55:26.702000000 Z content_type_id: chapter revision: 1 title_internal: 'Namibia: featured site, chapter 4' body: "It appears that the kudu figure is pregnant and it has been suggested that the choice of this animal may have been made in relation to female initiation practices. This is because the female kudu has a symbolic importance relating to women’s behaviour in the cosmology of some San&#124;Bushman¹ people, traditionally hunter-gatherer people whose ancestors are thought to have made most of southern Africa’s rock paintings and engravings. Other animals known to have symbolic and metaphorical significance to San&#124;Bushman people are also depicted here (giraffe images are most numerous) and these images have been interpreted in the vein of other southern African rock art sites, where images are thought to reflect the experiences of shamans while in a trance state, and may have multiple metaphorical and other cultural meanings. \n\nThe engravings were certainly made in strategic locations and not simply on any available rock surface, with some images having been deliberately made in places that are difficult to reach and to see. The reason for this is unclear, though it has been suggested that such placement might be in relation to the images serving a preparatory function for shamans preparing to enter a trance. Some of the engravings have exaggerated features such as elongated limbs and extremities which may reflect trance experience. One of the engravings appears to depict a lion with pugmarks (paw prints) instead of feet and third at the end of the tail. Each of those in the feet have five instead of the correct four pads and this has been interpreted as meaning that the figure represents a human shaman in trance who has taken on lion form. A similar suggestion has been made regarding the frequent depictions of ostriches (Kinahan, 2006). \ \n\n¹ San&#124;Bushmen is a collective term used to describe the many different hunter-gatherer-fisher groups living in southern Africa who have related languages and cultural traditions. Both 'San' and 'Bushmen' are considered offensive terms by some members of these groups, although others have positively adopted them.\n" - sys: id: 7264zOqUmIAMsgq4QKMgOE created_at: !ruby/object:DateTime 2016-09-26 14:55:40.171000000 Z updated_at: !ruby/object:DateTime 2018-05-10 13:45:12.694000000 Z content_type_id: image revision: 3 image: sys: id: 5qTBuuWKukMoO4kcQYiQWa created_at: !ruby/object:DateTime 2016-09-26 14:47:45.908000000 Z updated_at: !ruby/object:DateTime 2016-09-26 14:47:45.908000000 Z title: NAMDMT0020004 description: url: "//images.ctfassets.net/xt8ne4gbbocd/5qTBuuWKukMoO4kcQYiQWa/9b1c7477a36f65573bca76410c122d3f/NAMDMT0020004.jpg" caption: Painted human figures and an ostrich. Twyfelfontein | /Ui-//aes, Namibia. 2013,2034.22122 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3763727&partId=1&searchText=2013,2034.22122+&page=1 - sys: id: 5wA7wWhUVaEywmwauICIiK created_at: !ruby/object:DateTime 2016-09-26 14:55:53.771000000 Z updated_at: !ruby/object:DateTime 2016-09-26 14:55:53.771000000 Z content_type_id: chapter revision: 1 title_internal: 'Namibia: featured site, chapter 5' body: "Such interpretations are made on the basis that the artists followed the same cultural tradition as the ancestral San&#124;Bushman. The few examples of painted rock art at the site certainly appear to conform to the hunter-gatherer tradition found elsewhere in Namibia. Following this approach, the geometric engraved forms may be interpreted as illustrative of so-called ‘entoptic’ phenomena: shapes and patterns observed when entering a trance state, though an alternative origin for some of the geometrics with particular line and circle motifs has also been suggested. This proposal suggests that they were made by ancestral Khoenkhoen herder people, rather than hunter-gatherers, perhaps in relation to initiation practices. \n\nAttempting to date or sequence the images based on superimpositioning or patina is difficult – superimposition of engravings at the site is rare and a range of patination colours seem to indicate these works having been created over a wide timescale, though it has been noted that a certain style of spoor images sometimes overlie some of the animal figures, indicating that this is a younger tradition. Archaeological fieldwork around the site undertaken in 1968 by <NAME> recovered evidence of occupation including stone tools, worked ostrich eggshell and stone structures. \ The dates recovered from radiocarbon dating ranged widely from c.5,850-180 BP (years before present). The relationship between periods of occupation/site use and the production of rock art is not known, but based on archaeological evidence from around the wider area it is thought that engravings in the styles found at Twyfelfontein range from around 6,000 to around 1,000 years old, though some may be more recent.\n" - sys: id: 6uFGb5fXZ6yEESYw6C4S0C created_at: !ruby/object:DateTime 2016-09-26 14:56:10.408000000 Z updated_at: !ruby/object:DateTime 2016-09-26 14:56:10.408000000 Z content_type_id: image revision: 1 image: sys: id: 6AdC84mjBuuGMsQo2oCCYo created_at: !ruby/object:DateTime 2016-09-26 14:56:05.842000000 Z updated_at: !ruby/object:DateTime 2016-09-26 14:56:05.842000000 Z title: NAMDMT0040014 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6AdC84mjBuuGMsQo2oCCYo/27ba7c664835ba741ab1f4aa43582f1e/NAMDMT0040014.jpg" caption: Engraved panel showing the figures of giraffe and other animals, rows of dots, hoof prints and hand prints showing the range of juxtapositioning and superimposition at the site. Twyfelfontein | /Ui-//aes, Namibia. 2013,2034.22143 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3763757&partId=1&searchText=2013,2034.22143&page=1 - sys: id: 68rfcJmZDaAKGU0WAAysU0 created_at: !ruby/object:DateTime 2016-09-26 14:56:16.915000000 Z updated_at: !ruby/object:DateTime 2016-09-26 14:56:16.915000000 Z content_type_id: chapter revision: 1 title_internal: 'Namibia: featured site, chapter 6' body: 'In 1952 the site was made a National Monument and in 2007 Twyfelfontein | /Ui-//aes was inscribed on the UNESCO World Heritage list. Portions of it are currently open to the public for supervised visits and tours. ' citations: - sys: id: 2IwYq7P2DuyykIC6iwciC0 background_images: - sys: id: 1awSXvy0R0IsIOu2IeqEeK created_at: !ruby/object:DateTime 2016-09-26 14:56:32.301000000 Z updated_at: !ruby/object:DateTime 2016-09-26 14:56:32.301000000 Z title: NAMDMT0040003 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1awSXvy0R0IsIOu2IeqEeK/fccea4215104a2f0d107c85e2bf2abf4/NAMDMT0040003.jpg" - sys: id: 7eyjgnirUkqiwIQmwc8uoe created_at: !ruby/object:DateTime 2016-09-26 14:56:40.370000000 Z updated_at: !ruby/object:DateTime 2016-09-26 14:56:40.370000000 Z title: NAMDMT0010062 description: url: "//images.ctfassets.net/xt8ne4gbbocd/7eyjgnirUkqiwIQmwc8uoe/827acd6affabc436c4124be861493437/NAMDMT0010062.jpg" key_facts: sys: id: 5NZyKdNmfuUCyawIScewak created_at: !ruby/object:DateTime 2016-09-26 14:47:57.283000000 Z updated_at: !ruby/object:DateTime 2016-09-26 16:51:07.480000000 Z content_type_id: country_key_facts revision: 2 title_internal: 'Namibia: key facts' image_count: 1,338 images date_range: Mainly 6,000 BC to the mid-1st millennium AD main_areas: Throughout, with particular concentrations in the West and centre of the country techniques: Mainly brush painting and pecked engraving main_themes: Human figures, large fauna, particularly giraffe and antelope, accoutrements such as personal ornaments and musical instruments, geometric shapes, animal tracks and human hand and foot prints thematic_articles: - sys: id: 570TteJLy8EmE4SYAGKcQw created_at: !ruby/object:DateTime 2017-06-14 17:36:35.946000000 Z updated_at: !ruby/object:DateTime 2017-06-21 13:55:43.874000000 Z content_type_id: thematic revision: 5 title: Rhinos in rock art slug: rhinos-in-rock-art lead_image: sys: id: 4uVUj08mRGOCkmK64q66MA created_at: !ruby/object:DateTime 2016-09-26 14:46:35.956000000 Z updated_at: !ruby/object:DateTime 2019-02-12 02:01:17.553000000 Z title: '2013,2034.20476' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3730556&partId=1&searchText=NAMDMT0010010&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/4uVUj08mRGOCkmK64q66MA/c1c895d4f72a2260ae166ab9c2148daa/NAMDMT0010010.jpg" chapters: - sys: id: 4kAwRERjIIQ4wSkS6y2i8c - sys: id: 2hohzbPqWMU2IGWEeSo2ma - sys: id: 5Ld8vmtLAAGcImkQaySck2 - sys: id: 6jA55SyPksGMQIYmYceMkQ - sys: id: 7gBWq5BdnOYUGm6O4KK4u0 - sys: id: 1LYEwVNEogggeMOcuQUOQW - sys: id: 4dbpdyyr2UAk4yKAomw42I - sys: id: 3VgqyhGcViwkwCoI88W4Ii - sys: id: 4TnBbYK1SEueSCAIemKOcA - sys: id: 4Z8zcElzjOCyO6iOasMuig - sys: id: 2Z9GGCpzCMk4sCKKYsmaU8 - sys: id: 2S3mX9yJfqoMka8QoWUqOE - sys: id: 4KLSIsvlmEMeOsCo8SGOQA - sys: id: 1IlptwbzFmIaSkIWWAqw8U - sys: id: 2Moq7jFKLCc60oamksKUgU - sys: id: 2OfGVIZFbOOm8w6gg6AucI - sys: id: 16oCD2X1nmEYmCOMOm6oWi - sys: id: 2jfI6k6zKAauIS62IC6weq - sys: id: 4k9Uy1dQzmkcIY0kIogeWK - sys: id: 2QFAA8hik82Y4EAIwGSiEs - sys: id: 3ApAq8tLfG6wWaswQEwuaU - sys: id: 4S5oC30EcwEUGEuEO6sa4m - sys: id: 4Y3xOdstSowoYOGOEmW6K6 - sys: id: 6ZjeUWwA5aCEMUiIgukK48 citations: - sys: id: TwHxmivy8uW8mIKAkkMeA background_images: - sys: id: 2ztUAznRiwc0qiE4iUIQGc created_at: !ruby/object:DateTime 2017-05-17 11:44:42.255000000 Z updated_at: !ruby/object:DateTime 2017-05-17 11:44:42.255000000 Z title: Rhinocéros grotte Chauvet description: url: "//images.ctfassets.net/xt8ne4gbbocd/2ztUAznRiwc0qiE4iUIQGc/5958ce98b795f63e5ee49806275209b7/Rhinoc__ros_grotte_Chauvet.jpg" - sys: id: 6m2Q1HCGT6Q2cey00sKGmu created_at: !ruby/object:DateTime 2017-05-17 12:26:24.400000000 Z updated_at: !ruby/object:DateTime 2017-05-17 12:26:24.400000000 Z title: Black Rhino description: url: "//images.ctfassets.net/xt8ne4gbbocd/6m2Q1HCGT6Q2cey00sKGmu/92caad1c13d4bbefe80a5a94aef9844e/Black_Rhino.jpg" - sys: id: 9cRmg60WNGAk6i8Q6WKWm created_at: !ruby/object:DateTime 2018-05-10 14:12:25.736000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:42:15.905000000 Z content_type_id: thematic revision: 2 title: Introduction to rock art in southern Africa slug: rock-art-in-southern-africa lead_image: sys: id: 3cyElw8MaIS24gq8ioCcka created_at: !ruby/object:DateTime 2016-09-12 15:12:39.975000000 Z updated_at: !ruby/object:DateTime 2016-09-12 15:12:39.975000000 Z title: SOADRB0080007 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3cyElw8MaIS24gq8ioCcka/fcea216b7327f325bf27e3cebe49378e/SOADRB0080007.jpg" chapters: - sys: id: 5qv45Cw424smAwqkkg4066 created_at: !ruby/object:DateTime 2016-09-13 13:01:39.329000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:09:20.849000000 Z content_type_id: chapter revision: 6 title_internal: 'Southern Africa: regional, chapter 1' body: |+ The southern African countries of Zimbabwe, South Africa, Lesotho, Swaziland, Mozambique, Botswana and Namibia contain thousands of rock art sites and southern African rock art has been studied extensively. Due to perceived similarities in subject matter, even across great distances, much southern African rock art has been ascribed to hunter-gatherer painters and engravers who appear to have had a shared set of cultural references. These have been linked with beliefs and practices which remain common to modern San&#124;Bushman¹ people, a number of traditional hunter-gatherer groups who continue to live in Southern Africa, principally in Namibia, Botswana and South Africa. There are, however, differences in style and technique between regions, and various rock art traditions are attributed to other cultural groups and their ancestors. As is often the case with rock art, the accurate attribution of authorship, date and motivation is difficult to establish, but the rock art of this region continues to be studied and the richness of the material in terms of subject matter, as well as in the context of the archaeological record, has much to tell us, both about its own provenance and the lives of the people who produced it. - sys: id: r3hNyCQVUcGgGmmCKs0sY created_at: !ruby/object:DateTime 2016-09-13 13:02:04.241000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:09:49.095000000 Z content_type_id: chapter revision: 2 title: Geography and distribution title_internal: 'Southern Africa: regional, chapter 2' - sys: id: 5cKrBogJHiAaCs6mMoyqee created_at: !ruby/object:DateTime 2016-09-13 13:02:27.584000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:10:55.925000000 Z content_type_id: image revision: 4 image: sys: id: 4RBHhRPKHC2s6yWcEeWs0c created_at: !ruby/object:DateTime 2016-09-13 13:02:17.232000000 Z updated_at: !ruby/object:DateTime 2016-09-13 13:02:17.232000000 Z title: ZIMMSL0070001 description: url: "//images.ctfassets.net/xt8ne4gbbocd/4RBHhRPKHC2s6yWcEeWs0c/9d9bc5196cfac491fa099fd737b06e34/ZIMMSL0070001.jpg" caption: Yellow elephant calf painted on the roof of a shelter. Mashonaland, Zimbabwe. 2013,2034.22675 ©TARA/<NAME> col_link: http://bit.ly/2iUgvg0 - sys: id: 69tB5BiRVKG2QQEKoSYw08 created_at: !ruby/object:DateTime 2016-09-13 13:02:41.530000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:11:21.260000000 Z content_type_id: chapter revision: 3 title_internal: 'Southern Africa: regional, chapter 3' body: 'There is wide variation in the physical environments of southern Africa, ranging from the rainforests of Mozambique to the arid Namib Desert of western Namibia, with the climate tending to become drier towards the south and west. The central southern African plateau is divided by the central dip of the Kalahari basin, and bordered by the Great Escarpment, a sharp drop in altitude towards the coast which forms a ridge framing much of southern Africa. The escarpment runs in a rough inland parallel to the coastline, from northern Angola, south around the Cape and up in the east to the border between Zimbabwe and Malawi. Both painted and engraved rock art is found throughout southern Africa, with the type and distribution partially informed by the geographical characteristics of the different regions. Inland areas with exposed boulders, flat rock ‘pavements’ and rocky outcrops tend to feature engraved rock art, whereas paintings are more commonly found in the protective rock shelters of mountainous or hilly areas, often in ranges edging the Great Escarpment. ' - sys: id: 4BJ17cEGyIC6QYSYGAkoaa created_at: !ruby/object:DateTime 2016-09-13 13:03:04.486000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:11:57.877000000 Z content_type_id: image revision: 3 image: sys: id: 1hXbvhDSf2CmOss6ec0CsS created_at: !ruby/object:DateTime 2016-09-13 13:02:59.339000000 Z updated_at: !ruby/object:DateTime 2016-09-13 13:02:59.339000000 Z title: NAMBRG0030001 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1hXbvhDSf2CmOss6ec0CsS/0bb079e491ac899abae435773c74fcf4/NAMBRG0030001.jpg" caption: View out of a rock shelter in the Brandberg, Namibia. 2013,2034.20452 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3729901 - sys: id: 499lI34cAE6KAgKU4mkcqq created_at: !ruby/object:DateTime 2016-09-13 13:03:14.736000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:12:17.831000000 Z content_type_id: chapter revision: 5 title: Types of rock art title_internal: 'Southern Africa: regional, chapter 4' body: "Rock art of the type associated with hunter-gatherers is perhaps the most widely distributed rock art tradition in southern Africa, with numerous known examples in South Africa, Namibia and Zimbabwe, but also with examples found in Botswana and Mozambique. This tradition comprises paintings and engravings, with both techniques featuring images of animals and people. The type and composition varies from region to region. For example, rock art sites of the southern Drakensberg and Maloti mountains in South Africa and Lesotho contain a higher proportion of images of eland antelope, while those in Namibia in turn feature more giraffes. There are also regional variations in style and colour: in some sites and areas paintings are polychrome (multi-coloured) while in others they are not.\n\nDifferences also occur in composition between painting and engraving sites, with paintings more likely to feature multiple images on a single surface, often interacting with one another, while engraving sites more often include isolated images on individual rocks and boulders. \ However, there are commonalities in both imagery and style, with paintings throughout southern Africa often including depictions of people, particularly in procession and carrying items such as bows and arrows. Also heavily featured in both paintings and engravings are animals, in particular large ungulates which are often naturalistically depicted, sometimes in great detail. Additionally, images may include people and animals which appear to have the features of several species and are harder to identify. Some hunter-gatherer type paintings are described as ‘fine-line’ paintings because of the delicacy of their rendering with a thin brush. \n" - sys: id: 4NfdPoVtFKaM6K4w8I8ckg created_at: !ruby/object:DateTime 2016-09-13 13:22:13.102000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:12:40.860000000 Z content_type_id: image revision: 4 image: sys: id: 20oHYa0oEcSEMOyM8IcCcO created_at: !ruby/object:DateTime 2016-09-13 13:22:08.653000000 Z updated_at: !ruby/object:DateTime 2016-09-13 13:22:08.653000000 Z title: NAMBRT0010002 description: url: "//images.ctfassets.net/xt8ne4gbbocd/20oHYa0oEcSEMOyM8IcCcO/67a69f9814e8ec994003bfacff0962cc/NAMBRT0010002.jpg" caption: " Fine-line paintings of giraffes and line patterns, Brandberg, Namibia. \ It is thought that giraffes may have been associated with rain in local belief systems. 2013,2034.21324 © TARA/<NAME>" col_link: http://bit.ly/2j9778d - sys: id: 2nqpXdHTeoyKakEEOMUSA0 created_at: !ruby/object:DateTime 2016-09-13 13:03:40.877000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:13:26.231000000 Z content_type_id: chapter revision: 9 title_internal: 'Southern Africa: regional, chapter 5' body: "Hunter-gatherer rock paintings are found in particular concentrations in the Drakensberg-Maloti and Cape Fold Mountains in South Africa and Lesotho, the Brandberg and Erongo Mountains in Namibia and the Matobo Hills in Zimbabwe, while engraving sites are found throughout the interior, often near water courses. \n\nA different form of rock painting from the hunter-gatherer type, found mainly in the north-eastern portion of southern Africa is that of the ‘late whites’. Paintings in this tradition are so-called because they are usually associated with Bantu language-speaking Iron Age farming communities who entered the area from the north from around 2,000 years ago and many of these images are thought to have been painted later than some of the older hunter-gatherer paintings. ‘Late white’ paintings take many forms, but have generally been applied with a finger rather than a brush, and as the name suggests, are largely white in colour. These images represent animals, people and geometric shapes, often in quite schematic forms, in contrast to the generally more naturalistic depictions of the hunter-gatherer art. \n\nSometimes ‘late white’ art images relate to dateable events or depict objects and scenes which could only have taken place following European settlement, such as trains. \ Other forms of southern African rock art also depict European people and objects. These include images from the Western Cape in South Africa of a sailing ship, estimated to date from after the mid-17th century, as well as painted and engraved imagery from throughout South Africa showing people on horseback with firearms. Such images are sometimes termed ‘contact art’ as their subject matter demonstrates that they follow the period of first contact between European and indigenous people. \n" - sys: id: 1NrA6Z43fWIgwGoicy2Mw2 created_at: !ruby/object:DateTime 2016-09-13 13:03:57.014000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:13:43.550000000 Z content_type_id: image revision: 2 image: sys: id: 6QHTRqNGXmWic6K2cQU8EA created_at: !ruby/object:DateTime 2016-09-13 13:03:52.426000000 Z updated_at: !ruby/object:DateTime 2016-09-13 13:03:52.426000000 Z title: SOASWC0110006 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6QHTRqNGXmWic6K2cQU8EA/3d924964d904e34e6711c6224a7429e6/SOASWC0110006.jpg" caption: Painting of a ship from the south Western Cape in South Africa. 2013,2034.19495 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3730142&partId=1&searchText=2013%2c2034.19495&page=1 - sys: id: 4JVHOgrOyAAI8GWAuoyGY created_at: !ruby/object:DateTime 2016-09-13 13:24:14.217000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:17:20.511000000 Z content_type_id: chapter revision: 5 title_internal: 'Southern Africa: regional, chapter 6' body: "This kind of imagery is found in a variety of styles, and some of those producing ‘contact’ images in the Cape may have been people of Khoekhoen heritage. The Khoekhoen were traditionally cattle and sheep herders, culturally related to modern Nama people and more loosely to San&#124;Bushman hunter-gatherers. \ A distinct tradition of rock art has been suggested to be of ancestral Khoekhoen origin. This art is predominantly geometric in form, with a particular focus on circle and dotted motifs, and engravings in this style are often found near watercourses. \n" - sys: id: 3zUtkjM57Omyko6Q2O0YMG created_at: !ruby/object:DateTime 2016-09-13 13:04:05.564000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:17:47.538000000 Z content_type_id: chapter revision: 6 title: History of research title_internal: 'Southern Africa: regional, chapter 7' body: 'The first known reports of African rock art outside of the continent appear to come from the Bishop of Mozambique, who in 1721 reported sightings of paintings on rocks to the Royal Academy of History in Lisbon. Following this, reports, copies and publications of rock art from throughout modern South Africa were made with increasing frequency by officials and explorers. From the mid-19th century onwards, rock art from present-day Namibia, Zimbabwe and Botswana began to be documented, and during the first few decades of the twentieth century global public interest in the art was piqued by a series of illustrated publications. The hunter-gatherer rock art in particular had a strong aesthetic and academic appeal to western audiences, and reports, photographs and copied images attracted the attention of prominent figures in archaeology and ethnology such as <NAME>, <NAME> and the <NAME>, researchers whose interest in rock art worldwide let them to visit and write about southern African rock art sites. A further intensification of archaeological and anthropological research and recording in the 1950s-70s, resulted in new insights into the interpretations and attributions for southern African rock art. Rock art research continues throughout the area today. ' - sys: id: 5bPZwsgp3qOGkogYuCIQEs created_at: !ruby/object:DateTime 2016-09-13 13:04:30.652000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:18:07.313000000 Z content_type_id: image revision: 3 image: sys: id: 3BLPJ6SPMcccCE2qIG4eQG created_at: !ruby/object:DateTime 2016-09-13 13:04:26.508000000 Z updated_at: !ruby/object:DateTime 2016-09-13 13:04:26.508000000 Z title: BOTTSD0300015 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3BLPJ6SPMcccCE2qIG4eQG/639dd24028612b985042ea65536eef2e/BOTTSD0300015.jpg" caption: Rhinoceros and cattle painting, <NAME>, Botswana. 2013,2034.20848 © TARA/<NAME> col_link: http://bit.ly/2i5xfUJ - sys: id: 1QaeG3pF1KOEaooucoMUeE created_at: !ruby/object:DateTime 2016-09-13 13:04:37.305000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:18:34.546000000 Z content_type_id: chapter revision: 4 title: Interpretation title_internal: 'Southern Africa: regional, chapter 8' body: Rather than showing scenes from daily life, as was once assumed, it is now usually accepted that hunter-gatherer art in southern Africa shows images and motifs of spiritual and cultural importance. In particular, it is thought that some images reflect trance visions of San&#124;Bushman spiritual leaders, or shamans, during which they are considered to enter the world of spirits, where they are held to perform tasks for themselves and their communities, such as healing the sick or encouraging rain. This interpretation, which has been widely accepted, explains certain features of the art, for example the predominance of certain animals like eland antelope (due to their special cultural significance) and themes such as dot patterns and zigzag lines (interpreted as geometric patterns that shamans may see upon entering a trance state). - sys: id: 1YgT9SlSNeU8C6Cm62602E created_at: !ruby/object:DateTime 2016-09-13 13:04:53.447000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:19:08.779000000 Z content_type_id: image revision: 2 image: sys: id: 5Zk1QhSjEAOy8U6kK4yS4c created_at: !ruby/object:DateTime 2016-09-13 13:04:48.941000000 Z updated_at: !ruby/object:DateTime 2016-09-13 13:04:48.941000000 Z title: SOADRB0030002 description: url: "//images.ctfassets.net/xt8ne4gbbocd/5Zk1QhSjEAOy8U6kK4yS4c/5896c3d088678257f9acd01bd59c4b26/SOADRB0030002.jpg" caption: 'Painting of an eland and an ambiguous figure in the Drakensberg, South Africa. Both the eland and this kind of human-like figure are thought to have had symbolic associations with beliefs about gender and power. 2013,2034.18187© TARA/<NAME> ' col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3738250&partId=1&searchText=2013,2034.18187&page=1 - sys: id: 5byxQopdNCqEC2kCa0OqCm created_at: !ruby/object:DateTime 2016-09-13 13:05:00.899000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:19:37.565000000 Z content_type_id: chapter revision: 4 title_internal: 'Southern Africa: regional, chapter 9' body: "The rock art attributed to ancestral San&#124;Bushman hunter-gatherers has many varied motifs, some of which may also relate to specific themes such as initiation or rainmaking (indeed within its cultural context one image may have several significances). San&#124;Bushman informants in the 19th century told researchers that certain ambiguously shaped animals in the rock art repertoire represented animals related to water. Images such as these are known to researchers as 'rain animals' and it has been suggested that certain images could reflect—or prompt—the shaman's attempt to control rainfall. Some 'late white' art has also been proposed to have associations with rainmaking practices, and indeed the proximity of some geometric rock art images, proposed to be of possible Khoekhoen origin, to watercourses appears to emphasise the practical and spiritual significance of water among historical southern African communities. It has also been proposed that some forms of geometric art attributed to Khoekhoen people may be linked by tradition and motif to the schematic art traditions of central Africa, themselves attributed to hunter-gatherers and possibly made in connection with beliefs about water and fertility. Much in the “late white” corpus of paintings appears to be connected to initiation practices, part of a larger set of connected traditions extending north as far as Kenya. \n\nThe long time periods, cultural connections, and movements involved can make attribution difficult. For example, the idiosyncratic rock paintings of Tsodilo Hills in Botswana which appear to have similarities with the hunter-gatherer style include images of domesticates and may have been the work of herders. More localised traditions, such as that of engravings in north-western South Africa representing the homesteads of ancestral Nguni or Sotho-Tswana language speakers, or the focus on engravings of animal tracks found in Namibia, demonstrate more specific regional significances. Research continues and in recent decades, researchers, focusing on studying individual sites and sets of sites within the landscape and the local historical context, have discussed how their placement and subject matter may reflect the shifting balances of power, and changes in their communities over time. \n" - sys: id: L9AkWhM1WwUKWC4MQ4iMe created_at: !ruby/object:DateTime 2016-09-13 13:05:15.123000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:21:01.026000000 Z content_type_id: image revision: 5 image: sys: id: ETDpJFg6beKyyOmQGCsKI created_at: !ruby/object:DateTime 2016-09-13 13:05:11.473000000 Z updated_at: !ruby/object:DateTime 2016-09-13 13:05:11.473000000 Z title: NAMSNH0030006 description: url: "//images.ctfassets.net/xt8ne4gbbocd/ETDpJFg6beKyyOmQGCsKI/3dabb2ba8a3abaa559a6652eb10ea1eb/NAMSNH0030006.jpg" caption: 'Geometric rock engravings of the type suggested by some to be the work of Khoekhoen pastoralists and their ancestors. 2013,2034.22405 © TARA/David Coulson ' col_link: http://bit.ly/2iVIIoL - sys: id: ayvCEQLjk4uUk8oKikGYw created_at: !ruby/object:DateTime 2016-09-13 13:05:22.665000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:21:16.059000000 Z content_type_id: chapter revision: 6 title: Dating title_internal: 'Southern Africa: regional, chapter 10' body: "Although dating rock art is always difficult, the study of rock art sites from southern Africa has benefitted from archaeological study and excavations at rock art sites have sometimes revealed useful information for ascribing dates. Some of the oldest reliably dated examples of rock art in the world have been found in the region, with the most well-known examples probably being the painted plaques from Apollo 11 Cave in Namibia, dated to around 30,000 years ago. A portion of an engraved animal found in South Africa’s Northern Cape is estimated to be 10,200 years old and painted spalls from shelter walls in Zimbabwe have been dated to 12,000 years ago or older. However, it is thought that the majority of existing rock art was made more recently. \ As ever, subject matter is also helpful in ascribing maximum date ranges. \ We know, for example,that images of domestic animals are probably less than 2,000 years old. The condition of the art may also help to establish relative ages, particularly with regards to engravings, which may be in some cases be categorised by the discolouration of the patina that darkens them over time. \n\nThe multiplicity of rock art sites throughout southern Africa form a major component of southern Africa’s archaeological record, with many interesting clues about the lives of past inhabitants and, in some cases, continuing religious and cultural importance for contemporary communities. \ Many sites are open to the public, affording visitors the unique experience of viewing rock art in situ. Unfortunately, the exposed nature of rock art in the field leaves it open to potential damage from the environment and vandalism. \ Many major rock art sites in southern Africa are protected by law in their respective countries and the Maloti-Drakensberg Park in South Africa and Lesotho, Twyfelfontein/ǀUi-ǁAis in Namibia, Tsodilo Hills in Botswana and the Matobo Hills in Zimbabwe are all inscribed on the UNESCO World Heritage list. \n" - sys: id: 3Kjcm7V1dYoCuyaqKga0GM created_at: !ruby/object:DateTime 2016-09-13 13:05:38.418000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:25:17.372000000 Z content_type_id: image revision: 2 image: sys: id: 58V5qef3pmMGu2aUW4mSQU created_at: !ruby/object:DateTime 2016-09-13 13:05:34.865000000 Z updated_at: !ruby/object:DateTime 2016-09-13 13:05:34.865000000 Z title: NAMDME0080012 description: url: "//images.ctfassets.net/xt8ne4gbbocd/58V5qef3pmMGu2aUW4mSQU/dec59cd8209d3d04b13447e9c985574a/NAMDME0080012.jpg" caption: Engraved human footprints, Erongo Region, Namibia. 2013,2034.20457 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3729958&partId=1&searchText=2013,2034.20457+&page=1 - sys: id: 1kwt8c4P0gSkYOq8CO0ucq created_at: !ruby/object:DateTime 2016-09-13 13:28:16.189000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:25:44.294000000 Z content_type_id: chapter revision: 2 title_internal: 'Southern Africa: regional, chapter 11' body: "¹ San&#124;Bushmen is a collective term used to describe the many different hunter-gatherer-fisher groups living in southern Africa who have related languages and cultural traditions. Both 'San' and 'Bushmen' are considered offensive terms by some members of these groups, although others have positively adopted them." citations: - sys: id: 6GlTdq2WbeIQ6UoeOeUM84 created_at: !ruby/object:DateTime 2016-10-17 10:45:36.418000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:39:37.963000000 Z content_type_id: citation revision: 2 citation_line: |+ <NAME>., <NAME>. and <NAME>. 2010. Tsodilo Hills: Copper Bracelet of the Kalahari. East Lansing: Michigan State University Press. <NAME>. 1995. The Hunter's Vision: The Prehistoric Art of Zimbabwe. London: British Museum Press. <NAME>. 1981. Believing and Seeing: Symbolic Meanings in San&#124;BushmanRock Paintings. Johannesburg: University of Witwatersrand Press <NAME>. 1995. 'Neglected Rock Art: The Rock Engravings of Agriculturist Communities in South Africa'. South African Archaeological Bulletin. Vol. 50 No. 162. pp. 132.142. <NAME>. 1989. Rock Paintings of the Upper Brandberg. vols. I-VI. Köln: Heinrich-Barth-Institut <NAME>. & <NAME>. 2008. 'Beyond Development - Global Visions and Local Adaptations of a Contested Concept' in Limpricht, C., & M. Biesele (eds) Heritage and Cultures in modern Namibia: in-depth views of the country: a TUCSIN Festschrift. Goettingen : Klaus Hess Publishers. pp 37:46. <NAME>. 2013. 'Rock Art Research in Africa' in Mitchell, P. and P. Lane (eds), The Oxford Handbook of African Archaeology. Oxford, Oxford University Press. <NAME>. & <NAME>. 2004. 'Taking Stock: Identifying Khoekhoen Herder Rock Art in Southern Africa'. Current Anthropology Vol. 45, No. 4. pp 499-52. background_images: - sys: id: 6oQGgfcXZYWGaeaiyS44oO created_at: !ruby/object:DateTime 2016-09-13 13:05:47.458000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:41:12.556000000 Z title: ZIMMSL0120015.tiff description: url: "//images.ctfassets.net/xt8ne4gbbocd/6oQGgfcXZYWGaeaiyS44oO/c8bc0d9d1ceee0d23517a1bc68276b24/ZIMMSL0120015.tiff.jpg" - sys: id: 69ouDCLqDKo4EQWa6QCECi created_at: !ruby/object:DateTime 2016-09-13 13:05:55.993000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:41:44.910000000 Z title: SOAEFS0030008 description: url: "//images.ctfassets.net/xt8ne4gbbocd/69ouDCLqDKo4EQWa6QCECi/9c5da3bf755188e90003a9bc55550f6f/SOAEFS0030008.jpg" country_introduction: sys: id: 8t9OseGfHqIgcUCao2ysq created_at: !ruby/object:DateTime 2016-09-26 14:54:01.738000000 Z updated_at: !ruby/object:DateTime 2016-10-17 15:39:27.185000000 Z content_type_id: country_information revision: 2 title: 'Namibia: country introduction' chapters: - sys: id: 4UiO2GnKUMUwso4aYMqCaG created_at: !ruby/object:DateTime 2016-09-26 14:48:35.037000000 Z updated_at: !ruby/object:DateTime 2018-05-09 16:46:01.299000000 Z content_type_id: chapter revision: 3 title: Introduction title_internal: 'Namibia: country, chapter 1' body: 'Namibia is home to over 1,200 rock art sites countrywide. Most of these sites appear to correspond with the hunter-gatherer art tradition found throughout southern Africa, with certain specific regional features. ' - sys: id: 1dABVOGavUAI6goAY8miaA created_at: !ruby/object:DateTime 2016-10-17 15:38:31.464000000 Z updated_at: !ruby/object:DateTime 2018-09-19 14:58:53.570000000 Z content_type_id: chapter revision: 2 title: Geography and rock art distribution title_internal: 'Namibia: country, chapter 2' - sys: id: 5gSXylxGD6eO20EyeOIQSY created_at: !ruby/object:DateTime 2016-09-26 14:49:11.461000000 Z updated_at: !ruby/object:DateTime 2016-09-26 14:49:11.461000000 Z content_type_id: image revision: 1 image: sys: id: 3Xk6O4MMsgEYY0WcaiCYqs created_at: !ruby/object:DateTime 2016-09-26 14:49:06.642000000 Z updated_at: !ruby/object:DateTime 2016-09-26 14:49:06.642000000 Z title: NAMDMB0010001 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3Xk6O4MMsgEYY0WcaiCYqs/fb7f2a4378bb27d56354a99c94ee7624/NAMDMB0010001.jpg" caption: View of the Brandberg, Namibia. 2013,2034.20454 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3729934&partId=1&people=197356&place=17546&museumno=2013,2034.20454+&page=1 - sys: id: 3KVc3so4EMwom64W8mGmUs created_at: !ruby/object:DateTime 2016-09-26 14:49:17.497000000 Z updated_at: !ruby/object:DateTime 2018-05-09 16:51:45.252000000 Z content_type_id: chapter revision: 5 title_internal: 'Namibia: country, chapter 3' body: 'Namibia covers an area of around 815,625km² in the south-west of Africa, bordering Angola and Zambia in the north, Botswana in the east, and South Africa to the south. Namibia’s climate is mainly arid or semi-arid, with the dry environment of the Namib desert covering the entirety of the country’s coastline in the west and bordered by southern Africa’s Great Escarpment, a rocky ridge at the edge of the central plateau running in rough parallel to the coastline. East of the ridge, the central plateau stretches towards the edge of the basin enclosing the western portion of the Kalahari, a semi-desert environment extending into Botswana and South Africa. ' - sys: id: 1uThiykyCAYWWieyOKciQi created_at: !ruby/object:DateTime 2016-09-26 14:49:30.621000000 Z updated_at: !ruby/object:DateTime 2018-05-09 16:53:37.343000000 Z content_type_id: image revision: 2 image: sys: id: 62AXX05gE8yACQgOgW0kqO created_at: !ruby/object:DateTime 2016-09-26 14:49:26.962000000 Z updated_at: !ruby/object:DateTime 2016-09-26 14:49:26.962000000 Z title: NAMDME0040007 description: url: "//images.ctfassets.net/xt8ne4gbbocd/62AXX05gE8yACQgOgW0kqO/0571a6030a608d5c7390cb521681a48e/NAMDME0040007.jpg" caption: Painted tableau showing giraffe, springbok, human figures and a tree. Omandumba, Namibia. 2013,2034.21544 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3767635&partId=1&searchText=2013,2034.21544&page=1 - sys: id: 3v5501rl28sYOwW2Cm8ga2 created_at: !ruby/object:DateTime 2016-09-26 14:49:37.812000000 Z updated_at: !ruby/object:DateTime 2018-05-09 16:57:17.099000000 Z content_type_id: chapter revision: 9 title_internal: 'Namibia: country, chapter 4' body: "Rock art is found across the country from the southern border almost to the northern border, although rock art sites are scarce in the far north. \ The majority of known rock art sites are found in the rocky and mountainous areas forming the escarpment edge in the west of the country. Particular concentrations of rock art are found in the west-centre of the country, north of the edge of the Namib’s coastal sand sea. Namibia’s most well-known rock art locales are clustered in this area, among them the Brandberg (also known as Dâures) and Erongo mountains and the Spitzkoppe peaks, as well as the well-known engraved rock art complex at Twyfelfontein | /Ui-//aes. \n\nAt approximately 20km wide, the almost circular granitic intrusion of the Brandberg contains Namibia’s highest point at over 2,500 ft., containing around 1,000 rock art sites and around 50,000 individual figures recorded. These include both paintings and engravings but paintings form the majority. The Erongo mountains, a similar but less compact formation around 120km to the south-east, contain a further 80 sites and 50km to the west of this, the Spitzkoppe peaks, a group of granite inselbergs, has a smaller concentration of known sites with 37 so far recorded. \ Painting sites are most often found on vertical surfaces in rock shelters or the sides of granitic boulders, while engravings may survive in more exposed environments such as on boulders, often dolerite or sandstone. \n\nThe most well-known of the engraving sites is that of Twyfelfontein | /Ui-//aes, around 50 km north of the Brandberg. The rock art complex here is dominated by collections of engraved images, though some paintings are also present. With well over 2,000 individual images, the Twyfelfontein engravings form the largest known discrete collection of engraved rock art in southern Africa. \n" - sys: id: 18lzX7RJb8skMkC0ousqMY created_at: !ruby/object:DateTime 2016-09-26 14:49:45.248000000 Z updated_at: !ruby/object:DateTime 2018-05-09 16:56:06.499000000 Z content_type_id: chapter revision: 5 title: History of research title_internal: 'Namibia: country, chapter 5' body: 'The first published mention of rock art in south-western Africa may be that of <NAME> who mentioned “A strange tale of a rock in which the tracks of…animals are distinctly visible” in his 1856 book Lake Ngami. Further reports came in the 1870s when the Reverend <NAME> published an article in a South African periodical reporting rock art in the Erongo Mountains, while Commissioner William Coates Palgrave made a report of paintings near Dassiesfontein, along with some the earliest known photographs of rock art in Africa. European public awareness of rock art from the region in Europe was spurred by the January 1910 publication of an article by Oberleutnant <NAME> featuring images from various sites in a German magazine. The first monograph on the rock art of the area then known as South West Africa was published in 1930 (Obermaier & Kühn, 1930), following further reports by officials, including the explorer and geographer <NAME>, who in a 1921 report first noted the existence of engravings at Twyfelfontein. ' - sys: id: 6oW0rqforuI6AQIUaMu4Ks created_at: !ruby/object:DateTime 2016-09-26 14:50:03.966000000 Z updated_at: !ruby/object:DateTime 2016-09-26 14:50:03.966000000 Z content_type_id: image revision: 1 image: sys: id: 4nbVLA22Y0Uw06ICSeGYQm created_at: !ruby/object:DateTime 2016-09-26 14:49:57.411000000 Z updated_at: !ruby/object:DateTime 2016-09-26 14:49:57.411000000 Z title: NAMDMT0010073 description: url: "//images.ctfassets.net/xt8ne4gbbocd/4nbVLA22Y0Uw06ICSeGYQm/b5c26da0464ec9a64fdde76edcc0fa3e/NAMDMT0010073.jpg" caption: Engraved kudu cow with geometric engravings. Twyfelfontein | /Ui-//aes, Namibia. 2013,2034.22095 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3763210&partId=1&searchText=2013,2034.22095&page=1 - sys: id: 25d3VoqJDWy2OGSEM2a8so created_at: !ruby/object:DateTime 2016-09-26 14:50:14.861000000 Z updated_at: !ruby/object:DateTime 2016-09-26 16:36:47.346000000 Z content_type_id: chapter revision: 2 title_internal: 'Namibia: country, chapter 6' body: "During the course of an earlier expedition, Maack had stumbled upon a singular painting in a Brandberg rock shelter. This image came to be well-known as the ‘White Lady’ of the Brandberg, after the renowned rock art researcher the <NAME>, who saw Maack’s copy of it and took a keen interest in the image. Eventually Breuil published a lavishly illustrated volume on the White Lady in 1955, which made it one of the most famous rock painting images in the world. During the 1940s and 50s Breuil also explored and published on rock art sites elsewhere in the Brandberg and Erongo mountains. \n\nErnst Scherz, who had acted as a guide for Breuil, would go on to conduct extensive documentation work throughout the country as part of the comprehensive research project investigating the archaeology of South West Africa run by the University of Cologne and sponsored by the Deutschen Forschungsgemeinschaft. Beginning in 1963, this resulted in the publications of Scherz’s three-volume opus *Felsbilder in Sudwest-Afrika* in 1970, 1975 and 1986, containing site by site descriptions and classifications of painting and engraving sites throughout modern Namibia, along with discussion of theme and context. The Cologne programme also supported the work of several other researchers, including the designer and artist Harald Pager, whose meticulous work recording rock paintings in South Africa’s Drakensberg had already gained him recognition in the field of rock art research. From 1977, Pager began a seven year project of recording painted rock art sites in the Brandberg, documenting around 43,000 individual images. Pager’s corpus has been organised by <NAME> and published posthumously in the six-volume *Rock Paintings of the Upper Brandberg*, as a result of which the Brandberg is one of the most comprehensively documented rock art regions on earth.\n" - sys: id: pt0EDsK0SWU2Cg2EkuQKw created_at: !ruby/object:DateTime 2016-09-26 14:50:38.544000000 Z updated_at: !ruby/object:DateTime 2018-05-09 16:59:58.758000000 Z content_type_id: image revision: 2 image: sys: id: 4ZB32q4diwyQMIaOomeQOg created_at: !ruby/object:DateTime 2016-09-26 14:50:26.431000000 Z updated_at: !ruby/object:DateTime 2016-09-26 14:50:26.431000000 Z title: NAMDMB0010016 description: url: "//images.ctfassets.net/xt8ne4gbbocd/4ZB32q4diwyQMIaOomeQOg/5dd2b69e51fa5dd4bcd8f24c1cbe6df2/NAMDMB0010016.jpg" caption: The ‘White Lady’ painting, showing human figures, gemsbok antelope and a therianthrope (part-human, part-animal figure). <NAME>, Brandberg, Namibia. 2013,2034.21340 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3771011&partId=1&searchText=2013,2034.21340&page=1 - sys: id: 2Oc2SJpN9msEGCM0iWUGsw created_at: !ruby/object:DateTime 2016-09-26 14:50:47.116000000 Z updated_at: !ruby/object:DateTime 2018-05-09 16:48:16.058000000 Z content_type_id: chapter revision: 2 title_internal: 'Namibia: country, chapter 7' body: 'The Cologne programme also sponsored the excavation work of archaeologist <NAME>, who between 1968 and 1970 worked at numerous sites investigating Late Stone Age activity in the country. During this time, Wendt recovered seven slabs bearing pigment from a layer in a cave of the Huns Mountains in southern Namibia, which have been scientifically dated to 30,000 years ago. Four of these exhibited pigmented imagery of animals including a possible rhinoceros, a portion of a possible zebra figure and a complete unidentified quadruped formed by two of the plaques fitting together. These remain the oldest known figurative art in Africa. Much further rock art recording and excavation work has been undertaken since the 1980s in the Spitzkoppe, Erongo, Brandberg and other areas, with key research led by archaeologists <NAME>, <NAME>, <NAME>,<NAME> and <NAME>, among others. ' - sys: id: 1pTemf7LfaYckkgiam004s created_at: !ruby/object:DateTime 2016-09-26 14:51:03.951000000 Z updated_at: !ruby/object:DateTime 2018-05-09 16:48:40.803000000 Z content_type_id: chapter revision: 3 title: Themes title_internal: 'Namibia: country, chapter 8' body: "Much of the painted rock art in Namibia may be broadly compared to the wider hunter-gatherer rock art oeuvre found throughout southern Africa, similar in theme and composition and believed to be a part of the same general tradition, which is generally attributed to San&#124;Bushman¹ people and their ancestors. Imagery includes scenes of human figures carrying bows and other implements, wild animals and unidentified shapes in different pigments. Overall, human figures dominate in the paintings of Namibia, making up more than 2/3 of the painted figures, and where the gender can be recognised, they are more commonly male than female. Prominent painting subjects and styles in the rock art of Namibia (particularly the best-studied west-central region) include, at some sites, clearly delineated dots and patterns on human figures, a particular tradition of showing human figures with voluminous decorated hairstyles, and more images of giraffe and kudu, gemsbok and springbok antelope than in other southern African regions. Other images of animals include those of zebras, elephants, rhinoceros and ostriches. More occasional motifs found include plants, cattle, sheep and handprints. \n\n¹ San&#124;Bushmen is a collective term used to describe the many different hunter-gatherer-fisher groups living in southern Africa who have related languages and cultural traditions. Both 'San' and 'Bushmen' are considered offensive terms by some members of these groups, although others have positively adopted them." - sys: id: 3EiSSgVDtCWA4C4EOyW2ai created_at: !ruby/object:DateTime 2016-09-26 14:51:19.714000000 Z updated_at: !ruby/object:DateTime 2018-05-09 17:01:09.262000000 Z content_type_id: image revision: 2 image: sys: id: 3eVwGLF6ooeMySiG8G0a8U created_at: !ruby/object:DateTime 2016-09-26 14:51:15.764000000 Z updated_at: !ruby/object:DateTime 2016-09-26 14:51:15.764000000 Z title: NAMDMB0020012 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3eVwGLF6ooeMySiG8G0a8U/9c2150eacdb954ceb3f56afcbd4a5517/NAMDMB0020012.jpg" caption: Painted women carrying bows and showing detail of white dots (personal ornament or body paint). <NAME>. 2013,2034.21364 © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3771040&partId=1&searchText=2013,2034.21364&page=1 - sys: id: 7LqBKmEh1YMWOEymKkiQSk created_at: !ruby/object:DateTime 2016-09-26 14:51:27.064000000 Z updated_at: !ruby/object:DateTime 2018-05-10 10:22:02.825000000 Z content_type_id: chapter revision: 3 title_internal: 'Namibia: country, chapter 9' body: "Within Namibia, paintings come in a variety of styles, ranging from naturalistic to stylised. Paintings found at Spitzkoppe tend to be smaller and cruder than others in the region, where some sites feature tableaux in many colours while others are entirely monochrome. While the majority of rock paintings in Namibia seem to conform to the hunter-gatherer style, there are also some examples of finger paintings in the Brandberg and northern Namibia, which are much more schematic in style and appear to belong to a different tradition altogether. \n\nAs with much southern African rock art, the colours visible today may not always accurately reflect the original look. This is particularly true for those used for pale colours or white, which may be ‘fugitive’, meaning that over time they fade or wash away faster than the more stable pigments around them, leaving gaps which were once coloured. Chemical analyses have shown that a major binder (used to coalesce dry pigment powder) for painted rock art in Namibia was blood, and in some cases egg white. \n" - sys: id: 2b4cKiDAbeuKMcO6siYG6Y created_at: !ruby/object:DateTime 2016-09-26 14:51:42.124000000 Z updated_at: !ruby/object:DateTime 2018-05-10 10:23:26.466000000 Z content_type_id: image revision: 2 image: sys: id: 3zUEF7pFUIeqsKeW2wOIkw created_at: !ruby/object:DateTime 2016-09-26 14:51:37.704000000 Z updated_at: !ruby/object:DateTime 2016-09-26 14:51:37.704000000 Z title: NAMDME0070010 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3zUEF7pFUIeqsKeW2wOIkw/15882e5e2123e5477d082edffd38e034/NAMDME0070010.jpg" caption: Painting showing evidence of ‘fugitive’ pigment. Gemsbok or eland antelope with only the red pigment remaining. Omandumba, Erongo Mountains, Namibia. 2013,2034.21647 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3771309&partId=1&searchText=2013%2c2034.21647&page=1 - sys: id: 1UtWlqa1926kMisQkuimQK created_at: !ruby/object:DateTime 2016-09-26 14:51:49.953000000 Z updated_at: !ruby/object:DateTime 2018-05-09 16:49:27.291000000 Z content_type_id: chapter revision: 2 title_internal: 'Namibia: country, chapter 10' body: 'Engravings are often pecked and sometimes rubbed or polished. Although engravings, like paintings, feature animal figures heavily, with images of ostriches more common than those in paintings, there is a comparative dearth of engraved human figures. There is also less obvious interaction between individual engraved figures in the form of ‘scenes’ than in paintings, but instead more isolated individuals scattered on rock surfaces. Engraved rock art in Namibia also features a particular preponderance of images of spoor (animal hoof or paw prints). Some of these engravings are very naturalistic and may be identified by species whereas others, such as some showing human footprints, can be quite schematic. In addition, many engravings are geometric in nature. ' - sys: id: 6thXaCP5kIYysCy42IUgCC created_at: !ruby/object:DateTime 2016-09-26 14:52:14.154000000 Z updated_at: !ruby/object:DateTime 2018-05-10 10:24:08.309000000 Z content_type_id: image revision: 2 image: sys: id: 6lpq225cZOe0MKaC8cuuy6 created_at: !ruby/object:DateTime 2016-09-26 14:52:07.502000000 Z updated_at: !ruby/object:DateTime 2016-09-26 14:52:07.502000000 Z title: NAMWNK0010002 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6lpq225cZOe0MKaC8cuuy6/9815942f1c318fa7f945eb3075f8b109/NAMWNK0010002.jpg" caption: Examples of engraved spoor corresponding to eland hoof prints, Kalahari, Namibia. 2013,2034.22459 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3770294&partId=1&searchText=2013%2c2034.22459&page=1 - sys: id: 17KwAElNmCIGUoK4os22Gw created_at: !ruby/object:DateTime 2016-09-26 14:52:22.473000000 Z updated_at: !ruby/object:DateTime 2018-05-09 16:49:48.177000000 Z content_type_id: chapter revision: 3 title: Interpretation title_internal: 'Namibia: country, chapter 11' body: "Namibian rock paintings, and most engravings, have largely been interpreted in the vein largely espoused by researchers over the past 30 years. This postulates that much of this rock art reflects the experience of San&#124;Bushman shamans entering trance states and that rather than being scenes from daily life, the depictions of animals and activities are highly symbolic within San&#124;Bushman cosmology, with images acting as reservoirs of spiritual power. This avenue of interpretation originates largely from the study of rock art in South Africa and Lesotho. While it appears broadly applicable here, the fact that direct attributions to known cultural groups in this area are difficult somewhat hinders direct comparisons with Namibian rock art. While hunter-gatherer rock painting production in South Africa was practiced until the recent past, it appears to have ceased in Namibia around a thousand \ years ago and modern San&#124;Bushman groups in the Kalahari area have no tradition of rock art production. \n\nAdditionally, hundreds of miles and different geographical environments separate the rock art centres of north-western Namibia from those in neighbouring countries. This is particularly apparent in the differences in terms of animal subject matter, with the numerous depictions of gemsbok and springbok, explicable by the rock art creators being semi-desert dwellers where gemsbok and springbok are found locally though largely absent from rock art elsewhere in southern Africa, where these animals are not found. \n" - sys: id: lwcNbhZZy8koW0Uq2KEkq created_at: !ruby/object:DateTime 2016-09-26 14:52:40.163000000 Z updated_at: !ruby/object:DateTime 2018-05-10 10:26:46.067000000 Z content_type_id: image revision: 2 image: sys: id: 5UMcF5DE2siok0k4UakAUW created_at: !ruby/object:DateTime 2016-09-26 14:52:36.239000000 Z updated_at: !ruby/object:DateTime 2016-09-26 14:52:36.239000000 Z title: NAMBRH0010024 description: url: "//images.ctfassets.net/xt8ne4gbbocd/5UMcF5DE2siok0k4UakAUW/91a406ca0cb338ddf1c7e4b98325cd63/NAMBRH0010024.jpg" caption: Examples of painted motifs in rock art of the Brandberg, showing gemsbok antelope, giraffe, human, zebra and ostrich figures. Brandberg, Namibia. 2013,2034.21303 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3768631&partId=1&searchText=2013%2c2034.21303&page=1 - sys: id: 6x77m8o4vuuEMeqiSISGCK created_at: !ruby/object:DateTime 2016-09-26 14:52:47.433000000 Z updated_at: !ruby/object:DateTime 2018-05-10 10:30:06.342000000 Z content_type_id: chapter revision: 2 title_internal: 'Namibia: country, chapter 12' body: "Other differences are found in style and emphasis: the frequency with which giraffe feature in Namibian paintings and engravings contrasts with the South African rock art, where the emphasis is more on the eland antelope. \ This has led some to propose that the giraffe, similarly, must have held a particular symbolic meaning for the painters of the region. Based on associated imagery, placement of the rock art sites, and some ethnography (written records of insights from contemporary San&#124;Bushman culture compiled by anthropologists) it has been suggested that giraffes may have been linked with rain in local belief systems, with some Namibian rock painting sites associated specifically with rainmaking or healing activities. \n\nWhile the more naturalistic examples of engravings are thought to have also been produced by ancient hunter-gatherers, as with the paintings, it has been suggested that some geometric engravings were produced by herding people, possibly ancestral Khoenkhoen, perhaps in relation to initiation rites. Schematic finger paintings have also been attributed to pastoralist people. All attributions are tentative, however, because the majority of the art is thought to be many hundreds of years old and the historical distinctions between hunter-gatherers and herders is by no means clear-cut in the archaeological record.\n" - sys: id: 6Ljhl9Tm5GGKeU6e6GMSOA created_at: !ruby/object:DateTime 2016-09-26 14:52:59.658000000 Z updated_at: !ruby/object:DateTime 2018-05-09 16:50:17.361000000 Z content_type_id: chapter revision: 5 title: Chronology title_internal: 'Namibia: country, chapter 13' body: "The pieces from the cave Wendt excavated (named ‘Apollo 11 Cave’ after the moon mission which took place during the period of the excavation work) are not thought to have fallen from a cave wall but were made on loose rock pieces. The only parietal art (on a fixed rock surface) dated from excavated deposits in Namiba so far consists of pieces of painted granite from the largest painted shelter in the Brandberg, one of which, found in a sedimentary layer radiocarbon dated to around 2,700 years ago, had clearly fallen from an exposed rock surface into which researchers were able to refit it. Aside from this, estimates at the age of rock art are based on superimposition, patination and associated archaeological finds. \n\nBased on archaeological evidence, it is thought that the majority of the fine-line hunter-gatherer rock art in the Brandberg area was produced between around 4,000 and 2,000 years ago, with the painting tradition in the wider region starting as much as 6,000 years ago. This ceased sometime after the introduction of small domestic stock to the area, although not immediately, as fine-line paintings of sheep and paintings and engravings of cattle testify. Across central Namibia, there appears to be a particularly strong correspondence of finds relating to paintings—such as grinding equipment and pigments—with dated layers from the 1st millennium BC.\n" - sys: id: 3k0RnznV5Yu2uoGgc0UkCC created_at: !ruby/object:DateTime 2016-09-26 14:53:21.292000000 Z updated_at: !ruby/object:DateTime 2018-05-10 10:30:47.494000000 Z content_type_id: image revision: 2 image: sys: id: 5SxIVsUotUcuWoI2iyYOSO created_at: !ruby/object:DateTime 2016-09-26 14:53:15.820000000 Z updated_at: !ruby/object:DateTime 2016-09-26 14:53:15.821000000 Z title: NAMNNO0010020 description: url: "//images.ctfassets.net/xt8ne4gbbocd/5SxIVsUotUcuWoI2iyYOSO/b2b0daf1086aba5ebb54c90b0b1cce42/NAMNNO0010020.jpg" caption: Finger painted rock art, northern Namibia. 2013,2034.22237 © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3771279&partId=1&searchText=2013%2c2034.22237&page=1 - sys: id: 7hIopDzZzGI8iMiuEOOOyG created_at: !ruby/object:DateTime 2016-09-26 14:53:29.617000000 Z updated_at: !ruby/object:DateTime 2018-05-09 16:50:37.206000000 Z content_type_id: chapter revision: 2 title_internal: 'Namibia: country, chapter 14' body: 'Engravings are more difficult to obtain dates for scientifically. Superimpositioning and other physical factors can serve to indicate which styles of image are more recent with both paintings and engravings. For example, in the Brandberg, monochrome tableaux appear older than detailed polychrome depictions of individuals, and certain images, such as those of zebras, are thought to be relatively late. Among engravings of central Namibia, a certain style of hoof print appears to overlie some figurative images, leading researchers to believe them younger. Overall it is thought that the engraving and painting traditions were concurrent, with some clear parallels in style, but that engraving probably lasted for several hundred years as a tradition after painting ceased. ' - sys: id: 137eUF3ZZGUGy6SM4cWimS created_at: !ruby/object:DateTime 2016-09-26 14:53:45.520000000 Z updated_at: !ruby/object:DateTime 2018-05-10 10:40:21.998000000 Z content_type_id: image revision: 2 image: sys: id: 4I7MYP97u8AK8YE88UGOKS created_at: !ruby/object:DateTime 2016-09-26 14:53:41.001000000 Z updated_at: !ruby/object:DateTime 2016-09-26 14:53:41.001000000 Z title: NAMSNA0010011 description: url: "//images.ctfassets.net/xt8ne4gbbocd/4I7MYP97u8AK8YE88UGOKS/0b33b94b43c9ba242717ba831d3f7fe3/NAMSNA0010011.jpg" caption: Engraved geometric rock art in the style thought to have been made by herder people. ǁKaras Region, Southern Namibia. 2013,2034.22285 ©TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3772002&partId=1&place=108716&plaA=108716-2-2&page=1 citations: - sys: id: 2Looo7MWBGKQQKAooSausA created_at: !ruby/object:DateTime 2016-09-26 14:53:53.399000000 Z updated_at: !ruby/object:DateTime 2016-09-26 14:53:53.399000000 Z content_type_id: citation revision: 1 citation_line: | CeSMAP- Study Centre and Museum of Prehistoric Art of Pinerolo. 1997. African pictograms. Pinerolo, Centro Studi e Museo di arte preistorica. Kinahan, J. 2010. The rock art of /Ui-//aes (Twyfelfontein) Namibia’s first World Heritage Site. Adoranten 2010. Tanumshede: Tanums Hällristningsmuseum Kinahan, J. 1999. Towards an Archaeology of mimesis and rainmaking in Namibian rock art in : Ucko, P. J., & <NAME>. (1999). The Archaeology and Anthropology of Landscape: Shaping your Landscape. London, Routledge pp. 336-357 <NAME>. 2015. IFRAO. Rock art research in Namibia: a synopsis A investigação de arte rupestre na Namíbia: uma visão geral in: Giraldo, H.C. & Arranz, J.J.G (eds.) Symbols in the Landscape: Rock Art and its Context. Proceedings of the XIX International Rock Art Conference IFRAO 2015, Arkeos 37 pp. 1419:1436 <NAME>., Kuhn., & <NAME>. 1930. Bushman art: rock paintings of south-west Africa. London, <NAME>, Oxford University Press <NAME>. 1989-. Rock Paintings of the Upper Brandberg. vols. I-VI. Köln: Heinrich-Barth-Institut <NAME>. & <NAME>: Rock Art in North-Westerpn Central Namibia – its Age and Cultural Background in: <NAME>., & <NAME>. 2008. Heritage and Cultures in modern Namibia: in-depth views of the country : a TUCSIN Festschrift. Windhoek ; Goettingen : Klaus Hess Publishers pp 37:46 <NAME>. 1970, 1975, 1986. Felsbilder in Südwest-Afrika. Teilen I-III. Köln ;Wien: Böhlau background_images: - sys: id: BhOqSut01augms8wwkY8m created_at: !ruby/object:DateTime 2015-12-08 13:42:04.235000000 Z updated_at: !ruby/object:DateTime 2015-12-15 11:45:44.591000000 Z title: NAMDMT0010062 description: url: "//images.ctfassets.net/xt8ne4gbbocd/BhOqSut01augms8wwkY8m/a91859d293ab45f0b1ebbb75525337e0/NAMDMT0010062.jpg" - sys: id: 1a2GJATzdmuSKyA0sW8gmY created_at: !ruby/object:DateTime 2016-09-26 14:48:10.002000000 Z updated_at: !ruby/object:DateTime 2016-09-26 14:48:10.002000000 Z title: NAMBRG0030001 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1a2GJATzdmuSKyA0sW8gmY/5d8121e14cd4e1258d01a0f6c049ddbb/NAMBRG0030001.jpg" - sys: id: 2JJhvPXvQkYkS84couiQMk created_at: !ruby/object:DateTime 2016-09-26 14:48:21.152000000 Z updated_at: !ruby/object:DateTime 2016-09-26 14:48:21.152000000 Z title: NAMBRG0010004 description: url: "//images.ctfassets.net/xt8ne4gbbocd/2JJhvPXvQkYkS84couiQMk/854c949053f5ad0f54d174d92f71466d/NAMBRG0010004.jpg" region: Southern Africa ---<file_sep>/_coll_country_information/tanzania-country-introduction.md --- contentful: sys: id: 1LiwPCnyFKmciIOKysACI0 created_at: !ruby/object:DateTime 2016-07-27 07:44:27.856000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:44:27.856000000 Z content_type_id: country_information revision: 1 title: 'Tanzania: Country Introduction' chapters: - sys: id: 43gtar9Bd6iwSOOug8Ca2K created_at: !ruby/object:DateTime 2016-07-27 07:45:18.035000000 Z updated_at: !ruby/object:DateTime 2016-07-27 12:30:57.863000000 Z content_type_id: chapter revision: 3 title: Introduction title_internal: Tanzania Chapter 1 body: Containing some of the densest concentrations of rock art in East Africa, Tanzania includes many different styles and periods of rock art, the earliest of which may date back 10,000 years. Consisting mainly of paintings, rock art is found predominantly in the Kondoa region and the adjoining Lake Eyasi basin. Those at Kondoa were inscribed as a UNESCO World Heritage site in 2006, and were the first to be documented by missionaries in 1908. - sys: id: 3cunSLA63KsGEGIw0C8ki created_at: !ruby/object:DateTime 2016-07-27 07:45:11.825000000 Z updated_at: !ruby/object:DateTime 2017-01-24 15:37:31.932000000 Z content_type_id: image revision: 2 image: sys: id: 6jqxlKBK8ggSwAyOIWC2w created_at: !ruby/object:DateTime 2016-07-27 07:46:37.419000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:37.419000000 Z title: TANKON0130004 jpeg description: url: "//images.ctfassets.net/xt8ne4gbbocd/6jqxlKBK8ggSwAyOIWC2w/62820080f1ce2792a5bbc9c38ac89b50/TANKON0130004_jpeg.jpg" caption: Painted panel of fine-line paintings of kudu and human figures with bow and arrow. Msokia, Kondoa, Tanzania. 2013,2034.17086 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3710216&partId=1&searchText=2013,2034.17086&page=1 - sys: id: 3fuknu8MJiS2CEUo8c48Mm created_at: !ruby/object:DateTime 2016-07-27 07:45:16.738000000 Z updated_at: !ruby/object:DateTime 2016-07-27 08:44:49.657000000 Z content_type_id: chapter revision: 3 title: Geography and Rock Art distribution title_internal: Tanzania Chapter 2 body: |- Situated within the Great Lakes Region of East Africa, Tanzania is bordered by Kenya and Uganda to the north; Rwanda, Burundi, and the Democratic Republic of the Congo to the west; Zambia, Malawi, and Mozambique to the south; and the Indian Ocean to the east, with a coastline of approx. 800km. At 947,303 km², Tanzania is the largest country in East Africa and is home to Africa's highest mountain, Kilimanjaro (5,895 m, 19,340 feet), located in the north-east of the country. Central Tanzania is comprised largely of a plateau, which is mainly grassland and contains many national parks. The north of the country is predominantly arable and includes the national capital of Dodoma. The north-east of the country is mountainous and contains the eastern arm of the Great Rift Valley. Further north-west is Lake Victoria adjoining the Kenya–Uganda–Tanzania border. Concentrations of rock art are found mainly in the Kondoa province of central Tanzania and also the Lake Eyasi Basin in the north of the country. The rock art of the Lake Eyasi Basin and that of Kondoa share many similarities related to subject matter, styles, pigments and even types of sites. This may possibly reflect a shared art tradition among hunter-gatherers, which is feasible as there are no natural barriers preventing the movement of cultural ideas and techniques. - sys: id: 5bWgTlQsXCq2OQC0Koa8OU created_at: !ruby/object:DateTime 2016-07-27 07:45:10.912000000 Z updated_at: !ruby/object:DateTime 2017-01-24 15:38:18.560000000 Z content_type_id: image revision: 2 image: sys: id: 5XVIPjHq7K4MiWIm6i6qEk created_at: !ruby/object:DateTime 2016-07-27 07:46:38.051000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:38.051000000 Z title: TANKON0310006 jpeg description: url: "//images.ctfassets.net/xt8ne4gbbocd/5XVIPjHq7K4MiWIm6i6qEk/55d7e3497c0e2715ad2fe7605c49d533/TANKON0310006_jpeg.jpg" caption: Elongated red figure facing right with rounded head and holding a narrow rectangular object (shield?); the image has been damaged by white water seepage. Kondoa, Tanzania. 2013,2034.17497 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3712306&partId=1&searchText=2013,2034.17497&page=1 - sys: id: 2s5iBeDTAMk8Y2Awqc024i created_at: !ruby/object:DateTime 2016-07-27 07:45:18.020000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:45:18.020000000 Z content_type_id: chapter revision: 1 title: History of rock art research in Tanzania title_internal: Tanzania Chapter 3 body: 'The existence of painted rock art was first reported to Europeans in 1908 by missionaries, but the first scientific explorations date back to the 1930s. Early surveys were undertaken by L<NAME> (1958), a German physician, amateur anthropologist and explorer, who traced images in more than 70 rock shelters in 1935. The renowned paleoanthropologists Mary and <NAME> (1983) were the first to extensively study the rock art of Tanzania during the 1930s and 1950s (having noted many sites in the 1920s), documenting over 1600 painted images at 186 sites north of Kondoa. In the late 1970s and during the 1980s Fidelis Masao (1979) surveyed 68 rock paintings sites and excavated four of them while <NAME> (1996) recorded 200 sites in Kondoa. Other researchers include <NAME> (1971, 1974), <NAME> (1986), <NAME> (1992), and <NAME> (2008, 2011); all of whom have recorded numerous sites, contributing to identifying chronologies, styles and possible interpretations. Conservation and preservation of the rock art has been of importance since the 1930s, and many of the paintings recorded by the Leakeys in the early 1950s are now severely deteriorated, or in some cases completely destroyed. ' - sys: id: MsqR1AiFOKQqiySkEIAwQ created_at: !ruby/object:DateTime 2016-07-27 07:45:10.806000000 Z updated_at: !ruby/object:DateTime 2017-01-24 15:41:21.774000000 Z content_type_id: image revision: 2 image: sys: id: 28qJxjtSOoC6Aa2IgQk06q created_at: !ruby/object:DateTime 2016-07-27 07:46:37.137000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:37.137000000 Z title: TANKON0050001 jpeg description: url: "//images.ctfassets.net/xt8ne4gbbocd/28qJxjtSOoC6Aa2IgQk06q/9d9b407dd70a62d06c4a95db72c0e9eb/TANKON0050001_jpeg.jpg" caption: View looking out of rock shelter over Kondoa region, Tanzania. 2013,2034.16942 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3709993&partId=1&searchText=2013,2034.16942&page=1 - sys: id: i9BKWyIrJeYSQICcciYGC created_at: !ruby/object:DateTime 2016-07-27 07:45:16.691000000 Z updated_at: !ruby/object:DateTime 2016-07-27 12:32:37.897000000 Z content_type_id: chapter revision: 4 title: Chronologies title_internal: Tanzania Chapter 4 body: "Scholars have classified the rock art in Tanzania into three main stylistic groups: Hunter-gatherer, also known as Sandawe, Pastoral, and Late Whites. Hunter-gatherer and Late White paintings are often found in the same rock shelters and in some instances, all three types occur at the same site. \n\nNo paintings have been scientifically dated, but some researchers have proposed the earliest dates for the art: Anati (1996) has suggested paintings at Kondoa may be up to 40,000 years old; Leakey (1985) and Coulson and Campbell (2001) up to 10,000 years old. Masao (1979) has estimated the earliest art at perhaps 3000 years old. These are estimates and not based on radiometric dating techniques, and as the paintings have been exposed to considerable weathering these very early dates currently cannot be substantiated.\n\n__Hunter-gatherer__\n\nHunter-gatherer or Sandawe rock art is characterised by fine-line paintings and includes images of animals, human figures, handprints and circular designs. These are the earliest paintings, thought to date to between 3,000-10,000 years ago, and are attributed to the ancestral Sandawe, a hunter-gatherer group indigenous to north-east Tanzania. \n\nThis tradition of rock art occurs in the Kondoa region, with just a few hundred sites in a concentration of less than a 100km in diameter and corresponding closely to the known distribution of the Sandawe people. Animals, such as giraffe, elephant, rhinoceros, antelope, plus a few birds and reptiles, dogs and possibly bees, make up more than half of the images depicted. In addition there are a few animal tracks depicted: cloven hooves, porcupine and aardvark. \n" - sys: id: 5yhqNSTj7USAE6224K28ce created_at: !ruby/object:DateTime 2016-07-27 07:45:11.089000000 Z updated_at: !ruby/object:DateTime 2017-01-24 15:41:54.311000000 Z content_type_id: image revision: 2 image: sys: id: 3fNBqZVcfK8k0Cgo4SsGs6 created_at: !ruby/object:DateTime 2016-07-27 07:46:37.182000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:37.182000000 Z title: TANKON0100004 jpeg description: url: "//images.ctfassets.net/xt8ne4gbbocd/3fNBqZVcfK8k0Cgo4SsGs6/1e5b30977d1a9f021e3eea07fca43f5a/TANKON0100004_jpeg.jpg" caption: Panel of fine-line red figures with rounded heads seated, standing and dancing. <NAME>, Tanzania. 2013,2034.17042 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3710340&partId=1&searchText=2013,2034.17042&page=1 - sys: id: 7w5bbsaHIcGU8U4KyyQ8W6 created_at: !ruby/object:DateTime 2016-07-27 07:45:17.860000000 Z updated_at: !ruby/object:DateTime 2017-01-24 15:45:13.087000000 Z content_type_id: chapter revision: 2 title_internal: Tanzania Chapter 5 body: |2 Typically, human figures are slender and elongated, wearing large elaborate coiffures or headdresses, and sometimes with animal heads. Occasionally they are bent at the waist but they always appear in groups or pairs. A few of the figures are painted with bows and arrows and occur with animals, although whether these represent a hunting scene is uncertain. Women are very scarce. The few handprints present are painted depictions rather than stencils and circular designs are made up of concentric circles sometimes with elaborate rays and occasional rectangles and finger dots. - sys: id: QLuzPXhKqOmMSm0weqOGG created_at: !ruby/object:DateTime 2016-07-27 07:45:10.897000000 Z updated_at: !ruby/object:DateTime 2019-02-12 00:37:50.613000000 Z content_type_id: image revision: 3 image: sys: id: 3zoMrANvf2SgUmuAu2Wa4W created_at: !ruby/object:DateTime 2016-07-27 07:46:38.115000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:38.115000000 Z title: TANKON0370007 jpeg description: url: "//images.ctfassets.net/xt8ne4gbbocd/3zoMrANvf2SgUmuAu2Wa4W/b759c5fe8747a6c19218f19bc693ab2e/TANKON0370007_jpeg.jpg" caption: Panel of Sandawe red, fine-line paintings showing elephants and slender elongated figures. Kondoa, Tanzania. 2013,2034.17702 © TARA/<NAME> col_link: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3712676&partId=1&searchText=2013,2034.17702&page=1 - sys: id: 55d7OVNn5YEii4KSYwE0wE created_at: !ruby/object:DateTime 2016-07-27 07:45:10.859000000 Z updated_at: !ruby/object:DateTime 2017-01-24 15:47:21.921000000 Z content_type_id: image revision: 2 image: sys: id: 4eRcBkspfOS2Ky4GE08qyC created_at: !ruby/object:DateTime 2016-07-27 07:46:38.051000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:38.051000000 Z title: TANKON0300005 jpeg description: url: "//images.ctfassets.net/xt8ne4gbbocd/4eRcBkspfOS2Ky4GE08qyC/5c0b8033c1328f01893ad54418b856ce/TANKON0300005_jpeg.jpg" caption: Seated figure wearing elaborate headdress which is possibly surrounded by bees. Thawi 1, Kondoa, Tanzania. 2013,2034. 17471 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3711764&partId=1&searchText=2013,2034.17471&page=1 - sys: id: 4OiTL2qHFeIEmGUE6OqUcA created_at: !ruby/object:DateTime 2016-07-27 07:45:16.827000000 Z updated_at: !ruby/object:DateTime 2017-01-24 15:45:27.688000000 Z content_type_id: chapter revision: 4 title: '' title_internal: Tanzania Chapter 6 body: | __Pastoral__ About 3,000 years ago, Cushitic herders from Ethiopia moved into the region, and were followed by Nilotic cattle pastoralists, ancestors of today’s Maasai. In comparison to hunter-gatherer rock art, Pastoral rock art yields many fewer paintings and generally depicts cattle in profile, and sometimes sheep and/or goats, a few dogs and figures holding sticks and bows. Predominantly painted in black and sometimes red and white, the colour of many images has now faded to a dull grey colour. - sys: id: 59cgwuXiu4EyiwGuIog0Wi created_at: !ruby/object:DateTime 2016-07-27 07:45:10.760000000 Z updated_at: !ruby/object:DateTime 2017-01-24 15:47:47.628000000 Z content_type_id: image revision: 2 image: sys: id: 1BwSSd5li0MUw4c4QYyAKA created_at: !ruby/object:DateTime 2016-07-27 07:46:38.208000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:38.208000000 Z title: TANLEY0020026 jpeg description: url: "//images.ctfassets.net/xt8ne4gbbocd/1BwSSd5li0MUw4c4QYyAKA/b8a08110079558a56d9ac1d7bfb813a9/TANLEY0020026_jpeg.jpg" caption: 'Top of this boulder: Red cow facing right superimposed on faded white cow facing left and figure facing forwards, Eshaw Hills, Tanzania. 2013,2034.17936 © TARA/<NAME>' col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3713196&partId=1&searchText=2013,2034.17936&page=1 - sys: id: 4zC1ndduCQa8YUSqii26C6 created_at: !ruby/object:DateTime 2016-07-27 07:45:15.874000000 Z updated_at: !ruby/object:DateTime 2017-01-24 15:45:36.649000000 Z content_type_id: chapter revision: 3 title: '' title_internal: Tanzania Chapter 7 body: | __Late White__ Late White paintings are crude, finger painted images and often superimpose older images. These were made by Bantu-speaking, iron-working farmers who moved into the region in the last 300-500 years. The most common type of depiction are designs and motifs that include circles, some of which have rays emanating outwards, concentric circles, patterns of dots and grids with outlines, what look like stick figures with multiple arms, as well as handprints. Animal depictions include giraffe, elephant, antelope, snakes, reptiles, baboons and domestic species. Human figures are less common, but when present are notably men facing forwards with hands on hips, sometimes holding weapons. - sys: id: 4zIzfG4WDKe6SYSimcaEqg created_at: !ruby/object:DateTime 2016-07-27 07:45:10.886000000 Z updated_at: !ruby/object:DateTime 2017-01-24 15:49:16.769000000 Z content_type_id: image revision: 3 image: sys: id: 2iqeQFLDE06A8MW0UcUm2k created_at: !ruby/object:DateTime 2016-07-27 07:46:37.131000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:37.131000000 Z title: TANKON0020039 jpeg description: url: "//images.ctfassets.net/xt8ne4gbbocd/2iqeQFLDE06A8MW0UcUm2k/12b31881421ef6d5f5ccebbc4ec1c009/TANKON0020039_jpeg.jpg" caption: Numerous finger painted geometric designs covering large granite boulder. Pahi, Tanzania. 2013,2034.16793 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3709639&partId=1&searchText=2013,2034.16793&page=1 citations: - sys: id: 5CTLCKcFag2yCMmCgoegE4 created_at: !ruby/object:DateTime 2016-07-27 07:45:15.786000000 Z updated_at: !ruby/object:DateTime 2016-07-27 12:42:00.048000000 Z content_type_id: citation revision: 6 citation_line: "<NAME>. (1996) ‘Cultural Patterns in the Rock Art of Central Tanzania.’ in *The Prehistory of Africa. XIII International Congress of Prehistoric and Protohistoric Sciences Forli-Italia-8/14* September 1996\n\nBwasiri, E.J (2008) 'The Management of Indigenous Heritage: A Case Study of Mongomi wa Kolo Rock Shelter, Central Tanzania'. MA Dissertation, University of the Witwatersrand \n\nBwasiri, E.J. (2011) ‘The implications of the management of indigenous living heritage: the case study of the Mongomi wa Kolo rock paintings World Heritage Site, Central Tanzania’, in *South African Archaeological Bulletin* 69-193:60-66\n\nCoulson, D. and <NAME>bell (2001) *African Rock Art: Paintings and Engravings on Stone* New York, Harry N. Abrams, Ltd.\n\nKohl-Larsen, L. (1958) *Die Bilderstrasse Ostafricas: Felsbilder in Tanganyika*. Kassel, Erich Roth-Verlag\n\nLeakey, M. (1983) *Africa’s Vanishing Art – The Rock Paintings of Tanzania.* London, Hamish Hamilton Ltd\n\nLewis-Williams, J.D. (1986) ‘Beyond Style and Portrait: A Comparison of Tanzanian and Southern African Rock Art’. *Contemporary Studies on Khoisan 2.* Hamburg, <NAME> Verlag\n\nLim, I.L. \ (1992) ‘A Site-Oriented Approach to Rock Art: a Study from Usandawe, Central Tanzania’. PhD Thesis, University of Michigan\n\nMasao, F.T. (1979)*The Later Stone Age and the Rock Paintings of Central Tanzania*. Wiesbaden, <NAME> Verlag\n\nTen Raa, E. (1971) ‘Dead Art and Living Society: A Study of Rock paintings in a Social Context’.*Mankind* 8:42-58\n\nTen Raa, E. (1974) ‘A record of some prehistoric and some recent Sandawe rock paintings’. *Tanzania Notes and Records* 75:9-27\n\n" ---<file_sep>/_coll_country_information/egypt-country-introduction.md --- contentful: sys: id: 3HkyZVGe2suiyEMe6ICs4U created_at: !ruby/object:DateTime 2015-11-26 10:45:19.662000000 Z updated_at: !ruby/object:DateTime 2015-12-07 13:42:03.255000000 Z content_type_id: country_information revision: 2 title: 'Egypt: country introduction' chapters: - sys: id: 1RtA0G7m6ok8cOWi20EC2s created_at: !ruby/object:DateTime 2015-11-26 10:37:46.214000000 Z updated_at: !ruby/object:DateTime 2017-01-09 15:05:57.139000000 Z content_type_id: chapter revision: 3 title: Introduction title_internal: 'Egypt: country, chapter 1' body: The rock art of Egypt was largely unknown outside of the region until the beginning of the 20th century. The rock paintings and engravings of Egypt feature a range of subjects and styles, including domestic cattle, wild animals, humans, boat images and inscriptions. Much of the rock art appears to date from within the last 8,000 years. However, earlier Palaeolithic engravings have also been found near the Nile, suggesting a longer time frame for the practice. The majority of Egypt’s most famous rock art, including the ‘Cave of Swimmers’, is found in the desert in the far south-west of the country. - sys: id: JXxIothd6gke6u68aMS2k created_at: !ruby/object:DateTime 2015-11-26 10:33:39.571000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:30:48.038000000 Z content_type_id: image revision: 4 image: sys: id: 4yqh628H2wae4Mwe6MQGWa created_at: !ruby/object:DateTime 2015-11-26 10:33:01.324000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:30:00.913000000 Z title: '2013,2034.25' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3577780&partId=1&images=true&people=197356&place=42209&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/4yqh628H2wae4Mwe6MQGWa/41dcae1c01f69ace28bccc26fd712c6f/2013_2034.5277.jpg" caption: Painted human figures and cows on rock shelter roof. <NAME>, Jebel Uweinat, Egypt. 2013,2034.25© TARA/<NAME> col_link: http://bit.ly/2iVMFd0 - sys: id: 3Cs9Muna1qeMOCAUyCCuQm created_at: !ruby/object:DateTime 2015-11-26 10:38:16.091000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:38:16.091000000 Z content_type_id: chapter revision: 1 title: Geography title_internal: 'Egypt: country, chapter 2' body: Egypt covers about 996,000km² at Africa’s north-east corner and until the creation of the Suez Canal in 1869, contained Africa’s only direct physical connection to Eurasia. The country’s most prominent geographical feature, the river Nile, flows from the highlands of Ethiopia and Central Africa into the Mediterranean, dividing the eastern portion of the Sahara into the Western and Eastern Deserts, with the Sinai Peninsula to the east. - sys: id: 7IH4mS5LW0cSGcgEaa6ESO created_at: !ruby/object:DateTime 2015-11-26 10:38:54.278000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:38:54.278000000 Z content_type_id: chapter revision: 1 title: Research history title_internal: 'Egypt: country, chapter 3' body: |- The presence of rock art in Egypt has been noticed by European scholars since the early 19th century. Geographically isolated from the bulk of rock art in the country, the paintings and engravings of Gilf Kebir and Jebel Uweinat were first catalogued in the 1920s by the Egyptian explorers and public figures <NAME> and <NAME>, and thereafter by renowned early twentieth century explorers and ethnographers such as <NAME>, <NAME>, <NAME> and <NAME>, whose expeditions helped bring Saharan rock art into wider public consciousness. Hans Winkler’s seminal *Rock Drawings of Southern Upper Egypt* (1938-9) was one of the first regional catalogues and remains a pre-eminent review of finds. Further cataloguing of rock art images and sites in the southern Nile valley took place at the time of the construction of the Aswan High Dam in the 1960s. Where rock art historically was part of larger archaeological research in the area, in recent years it has been subject to more direct and rigorous study which will contribute to a better understanding of chronologies and relationships. - sys: id: 3CzPFWoTFeIMaCsMgSy0sg created_at: !ruby/object:DateTime 2015-11-26 10:39:46.908000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:44:29.300000000 Z content_type_id: chapter revision: 2 title: Themes title_internal: 'Egypt: country, chapter 4' body: In desert areas, recognisably stylised Pharaonic-period inscriptions and engravings from between 3,100 and 30 BC can be found on rock faces, particularly at oases and quarry sites such as Kharga Oasis and Wadi Hammamat in the Western and Eastern deserts. There is also rock art from later periods like that at Matna el-Barqa in the Western Desert hinterland, where both Pharaonic and later Coptic inscriptions mix with images of gods and horsemen. Earlier examples of engraved rock art may be found in the Nile valley, in what is now southern Egypt and northern Sudan, linked to progenitors of ancient Egyptian cultures, most particularly the people of the Naqada Periods (4,000-3,100 BC). This art is characterised by frequent depictions on pottery of river boats, which occur in much of the rock art near the Nile, and include, pecked on a boulder at Nag el-Hamdulab near Aswan, what is considered the first known depiction of a Pharaoh, on just such a boat. Also prevalent in these areas are numerous engravings of animals and human figures. - sys: id: 2YNlS4f9ZuswQuwKQmIEkU created_at: !ruby/object:DateTime 2015-11-26 10:34:25.538000000 Z updated_at: !ruby/object:DateTime 2017-01-09 15:09:37.165000000 Z content_type_id: image revision: 2 image: sys: id: 3MIwpw8kAMIuGukggC2mUo created_at: !ruby/object:DateTime 2015-11-26 10:33:01.309000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:33:01.309000000 Z title: '2013,2034.108' description: url: "//images.ctfassets.net/xt8ne4gbbocd/3MIwpw8kAMIuGukggC2mUo/a296d679fd2c30c9a1fec354b5028ef9/2013_2034.108.jpg" caption: Engraved antelope and lion pugmarks on cave wall. Wadi el-Obeiyd, Farafra Oasis, Western Desert. 2013,2034.108 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3577697&partId=1&images=true&people=197356&place=42209&page=2 - sys: id: 4jirnWi9nqW0e44wqkOwMi created_at: !ruby/object:DateTime 2015-11-26 10:40:02.893000000 Z updated_at: !ruby/object:DateTime 2017-01-09 15:07:08.214000000 Z content_type_id: chapter revision: 2 title_internal: 'Egypt: country, chapter 5' body: Possible links between ancient Egyptian culture and wider Saharan rock art traditions have been discussed since the rock art of northern Africa first met European academic attention in the early 20th century. Although the arid Western Desert appears to have been a significant barrier, relations remain unclear. - sys: id: 69gKt6UfRuqKcSuCWUYOkc created_at: !ruby/object:DateTime 2015-11-26 10:40:26.215000000 Z updated_at: !ruby/object:DateTime 2017-01-09 15:21:14.317000000 Z content_type_id: chapter revision: 2 title: Chronology title_internal: 'Egypt: country, chapter 6' body: Certainly, not all rock art found in Egypt has direct links to Pharaonic cultures. Recently, the rock art at Qurta, south of Edfu, of naturalistic outline engravings of ancient aurochs (ancestors of domestic cattle), were dated reliably to the Palaeolithic Period, between 16,000 and 15,000 years ago, making them the oldest known rock art in northern Africa. Between the eighth and fourth millennia BC, Egypt’s climate was generally temperate, interrupted only briefly by dry spells, until the increasing aridity thereafter concentrated life in the Eastern Sahara around the river’s banks. - sys: id: 6JMuLUburS0sqo4aGIgq4e created_at: !ruby/object:DateTime 2015-11-26 10:35:03.483000000 Z updated_at: !ruby/object:DateTime 2017-01-09 15:21:43.897000000 Z content_type_id: image revision: 2 image: sys: id: 1BqBCPqhDiiM0qqeM6Eeie created_at: !ruby/object:DateTime 2015-11-26 10:33:01.325000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:33:01.325000000 Z title: '2013,2034.126' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1BqBCPqhDiiM0qqeM6Eeie/cc9f8eabaf32202035c94c9e7d444bb2/2013_2034.126.jpg" caption: Hand prints, blown pigment on cave wall. <NAME>-Obeiyd, Farafra Oasis, Western Desert. 2013,2034.126 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3577677&partId=1&images=true&people=197356&place=42209&page=1 - sys: id: 68oUY9MIOA82MUu0SUuYIU created_at: !ruby/object:DateTime 2015-11-26 10:40:44.511000000 Z updated_at: !ruby/object:DateTime 2016-07-22 19:36:46.175000000 Z content_type_id: chapter revision: 2 title_internal: 'Egypt: country, chapter 7' body: This development fostered both ancient Egyptian culture and isolated populations of animals elsewhere driven out of their environments by encroaching desert, some of which, like crocodiles, are represented in the rock engravings found along the alluvial plains. Engravings of wild fauna continue to be uncovered, such as that recently found near the Farafra Oasis, with depictions of giraffe and antelope scratched into the rock face. In a cave nearby, alongside engraved lion paw prints, are blown-pigment negative paintings of human hands. - sys: id: 5iFCF3Y5AsMoKE8mqa2gMK created_at: !ruby/object:DateTime 2015-11-26 10:35:44.393000000 Z updated_at: !ruby/object:DateTime 2017-01-09 15:28:38.595000000 Z content_type_id: image revision: 2 image: sys: id: 2eE8VylT2ocoEoAQ22m2Qq created_at: !ruby/object:DateTime 2015-11-26 10:33:01.349000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:33:01.349000000 Z title: '2013,2034.4' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2eE8VylT2ocoEoAQ22m2Qq/3a8fa3faf5eb2287751d90b451c1090c/2013_2034.4.jpg" caption: Engraved cattle. <NAME>, <NAME>. 2013,2034.4 © TARA/David Coulson col_link: http://bit.ly/2iW0oAD - sys: id: 4lif35hFsIWGGeYmQIK2Sc created_at: !ruby/object:DateTime 2015-11-26 10:41:00.987000000 Z updated_at: !ruby/object:DateTime 2017-01-09 15:30:05.093000000 Z content_type_id: chapter revision: 2 title_internal: 'Egypt: country, chapter 8' body: Some of Egypt’s most striking and famous rock art is found far from the Nile at Gilf Kebir, a vast sandstone plateau in the desert near the Libyan border. As elsewhere in the Sahara, there are frequent depictions of domestic cattle, people and wild animals. Like most rock art, the paintings and engravings here are hard to date accurately but may refer to the ‘Bovidian Period’ (Pastoral Period) rock art of the wider Sahara, typified by paintings and engravings of cattle and people (Huyge, 2009). However, the scholarly community recognises the inherent difficulty of formulating conclusions of direct links with wider rock art practices. Some evidence of pastoralists in the area means that this rock art could have been made as early as the fifth millennium BC and are thus possibly contemporaneous with Predynastic Egyptian cultures, but not necessarily connected (Riemer, 2013). - sys: id: 3MnIkobDNSIWoYeec8QmsI created_at: !ruby/object:DateTime 2015-11-26 10:41:27.078000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:41:27.078000000 Z content_type_id: chapter revision: 1 title: Interpretation title_internal: 'Egypt: country, chapter 9' body: The motivation behind producing these images remains elusive. Where a particular cosmology is better known, it can be speculated, such as the Nile boat paintings have been suggested to evoke funerary beliefs and practices. If nothing else, the cattle paintings of Gilf Kebir demonstrate the importance of cattle in the pastoralist culture that produced them. Despite still being relatively little known, the ‘mystique’ behind rock art has cultivated popular curiosity, in particular in Gilf Kebir’s famous ‘Cave of Swimmers’. This is a shallow rock shelter featuring many painted human figures in strange contortions, as if swimming – images which have captured the popular imagination, with their glimpse of life in Egypt millennia before the Pharaohs and their hints at a watery Sahara. - sys: id: 3Wc0ODJNxmUc86aiSCseWM created_at: !ruby/object:DateTime 2015-11-26 10:36:22.741000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:36:22.741000000 Z content_type_id: image revision: 1 image: sys: id: 2QN2xRgnrOcQKsIM224CYY created_at: !ruby/object:DateTime 2015-11-26 10:33:01.324000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:33:01.324000000 Z title: '2013,2034.212' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2QN2xRgnrOcQKsIM224CYY/6444f91f912b086def593035a40f987b/2013_2034.212.jpg" caption: Painted human and cattle figures, <NAME>, <NAME>. 2013,2034.212 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3577589&partId=1 citations: - sys: id: 6D5UoHwwO4sg8gmUA8ikWs created_at: !ruby/object:DateTime 2015-11-26 10:37:10.022000000 Z updated_at: !ruby/object:DateTime 2016-07-22 19:38:21.856000000 Z content_type_id: citation revision: 2 citation_line: |+ <NAME>. 2009, *Rock Art*. In Willeke Wendrich (ed.), UCLA Encyclopedia of Egyptology, Los Angeles, p. 4 <NAME>. 2013. *Dating the rock art of Wadi Sura, in Wadi Sura – The Cave of Beasts*, <NAME>. (ed). Africa Praehistorica 26 – Köln: Heinrich-Barth-Institut, pp. 38-39 ---<file_sep>/_coll_thematic/hairdressing-in-the-acacus.md --- contentful: sys: id: R61tF3euwCmWCUiIgi42q created_at: !ruby/object:DateTime 2015-11-26 17:46:43.669000000 Z updated_at: !ruby/object:DateTime 2018-05-16 17:44:43.683000000 Z content_type_id: thematic revision: 5 title: Hairdressing in the Acacus slug: hairdressing-in-the-acacus lead_image: sys: id: 2PRW2sBJWgiEwA40U2GSiC created_at: !ruby/object:DateTime 2015-11-26 17:38:04.460000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:38:04.460000000 Z title: '2013,2034.477' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2PRW2sBJWgiEwA40U2GSiC/10eed798251d37d988ca686b32c6f42d/2013_2034.477.jpg" chapters: - sys: id: 6eJZLBozwQuAI08GMkwSi6 created_at: !ruby/object:DateTime 2015-11-26 17:42:35.115000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:42:35.115000000 Z content_type_id: chapter revision: 1 title_internal: 'Thematic: hairdressing, chapter 1' body: Hair is a global form of social communication. Among numerous social groups throughout Africa, hairstyling and hairdressing hold great cultural and aesthetic significance. Coiffures have been regarded as indicative of ethnic origin, gender and stages of life development – as well as simply fashion – and have been related to power, age, religion and politics. The transitory yet highly visible nature of hair ensures its suitability as a medium for personal and social expression. And it is not just the domain of women; elaborate hair-styling for men can be an equally important indicator of their place in society. - sys: id: 3w7Qbm8FOw2oqQsm6WsI0W created_at: !ruby/object:DateTime 2015-11-26 17:38:46.614000000 Z updated_at: !ruby/object:DateTime 2018-05-16 15:27:05.950000000 Z content_type_id: image revision: 2 image: sys: id: 5vt4IZCBSEmAQESGiGIS6Q created_at: !ruby/object:DateTime 2015-11-26 17:38:08.444000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:38:08.444000000 Z title: '2013,2034.479' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5vt4IZCBSEmAQESGiGIS6Q/8ea72bce196d2281a0a80d2c2a3b5b5b/2013_2034.479.jpg" caption: Seated figure showing elaborate coiffure. Wadi Teshuinat, Acacus Mountains, Fezzan District, Libya. 2013,2034.479 © TARA/<NAME>. col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3581661&partId=1&page=1 - sys: id: 6x5pF6pyus2WomGOkkGweC created_at: !ruby/object:DateTime 2015-11-26 17:42:59.906000000 Z updated_at: !ruby/object:DateTime 2018-05-16 15:29:46.989000000 Z content_type_id: chapter revision: 2 title_internal: 'Thematic: hairdressing, chapter 2' body: |- A particularly interesting set of images from Uan Amil in the Acacus Mountains, south-western Libya, reflect the cultural significance of hair in African societies. The scenes depict groups of people engaged in a variety of communal social practices wearing elaborate coiffures, together with some very discrete moments of personal hairdressing. The image below, which is part of a larger panel, shows an intimate moment between two persons, an individual with an ornate coiffure washing or attending to the hair of another. In some African societies, a person’s choice of hairdresser is dictated by their relationship to them. It is most often the work of friends or family to whom you entrust your hair. In the hands of a stranger or adversary hair can be used as an ingredient in the production a powerful substance that could afflict its owner - such is the potency of hair. This image conveys such intimacy. - sys: id: 1XeQI6NL3qeuiosIEoiESE created_at: !ruby/object:DateTime 2015-11-26 17:39:31.382000000 Z updated_at: !ruby/object:DateTime 2018-05-16 15:38:40.565000000 Z content_type_id: image revision: 2 image: sys: id: 2PRW2sBJWgiEwA40U2GSiC created_at: !ruby/object:DateTime 2015-11-26 17:38:04.460000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:38:04.460000000 Z title: '2013,2034.477' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2PRW2sBJWgiEwA40U2GSiC/10eed798251d37d988ca686b32c6f42d/2013_2034.477.jpg" caption: Figure on the left wears an ornate hairstyle and attends to the washing or preparation of another’s hair. 2013,2034.477 © TARA/<NAME>. col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3581665&partId=1&people=197356&museumno=+2013,2034.477&page=1 - sys: id: 2GniIJcZiUSuYWQYYeQmOS created_at: !ruby/object:DateTime 2015-11-26 17:43:22.643000000 Z updated_at: !ruby/object:DateTime 2018-05-16 15:40:09.594000000 Z content_type_id: chapter revision: 2 title_internal: 'Thematic: hairdressing, chapter 3' body: 'The rock shelter of Uan Amil was discovered in 1957 by the Italian-Libyan Joint Archaeological Mission surveying in the Acacus and Messak regions of Libya. Excavations have indicated the shelter was in use over a long period, with at least three main occupational phases between the 8th and 4th millennium BP. Italian archaeologist <NAME> has dated these paintings to 6,000 years ago, while David Coulson has been more cautious and has suggested that the presence of a metal blade on the arrow head seen at the bottom of this image may indicate a more recent age. Notwithstanding the problems associated with the dating of rock art, the subject matter is intriguing. It has been suggested that today’s Wodaabe nomads of Niger resemble the people on these rock paintings: ‘the cattle look the same, as do the campsites with their calf-ropes, and the women’s hairstyles with the special bun on the forehead. The female hair bun is big and round like a globe.’(Bovin, 2001:12).' - sys: id: 5Vp0rW88lqs6UcgaSm6egI created_at: !ruby/object:DateTime 2015-11-26 17:39:56.320000000 Z updated_at: !ruby/object:DateTime 2018-05-16 15:38:59.901000000 Z content_type_id: image revision: 2 image: sys: id: 1KUdkb6fbmW8KOsKWEcu02 created_at: !ruby/object:DateTime 2015-11-26 17:38:12.261000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:38:12.261000000 Z title: '2013,2034.473' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1KUdkb6fbmW8KOsKWEcu02/06c41b36730e0cbf81b105dd400c52ef/2013_2034.473.jpg" caption: This scene has been variously interpreted as showing preparations for a wedding. Note the hairwashing scene top right. 2013,2034.473 © TARA/David Coulson. col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3581674&partId=1&people=197356&museumno=2013,2034.473&page=1 - sys: id: 59XlSp8P7O0ms8UI0auQCw created_at: !ruby/object:DateTime 2015-11-26 17:43:42.266000000 Z updated_at: !ruby/object:DateTime 2018-05-16 16:33:15.417000000 Z content_type_id: chapter revision: 3 title_internal: 'Thematic: hairdressing, chapter 4' body: |- The Wodaabe number around 125,000. As pastoral nomads they migrate often and over large geographical areas, keeping mahogany-coloured Zebu cattle which have a hump on their back and long horns, shaped like a lyre. As a cultural group they have attracted much anthropological attention because of their traditional values of beauty (in particular the male beauty pageant) which pervades their everyday lives and practices. Wodaabe seldom wash their entire bodies mainly because of the scarcity of water. Water from wells is mainly used for drinking by humans and animals. Washing the body and clothes is less of a priority; and hair is hardly ever washed. When Wodaabe put rancid butter on their hair it is to make it soft and shiny and cleanse it of dust and lice. To them rancid butter gives a nice sweet smell (Bovin, 2001:56). In the above image ([2013,2034.473](http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3581674&partId=1&searchText=2013,2034.473&page=1)) at the top right, a vessel sits between the two individuals that may have served to hold rancid butter used in the preparation of the hair. In fact, treating the hair with butter is a widespread practice in African societies. In addition, Wodaabe never cut their hair. Men and women alike desire to have their hair as long as possible. The ideal girl should have long, thick black hair, enough to make a huge round bun on her forehead, while the ideal young male should have long, thick black hair to make braids to the shoulders. - sys: id: 5mnMqJRcbuQqk0ucEOAGCw created_at: !ruby/object:DateTime 2015-11-26 17:40:22.244000000 Z updated_at: !ruby/object:DateTime 2018-05-16 15:48:54.315000000 Z content_type_id: image revision: 2 image: sys: id: 2blaCOYdgYsqqCGakGIwoA created_at: !ruby/object:DateTime 2015-11-26 17:38:04.452000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:38:04.452000000 Z title: '2013,2034.453' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2blaCOYdgYsqqCGakGIwoA/5267369f7e2901448a0f0b0af93ca2a4/2013_2034.453.jpg" caption: Two herders wearing feathers in their hair. <NAME>, Acacus Mountains, Fezzan District, Libya. 2013,2034.453 © TARA/<NAME>. col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3581631&partId=1&people=197356&museumno=2013,2034.453&page=1 - sys: id: qhIjVs2Vxe4muMCWawu0k created_at: !ruby/object:DateTime 2015-11-26 17:44:06.559000000 Z updated_at: !ruby/object:DateTime 2018-05-16 16:32:51.163000000 Z content_type_id: chapter revision: 3 title_internal: 'Thematic: hairdressing, chapter 5' body: |- A long, narrow face is also admired and this is enhanced by shaping the hair on top of the head, and also using an ostrich feather to elongate the face (Bovin,2001:26). The painting above, from <NAME>, characterises this. Interestingly, the coiffures in the images here are light in colour and do not conform to the black ideal as indicated above. It has been suggested that this represents Caucasians with blonde hair. However, it may also be a visual strategy to emphasise the aesthetics of the coiffure. Hairstyles in African sculpture are often shown conceptually, rather than mimetically; idealising rather than copying exactly from contemporary hairdressing practices. In this respect representation follows artistic traditions as much as, or more than, it responds to ephemeral shifts in fashion. - sys: id: 6aPxu2uKyci0Kee8G4gQcm created_at: !ruby/object:DateTime 2015-11-26 17:40:47.827000000 Z updated_at: !ruby/object:DateTime 2018-05-16 15:54:21.695000000 Z content_type_id: image revision: 2 image: sys: id: 4gAFUKBZEsGKMie4cMomwS created_at: !ruby/object:DateTime 2015-11-26 17:38:04.460000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:38:04.461000000 Z title: '2013,2034.466' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4gAFUKBZEsGKMie4cMomwS/0770077ecb7b113ef266b26bfe368bb4/2013_2034.466.jpg" caption: Central figure ‘washing’ their hair while other social practices are taking place. Uan Amil, Libya. 2013,2034.466 © TARA/<NAME>oulson. col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3581646&partId=1&people=197356&museumno=2013,2034.466&page=1 - sys: id: 74IrMM3qGkksSuA4yWU464 created_at: !ruby/object:DateTime 2015-11-26 17:44:28.703000000 Z updated_at: !ruby/object:DateTime 2018-05-16 15:59:10.344000000 Z content_type_id: chapter revision: 2 title_internal: 'Thematic: hairdressing, chapter 6' body: The cultural importance of hair is evident where depictions of hair-washing, hairstyling or hair preparation are an active element within more complex social and cultural activities, such as preparations for a wedding or a scene of supplication. In addition, the C-shaped feature in the image above has been suggested to be a coiled snake, and the figure sits between the head and tail. It may seem incongruous to have hair preparation scenes represented within a tableau representing a wedding or ceremonial meeting, but may say something more about the nature of representation. In each case, these may represent a conceptual depiction of time and space. These activities are not ones that occur concurrently temporally and spatially, but rather represent an assemblage of discrete moments that contribute to each ceremony in its entirety. - sys: id: tvHqAC4aqc2QQWIS8WA26 created_at: !ruby/object:DateTime 2015-11-26 17:42:04.601000000 Z updated_at: !ruby/object:DateTime 2018-05-16 16:31:22.408000000 Z content_type_id: image revision: 2 image: sys: id: 1a8FFEsdsuQeYggMCAasii created_at: !ruby/object:DateTime 2015-11-26 17:38:04.449000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:38:04.449000000 Z title: '2013,2034.465' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1a8FFEsdsuQeYggMCAasii/9c5d70e5961bc74dc11f2170d2ae6b1c/2013_2034.465.jpg" caption: Larger panel from Uan Amil of a figure ‘washing’ their hair. This scene has been interpreted as a possible scene of supplication with people visiting a man in a curved shelter. 2013,2034.465 © TARA/<NAME>. col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3581647&partId=1&people=197356&museumno=2013,2034.465&page=1 - sys: id: 5qMQLHHz7Uqg460WGO6AW0 created_at: !ruby/object:DateTime 2015-11-26 17:44:46.392000000 Z updated_at: !ruby/object:DateTime 2018-05-16 16:32:18.314000000 Z content_type_id: chapter revision: 2 title_internal: 'Thematic: hairdressing, chapter 7' body: The Wodaabe invest vast amounts of time and resources in their outward appearance and the need to beautify and refine. ‘Art’ is not just something that is aesthetically pleasing - it is a necessity of life, a necessity that must be exhibited. While there are likely to be a variety of complex social, economic and cultural motivations, that necessity is possibly additionally driven or fuelled by a seemingly desolate, unadorned, irregular landscape. The importance lies in distinguishing oneself as a cultural being rather than the ‘uncultured other’, such as an animal; and hair is an apposite medium by which to make this nature/culture distinction. Hair care in African societies is unmistakably aesthetic in its aspirations as it gets transferred into other artistic mediums, and the divide between nature and culture is thoroughly and intentionally in play. To transform hair is to transform nature, and is truly an artistic discipline. citations: - sys: id: 5Sk9I9j7lm0wuUs2m4Qqw4 created_at: !ruby/object:DateTime 2018-05-16 16:34:37.564000000 Z updated_at: !ruby/object:DateTime 2018-05-16 16:34:37.564000000 Z content_type_id: citation revision: 1 citation_line: 'Bovin, Mette. 2001. Nomads Who Cultivate Beauty. Uppsala: Nordiska Afrikainstitutet' background_images: - sys: id: 1uxzHwxp9GEUy2miq0C0mM created_at: !ruby/object:DateTime 2015-12-07 18:44:13.394000000 Z updated_at: !ruby/object:DateTime 2015-12-07 18:44:13.394000000 Z title: '01567916 001' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1uxzHwxp9GEUy2miq0C0mM/9c706cad52d044e1d459bba0166ec2fb/01567916_001.jpg" - sys: id: 3drvdVaCYoMs04ew2sIE8Y created_at: !ruby/object:DateTime 2015-12-07 18:43:47.560000000 Z updated_at: !ruby/object:DateTime 2015-12-07 18:43:47.560000000 Z title: 2013,2034.466 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3drvdVaCYoMs04ew2sIE8Y/78d8f39af68d603fbc8a46c745148f0e/2013_2034.466_1.jpg" ---<file_sep>/_coll_country_information/somalia-somaliland-country-introduction.md --- contentful: sys: id: 2DBcI8BWaU6mcgAKK6KCsE created_at: !ruby/object:DateTime 2015-11-26 18:31:41.871000000 Z updated_at: !ruby/object:DateTime 2015-12-07 13:43:18.317000000 Z content_type_id: country_information revision: 3 title: 'Somalia/ Somaliland: country introduction' chapters: - sys: id: 1KQNUoZNrCkAQ2SymEAMC created_at: !ruby/object:DateTime 2015-11-26 18:26:17.254000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:26:17.254000000 Z content_type_id: chapter revision: 1 title: Introduction title_internal: 'Somalia: country, chapter 1' body: Somalia is a country located at the corner of the Horn of Africa, bordered by Djibouti, Ethiopia and Kenya. Somaliland self-declared independence from Somalia in 1991 although the government of Somalia has not recognised this and views it as an autonomous region. A cultural and economic crossroads between Middle East, Africa and Asia, this area has historically been the centre of trade routes that linked these regions. It also has a very rich rock art heritage which has only recently been started to be studied in depth. Most of the known depictions correspond to painted or engraved cattle scenes, often accompanied by human figures, dogs and other domestic animals, although some warriors, camels and geometric symbols (sometimes interpreted as tribal marks) are common too. - sys: id: 3dA1xqkTa0mKwo2mQcASWm created_at: !ruby/object:DateTime 2015-11-26 18:23:03.983000000 Z updated_at: !ruby/object:DateTime 2018-05-17 16:37:53.141000000 Z content_type_id: image revision: 2 image: sys: id: 4n4aYQQ3ws86seSuSQC2Q0 created_at: !ruby/object:DateTime 2015-11-26 18:17:32.780000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:17:32.780000000 Z title: '2013,1023.15855' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4n4aYQQ3ws86seSuSQC2Q0/dbb3602a28b6144aa4c317fe75196363/SOMLAG0030004.jpg" caption: Figure of painted cattle and human figures, with a semi-desert plain in the background. <NAME>, Somaliland. 2013,1023.15855 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3691566&partId=1&people=197356&place=41067%7c27048%7c1665&view=list&page=2 - sys: id: 2OBCFk5x3OmouqCga48C8U created_at: !ruby/object:DateTime 2015-11-26 18:26:58.643000000 Z updated_at: !ruby/object:DateTime 2017-01-11 14:18:51.197000000 Z content_type_id: chapter revision: 2 title: Geography and rock art distribution title_internal: 'Somalia: country, chapter 2' body: 'The geography of Somaliland is characterized by a coastal semi-desert plain which runs parallel to the Gulf of Aden coast, crossed by seasonal rivers (wadis) which make possible some grazing during the rainy season. Farther to the south, this semi-desert plain gives rise to the Karkaar Mountains. These mountains, which run from Somaliland into the region of Puntland in Somalia, have an average height of 1800 meters above sea level and run west to east until Ras Caseyr (Cape Guardafui) where the north and east coasts of the Horn of Africa meet. Southward to the mountains there is a big, dry plateau known as the Ogo, whose western part (the Haud) is one of the few good grazing areas in the country. The Ogo plateau occupies much of central and eastern Somalia, which to the south is characterized by the two only permanent rivers in the country, the Jubba and the Shabeele, born in the Ethiopian highlands and running to the south. Regarding rock art, the distribution of the known rock art sites shows a high concentration in Somaliland, with only some sites located to the south in the Gobolka Hiiraan region. However, this distribution could be a result of lack of research in other areas. ' - sys: id: 2OM3VEqOV2esQye48QAu2s created_at: !ruby/object:DateTime 2015-11-26 18:23:30.937000000 Z updated_at: !ruby/object:DateTime 2017-01-11 14:21:01.481000000 Z content_type_id: image revision: 2 image: sys: id: 2mLUneHM24eEYEQ8W4EKsq created_at: !ruby/object:DateTime 2015-11-26 18:18:00.392000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:18:00.392000000 Z title: '2013,2034.15623' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2mLUneHM24eEYEQ8W4EKsq/53eef5b06e2341da0768225d38e7847c/SOMGABNAS010005.jpg" caption: Semi-desert landscape in Somaliland. Dhaga Koure. 2013,2034.15623 © TARA/David Coulson col_link: http://bit.ly/2jDoZeS - sys: id: 41tEkwH3cIckAgeM0MaO6o created_at: !ruby/object:DateTime 2015-11-26 18:27:28.491000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:27:28.491000000 Z content_type_id: chapter revision: 1 title: Research history title_internal: 'Somalia: country, chapter 3' body: A reconstruction of rock art research history is challenging due to its contemporary history. To begin with, during the colonial period the country was divided in three different territories (British, Italian and French) with very different trajectories, until 1960 when the British and Italian territories joined to create Somalia. In British Somaliland the first studies of rock art were carried out by <NAME> and <NAME> in the 1940s, and the first general overview was published in 1954 by <NAME>, as a part of a regional synthesis of the Horn of Africa prehistory, followed by limited research done by Italians in the north-east region in the late 1950s. Since then, research has been limited, with some general catalogues published in the 1980s and 1990s, although political instability has often prevented research, especially in the south-eastern region of Somalia. In fact, most rock art information comes from wider regional syntheses dedicated to the Horn of Africa. In the early 2000’s the discovery of the Laas Geel site led to a renewed interest in rock art in Somaliland, which has allowed a more systematic study of archaeological sites. Nowadays, about 70 of these sites have been located only in this area, something which shows the enormous potential of rock art studies in the Horn of Africa. - sys: id: 4w2Oo8iJG0A6a6suMusm8c created_at: !ruby/object:DateTime 2015-11-26 18:24:00.701000000 Z updated_at: !ruby/object:DateTime 2017-01-11 14:22:27.659000000 Z content_type_id: image revision: 2 image: sys: id: 3mWyGCLGFacW2aOUYmGQWs created_at: !ruby/object:DateTime 2015-11-26 18:19:01.529000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:19:01.529000000 Z title: '2013,2034.16100' description: url: "//images.ctfassets.net/xt8ne4gbbocd/3mWyGCLGFacW2aOUYmGQWs/066214022447d9fbe76ff624e2887a57/SOMLAG0100001.jpg" caption: View of engraved cattle with lyre-like horns and marked udders. Laas Geel. 2013,2034.16100© TARA/<NAME> col_link: http://bit.ly/2j68Ld2 - sys: id: 4gYGUVBkbKwWYqUwAsMs0U created_at: !ruby/object:DateTime 2015-11-26 18:27:53.242000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:27:53.242000000 Z content_type_id: chapter revision: 1 title: Themes title_internal: 'Somalia: country, chapter 4' body: The rock art has traditionally been ascribed to the so-called Ethiopian-Arabican style, a term coined by Pavel Červiček in 1971 to remark the strong stylistic relationship between the rock art found in the Horn of Africa and the Arabian Peninsula. According to this proposal, there was a progressive evolution from naturalism to schematism, perceptible in the animal depictions throughout the region. Wild animals seem to be largely absent but for Djibouti, while cattle depictions seem to have been fundamental elsewhere, either isolated or in herds. Such is the case with rock art in this region, where cows and bulls are the most common depictions, in many cases associated to human figures in what seems to be reverential or ritual scenes. In some of the sites, such as Laas Geel, the necks of the cows have been decorated with complex geometric patterns interpreted as a kind of mat used in special occasions to adorn them. - sys: id: LmEAuSwhEG6iuQ6K8CioS created_at: !ruby/object:DateTime 2015-11-26 18:24:22.355000000 Z updated_at: !ruby/object:DateTime 2017-01-11 14:26:37.550000000 Z content_type_id: image revision: 2 image: sys: id: 10vxtVrFIcuoaww8gEKCSY created_at: !ruby/object:DateTime 2015-11-26 18:19:22.576000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:19:22.576000000 Z title: '2013,2034.15935' description: url: "//images.ctfassets.net/xt8ne4gbbocd/10vxtVrFIcuoaww8gEKCSY/c4d210b0ddd69dd44e5bcd59cdecc875/SOMLAG0070012.jpg" caption: View of painted cattle and human figures. Laas Geel, Somaliland. 2013,2034.15935 © TARA/<NAME> col_link: http://bit.ly/2jiF5XI - sys: id: 2twRKjr52EwkSI0UMUIws4 created_at: !ruby/object:DateTime 2015-11-26 18:28:12.916000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:28:12.916000000 Z content_type_id: chapter revision: 1 title_internal: 'Somalia: country, chapter 5' body: Along with cattle, other animals were represented (humped cows or zebus, dogs, sheep, dromedaries), although to a much lesser extent. Wild animals are very rare, but giraffes have been documented in Laas Geel and elephants and antelopes in Tug Gerbakele, and lions are relatively common in the schematic, more modern depictions. Human figures also appear, either distributed in rows or isolated, sometimes holding weapons. Geometric symbols are also common, usually associated with other depictions. In Somalia, these symbols have often been interpreted as tribal or clan marks. With respect to techniques, both engraving and painting are common, although paintings seem to be predominant. - sys: id: 2gSkte21PuqswWM2Q804gi created_at: !ruby/object:DateTime 2015-11-26 18:24:47.061000000 Z updated_at: !ruby/object:DateTime 2017-01-12 16:00:51.600000000 Z content_type_id: image revision: 2 image: sys: id: 20zCz4hAbmiSm0MuGIkGQk created_at: !ruby/object:DateTime 2015-11-26 18:19:38.412000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:19:38.412000000 Z title: '2013,2034.15386' description: url: "//images.ctfassets.net/xt8ne4gbbocd/20zCz4hAbmiSm0MuGIkGQk/d36ff89e5284f1536daa5c3c82e345be/SOMDHA0020008.jpg" caption: Panel or relatively modern chronology showing painted white camels, unidentified quadrupeds and signs. <NAME>, Somaliland. 2013,2034.15386© TARA/David Coulson col_link: http://bit.ly/2j4Q3Ar - sys: id: 5QuYRZm7SMewQCgO0g2sE2 created_at: !ruby/object:DateTime 2015-11-26 18:28:43.949000000 Z updated_at: !ruby/object:DateTime 2015-12-11 12:13:57.212000000 Z content_type_id: chapter revision: 2 title: Chronology title_internal: 'Somalia: country, chapter 6' body: As in many other places, the establishment of accurate chronologies for Somaliland rock art is challenging. In this case, the lack of long term research has made things more difficult, and most hypotheses have been based in stylistic approaches, analysis of depictions and a small set of radiocarbon data and archaeological excavations. According to this, the oldest depictions could be dated to between the mid-3rd and the 2rd millennium BC, although older dates have been proposed for Laas Geel. This phase would be characterized by humpless cows, sheep and goats as well as wild animals. These sites would indicate the beginning of domestication in this region, the cattle being as a fundamental pillar of these communities. From this starting point the relative antiquity of the depictions would be marked by a tendency to schematism, visible in the superimpositions of several rock art sites. The introduction of camels would mark a chronology of the end of the first millennium BC, while the date proposed for the introduction of zebus (humped cows) should be placed at between the 1st Centuries BC and AD. - sys: id: 5Qtce93TSEks2Ukmks8e4E created_at: !ruby/object:DateTime 2015-11-26 18:25:07.168000000 Z updated_at: !ruby/object:DateTime 2017-01-12 16:24:38.017000000 Z content_type_id: image revision: 2 image: sys: id: 22wpEosKyYwyycaMgSmQMU created_at: !ruby/object:DateTime 2015-11-26 18:21:17.860000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:21:17.860000000 Z title: '2013,2034.15564' description: url: "//images.ctfassets.net/xt8ne4gbbocd/22wpEosKyYwyycaMgSmQMU/526e6ce44e5bf94379b55b2551a44b18/SOMGAB0050003.jpg" caption: Humped white cow. Dhaga Khoure, Somaliland. 2013,2034.15564 © TARA/David Coulson col_link: http://bit.ly/2ikqWb2 - sys: id: uPwtnjPhmK6y4kUImq4g8 created_at: !ruby/object:DateTime 2015-11-26 18:29:03.262000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:29:03.262000000 Z content_type_id: chapter revision: 1 title_internal: 'Somalia: country, chapter 7' body: Since the 1st millennium BC human figures armed with lances, bows and shields start to appear alongside the cattle, in some cases distributed in rows and depicting fighting scenes against other warriors or lions. The moment when this last period of rock art ended is unknown, but in nearby Eritrea some of these figures were depicted with firearms, thus implying that they could have reached a relatively modern date. - sys: id: PLXVZ70YMuKQuMOOecEIi created_at: !ruby/object:DateTime 2015-11-26 18:25:31.222000000 Z updated_at: !ruby/object:DateTime 2018-09-19 15:23:32.358000000 Z content_type_id: image revision: 3 image: sys: id: 4njSKDcdtuaCGiSKGKmGEa created_at: !ruby/object:DateTime 2015-11-26 18:21:32.901000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:21:32.901000000 Z title: '2013,2034.15617' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4njSKDcdtuaCGiSKGKmGEa/04b2b2ab0529ebec8831b47816d7f5f2/SOMGAB0090007.jpg" caption: 'Detail of painted rock art depicting two human figures and a humped cow, infilled in red and yellow. <NAME>, Somaliland. 2013,2034.15616 © TARA/<NAME> ' col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3711116&partId=1&searchText=2013,2034.15616+&page=1 citations: - sys: id: 62GO9AUWhq0GgwQC6keQAU created_at: !ruby/object:DateTime 2015-11-26 18:32:25.937000000 Z updated_at: !ruby/object:DateTime 2015-12-11 12:13:02.046000000 Z content_type_id: citation revision: 2 citation_line: | <NAME>. (1998): Contributo alla conoscenza dell’arte rupestre somala. *Rivista di Scienze Prehistoriche*, 49 (225-246). <NAME>. (1954): *The Prehistoric Cultures of the Horn of Africa*. Octagon Press, New York. <NAME>. (2015), Mapping the Archaeology of Somaliland: Religion, Art, Script, Time, Urbanism, Trade and Empire, *African Archaeological Review* 32(1): 111-136. ---<file_sep>/_coll_country/south-africa/gamepass.md --- breadcrumbs: - label: Countries url: "../../" - label: South Africa url: "../" layout: featured_site contentful: sys: id: 2XOggE9Gxaew6iMMKS4E4U created_at: !ruby/object:DateTime 2016-09-12 15:15:32.469000000 Z updated_at: !ruby/object:DateTime 2016-09-13 13:35:15.580000000 Z content_type_id: featured_site revision: 2 title: Game Pass Shelter, South Africa slug: gamepass chapters: - sys: id: 5WhcFBd6owA0UwoG6iOg4Y created_at: !ruby/object:DateTime 2016-09-12 15:12:00.222000000 Z updated_at: !ruby/object:DateTime 2016-09-13 13:34:42.735000000 Z content_type_id: chapter revision: 6 title: Game Pass Shelter, South Africa title_internal: 'South Africa: featured site, chapter 1' body: "Game Pass shelter is one of the most well-known rock art sites in South Africa. Situated in the foothills of the Drakensberg mountains, a sandstone recess atop a steep slope contains rock paintings made by people from the San&#124;Bushman¹ communities who historically lived as hunter-gatherers throughout southern Africa. The Drakensberg mountains in particular are known for their wealth of rock paintings, often showing detailed and brightly coloured images of people, animals and part-human, part-animal figures known as ‘therianthropes’, with this site a prime example. One of the panels of paintings here is particularly important in the history of rock art research, as in the 1970s it helped to inspire a new kind of approach to the understanding of the meanings and symbolism of San&#124;Bushman paintings and engravings.\n\n" - sys: id: 6mZ8n44JbyOIMKaQYKgm4k created_at: !ruby/object:DateTime 2016-09-12 15:12:11.338000000 Z updated_at: !ruby/object:DateTime 2018-05-15 13:55:27.144000000 Z content_type_id: image revision: 2 image: sys: id: XICyV4qumymqa8eIqCOeS created_at: !ruby/object:DateTime 2016-09-12 15:12:27.902000000 Z updated_at: !ruby/object:DateTime 2016-09-12 15:12:27.902000000 Z title: SOADRB0080002 description: url: "//images.ctfassets.net/xt8ne4gbbocd/XICyV4qumymqa8eIqCOeS/5c82b58cf67f6c300485aea40eb5b05a/SOADRB0080002.jpg" caption: View of the Game Pass Shelter from below. 2013,2034.18363 ©TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3730908&partId=1&searchText=2013,2034.18363&page=1 - sys: id: 3xOl8hqio0E2wYYKIKomag created_at: !ruby/object:DateTime 2016-09-12 15:12:45.525000000 Z updated_at: !ruby/object:DateTime 2018-05-15 13:57:48.547000000 Z content_type_id: image revision: 2 image: sys: id: 3cyElw8MaIS24gq8ioCcka created_at: !ruby/object:DateTime 2016-09-12 15:12:39.975000000 Z updated_at: !ruby/object:DateTime 2016-09-12 15:12:39.975000000 Z title: SOADRB0080007 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3cyElw8MaIS24gq8ioCcka/fcea216b7327f325bf27e3cebe49378e/SOADRB0080007.jpg" caption: Painted panel showing multiple eland antelope and other figures. 2013,2034.18368 ©TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3730846&partId=1&searchText=2013,2034.18368&page=1 - sys: id: 3ilqDwqo80Uq6Q42SosqQK created_at: !ruby/object:DateTime 2016-09-12 15:12:59.726000000 Z updated_at: !ruby/object:DateTime 2018-05-15 13:59:22.144000000 Z content_type_id: chapter revision: 5 title_internal: 'South Africa: featured site, chapter 2' body: The most prominent painting panel at Game Pass shows a series of carefully depicted eland antelope in delicately shaded red, brown and white pigment, largely super imposing a group of ambiguous anthropomorphic figures wrapped in what appear to be bell-shaped karosses (traditional skin cloaks). Several small human figures appear to be running above them. These are some of the best-preserved rock paintings in the Drakensberg, with the largest animals around 30 cm long. To the left of this panel are two smaller sets of images, one with two further eland, some further human-like figures and a human figure with a bow; the other a small panel, for which the site is most renowned. An image around 50 cm long shows an eland with its face turned towards the viewer, depicted as if stumbling forwards, with its hind legs crossed. Grasping the eland's tail is a therianthrope figure with hooves for feet. Like the eland, this figure has its legs crossed and is depicted with small lines like raised hairs bristling from its body. To the right are three further therianthrope figures. - sys: id: 3oYyhNlOdWu4oaoG0qUEGC created_at: !ruby/object:DateTime 2016-09-12 15:13:08.484000000 Z updated_at: !ruby/object:DateTime 2018-05-15 14:02:39.599000000 Z content_type_id: image revision: 3 image: sys: id: 777S5VQyBO0cMwKC0ayqKe created_at: !ruby/object:DateTime 2016-09-12 15:13:12.516000000 Z updated_at: !ruby/object:DateTime 2016-09-12 15:13:12.516000000 Z title: SOADRB0080015 description: url: "//images.ctfassets.net/xt8ne4gbbocd/777S5VQyBO0cMwKC0ayqKe/67d88e9197416be62cc8ccc0b576adf9/SOADRB0080015.jpg" caption: Panel showing an eland antelope with crossed legs and a therianthrope figure grasping its tail. 2013,2034.18376 ©TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3730898&partId=1&searchText=2013,2034.18376&page=1 - sys: id: 3t21DyQhhu6KYE24yOuW6E created_at: !ruby/object:DateTime 2016-09-12 15:13:26.839000000 Z updated_at: !ruby/object:DateTime 2018-05-15 14:02:03.671000000 Z content_type_id: chapter revision: 2 title_internal: 'South Africa: featured site, chapter 3' body: The rock paintings from this site were first brought to public attention in a 1915 issue of Scientific American, and it has been frequently published on and discussed through the 20th century. While studying a reproduction of the image with the stumbling eland in the early 1970s, researcher <NAME> began to consider that the figure holding the eland's tail might not be a simple illustration of a man wearing a skin suit, or performing an act of bravura, as had been suggested by previous researchers, but might be “idiomatic and metaphorical, rather than illustrative” (Lewis-Williams 1981:91). - sys: id: 8JKh5DFTLqMsaCQWAAA4c created_at: !ruby/object:DateTime 2016-09-12 15:13:41.069000000 Z updated_at: !ruby/object:DateTime 2018-05-15 14:03:14.804000000 Z content_type_id: image revision: 2 image: sys: id: 2QyopQgIx2AAMU46gEM2Wg created_at: !ruby/object:DateTime 2016-09-12 15:13:36.176000000 Z updated_at: !ruby/object:DateTime 2016-09-12 15:13:36.176000000 Z title: SOADRB0080017 description: url: "//images.ctfassets.net/xt8ne4gbbocd/2QyopQgIx2AAMU46gEM2Wg/614f0c5c375d7d8e8e9be93ce2179a18/SOADRB0080017.jpg" caption: The figure holding the eland’s tail has similar qualities to the eland itself. 2013,2034.1838 ©TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3730897&partId=1&place=107937&plaA=107937-2-2&page=1 - sys: id: 1l6QCXODlWoa6kmgWAgco2 created_at: !ruby/object:DateTime 2016-09-12 15:13:55.229000000 Z updated_at: !ruby/object:DateTime 2016-09-30 16:42:50.171000000 Z content_type_id: chapter revision: 3 title_internal: 'South Africa: featured site, chapter 4' body: "This idea was partly inspired by the testimony of Qing, a San&#124;Bushman man who, in 1873, had guided the Colonial Administrator <NAME> to rock art sites in the mountains of Lesotho, with which the Drakensberg forms a natural eastern border with South Africa and which also contains many rock paintings. Qing's explanations of the paintings, some of which Orpen copied, included a reference to antelope-headed human figures having “died and gone to live in rivers, who were spoilt at the same time as the elands and… by the dances of which you have seen paintings”. This, along with testimony and practices recorded from other South African San&#124;Bushman people at the time, as well as those living elsewhere in south-western Africa in the 20th century, suggested to Lewis-Williams that these and other images in San&#124;Bushman rock art may be a reference to the activities of spiritual leaders or 'shamans', people who, in San&#124;Bushman communities, are believed to have the power to interact with spirits and the spirit world in ways which may affect the physical world. \n\nLewis-Williams and other proponents of this 'shamanistic' approach to interpreting San&#124;Bushman rock art have proposed that much of its imagery is in fact related to the shaman's experience during the 'trance dance' ritual found in all San&#124;Bushman socie-ties. During this activity the shaman enters a hallucinatory state in which spiritual ‘tasks’ such as healing the sick may be undertaken on behalf of the community. On entering the trance state the shaman experiences trembling, sweating, stumbling and other symptoms similar to those of a dying antelope hit by a poisoned arrow. <NAME> noted that among some San&#124;Bushman people this process is referred to as ‘dying’ or being ‘spoilt’ and considered that the similarities between the eland and the therianthrope figure in this image represent this conceived equivalence.\n\n" - sys: id: 4cmGHIbGFqOEqYWwyi0S2e created_at: !ruby/object:DateTime 2016-09-12 15:14:08.008000000 Z updated_at: !ruby/object:DateTime 2018-05-15 14:05:13.185000000 Z content_type_id: image revision: 2 image: sys: id: 5qjFwYmXkca88mMcWSiGgc created_at: !ruby/object:DateTime 2016-09-12 15:14:04.272000000 Z updated_at: !ruby/object:DateTime 2016-09-12 15:14:04.272000000 Z title: SOADRB0010012 description: url: "//images.ctfassets.net/xt8ne4gbbocd/5qjFwYmXkca88mMcWSiGgc/761a55733ca2935fd7056e1a0de33dd6/SOADRB0010012.jpg" caption: Two eland antelope running in the Drakensberg. 2013,2034.18180 ©TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3729855&partId=1&searchText=2013,2034.18180&page=1 - sys: id: 1VRoS6FN4ga60gcYImm6c2 created_at: !ruby/object:DateTime 2016-09-12 15:14:20.350000000 Z updated_at: !ruby/object:DateTime 2016-09-30 16:47:30.231000000 Z content_type_id: chapter revision: 4 title_internal: 'South Africa: featured site, chapter 5' body: | Despite the historical presence of other large game animals in the Drakensberg, the eland is the most commonly depicted animal in rock art of the region. <NAME>, noting this and the focus on other particular subjects in the imagery at the expense of others, proposed in her pioneering 1976 study of the rock art of the Southern Drakensberg *People of the Eland* that the paintings are “not a realistic reflection of the daily pursuits or environment of the Bushmen” (Vinnicombe 1976:347). Vinnicombe recalled that when, in the 1930s, an old Sotho man named Mapote, who had San&#124;Bushman half-siblings and had used to paint with them, was requested to demonstrate, he had said that since the San&#124;Bushmen had been “of the eland”, he should first depict an eland. Based on this and recountings of a myth about the creation and death of the first eland from Qing and other contemporary Southern San&#124;Bushman people, Vinnicombe concluded that the eland, although regularly hunted by the Drakensberg San&#124;Bushmen, had been a particularly sacred or powerful animal to them and that “Through the act of painting and re-painting the eland… the mental conflict involved in destroying a creature that was prized and loved by their deity…was…ritually symbolised and resolved” (Vinnicombe, 1976:350). Building on the idea of the spiritual significance of the eland, the approach proposed by Lewis-Williams offered an alternative interpretation by inferring from ethnography that eland were believed to have spiritual ‘potency’. As part of a complex system of beliefs involving conceptions of power and potency in relation to animals and rites, this potency could be released upon death, with trancing shamans believed to be able to harness it, feeling themselves taking on the attributes of the animal. Thus therianthrope figures like those depicted here may be interpreted as representing hallucinatory experiences of shamans in trance, where they may feel that they are assuming the forms of other animals. It has been argued that other motifs such as geometric forms known as 'entoptics' represent the abstract patterns created by neural networks and ‘seen’ during the early stages of entering an altered state of consciousness and that the paintings themselves may have been created as reservoirs of spiritual potency. - sys: id: n044NT3TZAYwKSakkogoU created_at: !ruby/object:DateTime 2016-09-12 15:14:38.475000000 Z updated_at: !ruby/object:DateTime 2018-05-15 14:05:31.169000000 Z content_type_id: image revision: 2 image: sys: id: 60II5zuUne2A80682sYYs2 created_at: !ruby/object:DateTime 2016-09-12 15:14:34.660000000 Z updated_at: !ruby/object:DateTime 2016-09-12 15:14:34.660000000 Z title: SOADRB0080019 description: url: "//images.ctfassets.net/xt8ne4gbbocd/60II5zuUne2A80682sYYs2/bbee114e572cf8a7a403d6802749707c/SOADRB0080019.jpg" caption: Eland and faded figures. 2013,2034.18391 ©TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3730884&partId=1&place=107937&plaA=107937-2-2&page=1 - sys: id: 5Lheod1OGAYUW4Goi6GAUo created_at: !ruby/object:DateTime 2016-09-12 15:14:46.323000000 Z updated_at: !ruby/object:DateTime 2016-09-30 16:49:04.072000000 Z content_type_id: chapter revision: 2 title_internal: 'South Africa: featured site, chapter 6' body: "The shamanistic approach to interpreting San&#124;Bushman rock art images, for which the Game Pass panel is sometimes referred to as the ‘Rosetta Stone’, gained popularity in the 1980s and has since become the dominant interpretative framework for researchers. Debate continues about the extent and nature of its applicability in all of San&#124;Bushman rock art, and the extent to which myth and ritual not associated with the trance dance may also inform the art. Work that connects San&#124;Bushman cosmology and practice with images from sites like Game Pass continue to provide interesting insights into these enigmatic images. \n\nGame Pass Shelter and many other rock art sites are situated within the Maloti-Drakensberg Park, which was inscribed as a UNESCO Transboundary World Heritage Site in 2000. The site is open to the public and accessible via a trail from the Kamberg Rock Art Centre.\n\n" - sys: id: 4XwNgMsBPaQ06My8Qs4gKU created_at: !ruby/object:DateTime 2016-09-13 13:35:11.603000000 Z updated_at: !ruby/object:DateTime 2016-09-13 13:35:11.603000000 Z content_type_id: chapter revision: 1 title_internal: 'South Africa Featured Site Chapter 7 ' body: "¹ San&#124;Bushmen is a collective term used to describe the many different hunter-gatherer-fisher groups living in southern Africa who have related languages and cultural traditions. Both 'San' and 'Bushmen' are considered offensive terms by some members of these groups, although others have positively adopted them." citations: - sys: id: 3brqyMy1K0IC0KyOc8AYmE created_at: !ruby/object:DateTime 2016-09-12 15:14:59.720000000 Z updated_at: !ruby/object:DateTime 2016-09-12 15:14:59.720000000 Z content_type_id: citation revision: 1 citation_line: | <NAME>. 2009. 'Contested Histories: A Critique of Rock Art in the Drakens-berg Mountains' in Visual Anthropology 22:4, pp. 327 — 343 <NAME>. 1981. Believing and Seeing: Symbolic Meanings in San&#124;Bushman Rock Paintings. Johannesburg, University of Witwatersrand Press Vinnicombe, P. 1976. People of The Eland: Rock paintings of the Drakensberg Bushmen as a reflection of their life and thought. Pietermaritzburg, University of Natal Press Solomon, A. 1997. ‘The Myth of Ritual Origins: Ethnography, Mythology and Interpre-tation of San&#124;Bushman Rock Art’. South African Archaeological Bulletin 53, pp.3-13 <NAME>., & <NAME>. Art on the Rocks of Southern Africa. London, Mac-donald background_images: - sys: id: 6qIbC41P8IM2O8K4w6g0Ec created_at: !ruby/object:DateTime 2016-09-12 15:15:14.404000000 Z updated_at: !ruby/object:DateTime 2016-09-12 15:15:14.404000000 Z title: SOADRB0080001 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6qIbC41P8IM2O8K4w6g0Ec/60009e28497973bd9682d19ba5a9d497/SOADRB0080001.jpg" - sys: id: ARPF2hJVwOYm0iaAgUmk0 created_at: !ruby/object:DateTime 2016-09-12 15:15:22.171000000 Z updated_at: !ruby/object:DateTime 2016-09-12 15:15:22.171000000 Z title: SOADRB0080039 description: url: "//images.ctfassets.net/xt8ne4gbbocd/ARPF2hJVwOYm0iaAgUmk0/40e2845d0ffe86c19d674886a3721b10/SOADRB0080039.jpg" ---<file_sep>/_layouts/thematic_index.html --- layout: default --- {% assign collection = site.collections | where: "label", page.collection | first %} <div class="container"> <h1 class="page-heading">Explore {{ page.title }} </h1> {% for item in collection.docs %} {% assign introduction = item.contentful.chapters | where: "sys.content_type_id", "chapter" | first %} {% assign image = item.contentful.lead_image %} <div class="column-three-quarters collapsed"> <div class="card"> <div class="container"> <div class="column-eight-tenth card-content"> <h2 class="title"> <a href="{{ item.url | relative_url }}">{{ item.contentful.title }}</a> </h2> <p>{{ introduction.body | truncatewords: 45 }}</p> </div> <div class="column-two-tenth"> <div class="square-thumbnail"> <a href="{{ item.url | relative_url }}"> {% include image.html image=image %} </a> </div> </div> </div> </div> </div> {% endfor %} </div><file_sep>/_coll_introduction/techniques.md --- contentful: sys: id: 5j76DfcDwk28WOmWMAm20C created_at: !ruby/object:DateTime 2015-11-26 09:47:55.196000000 Z updated_at: !ruby/object:DateTime 2018-05-25 16:57:49.881000000 Z content_type_id: introduction revision: 6 title: Techniques of production slug: techniques lead_image: - sys: id: 4uVUj08mRGOCkmK64q66MA created_at: !ruby/object:DateTime 2016-09-26 14:46:35.956000000 Z updated_at: !ruby/object:DateTime 2019-02-12 02:01:17.553000000 Z title: '2013,2034.20476' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3730556&partId=1&searchText=NAMDMT0010010&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/4uVUj08mRGOCkmK64q66MA/c1c895d4f72a2260ae166ab9c2148daa/NAMDMT0010010.jpg" chapters: - sys: id: 3ATyteWLBeyy0IU6cUY8cc created_at: !ruby/object:DateTime 2015-11-26 09:42:50.596000000 Z updated_at: !ruby/object:DateTime 2015-11-26 09:42:50.596000000 Z content_type_id: chapter revision: 1 title: Introduction title_internal: 'General: how made, chapter 1' body: 'Rock art has been practised for tens of thousands of years and the techniques by which the paintings and engravings are created, while varied, conform to basic principles related to resources and technology. An equally important factor is where the image is placed. Not every rock surface is appropriate to inscribe, some may need preparing beforehand. While much research focus is generally given over to subject matter, dating and meaning in rock art studies, consideration of the techniques of production can provide some insightful observations into the methodologies by which images are created. Technically speaking, images can be broadly classified into two main groups: petroglyphs and pictographs. Petroglyphs are engraved or carved depictions on a rock surface; pictographs are painted images on a rock surface.' - sys: id: HYM6VlWCu2Uk28UwcI6qw created_at: !ruby/object:DateTime 2015-11-26 09:40:34.705000000 Z updated_at: !ruby/object:DateTime 2016-12-19 17:12:00.737000000 Z content_type_id: image revision: 2 image: sys: id: 53weII16ScuU6AQ6qWwIuS created_at: !ruby/object:DateTime 2015-11-26 09:39:59.713000000 Z updated_at: !ruby/object:DateTime 2015-11-26 09:39:59.713000000 Z title: '2013,2034.4108' description: url: "//images.ctfassets.net/xt8ne4gbbocd/53weII16ScuU6AQ6qWwIuS/bceed94a08e062929a8c23605155d23f/2013_2034.4108.jpg" caption: Bichrome antelope. <NAME>, <NAME>’Ajjer, Algeria. 2013,2034.4108 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3595543&partId=1&museumno=2013,2034.4108&page=1 - sys: id: 1rfIlXAQBWuOMK4sqiAwau created_at: !ruby/object:DateTime 2015-11-26 09:43:30.234000000 Z updated_at: !ruby/object:DateTime 2015-11-26 09:43:30.234000000 Z content_type_id: chapter revision: 1 title: Pictographs - Painting title_internal: 'General: how made, chapter 2' body: The pigments used in paintings are dependent on local resources, but typically have been made of minerals such as ochre that comes in a variety of red, brown and yellow hues. White is derived from silica, china clay and gypsum and black is obtained from manganese minerals, charcoal or specularite. Once collected these minerals were ground to form a powder and mixed with liquids such as egg albumen, urine, blood, saliva or water to make the pigment easier to apply and to act as a binding agent. Current research is exploring new methods to be able to date these ingredients. A variety of tools have been used to apply the pigment onto rock surfaces including birds’ feathers, animal hair, grasses or reeds and fingers. This process is not simply a technological one, and for many cultural groups the pigment itself and the method of application are imbued with symbolic meaning. - sys: id: 5FvF7jgtQkqSuK6gcScAks created_at: !ruby/object:DateTime 2015-11-26 09:41:14.113000000 Z updated_at: !ruby/object:DateTime 2016-12-19 17:14:58.388000000 Z content_type_id: image revision: 2 image: sys: id: 5eo1GYHRFS6SYSWoum4Usy created_at: !ruby/object:DateTime 2015-11-26 09:39:59.696000000 Z updated_at: !ruby/object:DateTime 2015-11-26 09:39:59.696000000 Z title: '2013,2034.123' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5eo1GYHRFS6SYSWoum4Usy/c698e0e9d7477b42c5375328abfd5a21/2013_2034.123.jpg" caption: Negative handprints. <NAME>-Obeiyd, Egypt. 2013,2034.123 © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?searchText=Search%20the%20collection&museumno=2013,2034.123&ILINK|34484,&#124;assetId=1492207&objectId=3577680&partId=1 - sys: id: 4CLJOn1uoEQyaSkAooaeQW created_at: !ruby/object:DateTime 2015-11-26 09:43:48.853000000 Z updated_at: !ruby/object:DateTime 2016-12-19 17:17:14.289000000 Z content_type_id: chapter revision: 2 title_internal: 'General: how made, chapter 3' body: A very specific type of image is the handprint. These can be made in two ways, positively and negatively; by covering the hand in paint and applying it to the rock surface or by placing the hand on the rock and blowing paint through a tube or from the mouth over the hand to produce a stencil effect. Most images were made just in one colour, although examples of bichrome or polychrome are relatively frequent. Again, although very rare, there are some examples of figures combining engraving and painting. - sys: id: 5H7r0joxbOgqeesE4m2MUU created_at: !ruby/object:DateTime 2015-11-26 09:44:30.108000000 Z updated_at: !ruby/object:DateTime 2015-11-26 09:44:30.108000000 Z content_type_id: chapter revision: 1 title: Petroglyphs – Engraving title_internal: 'General: how made, chapter 4' body: Three techniques were generally used to remove the rock surface; incising/engraving (lines are cut into the rock with a sharp tool); pecking (hammering and chipping away at the rock surface) and scraping. Rock faces were sometimes ‘prepared’ by scraping, allowing for an improved surface on which to inscribe the image. Incising or engraving involves scratching into the stone surface using a sharp lithic flake or metal blade. Pecking is a form of indirect percussion whereby a second rock is used like a chisel between the hammerstone and the rock face, while scraping is created using a hard hammerstone, which is battered against the rock surface. A last, much rarer method of engraving is the bas-relief technique, where the area around the image is lowered (usually by polishing) thus making the figure raise over the surface. - sys: id: 3GOG2oZPjGmmMCii2QS0yE created_at: !ruby/object:DateTime 2015-11-26 09:41:50.996000000 Z updated_at: !ruby/object:DateTime 2016-12-19 17:18:09.807000000 Z content_type_id: image revision: 2 image: sys: id: 1ViunR9pOs40oei6A4yC6q created_at: !ruby/object:DateTime 2015-11-26 09:39:59.695000000 Z updated_at: !ruby/object:DateTime 2015-11-26 09:39:59.696000000 Z title: '2013,2034.4328' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1ViunR9pOs40oei6A4yC6q/a403a948fda6df00ef8ca14a2b9f409c/2013_2034.4328.jpg" caption: Polished cattle engravings. Tegharghart, Tassili n’Ajjer, Algeria. 2013,2034.4328 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3601772&partId=1&museumno=2013,2034.4328&page=1 - sys: id: 6EyM70F9YIq4eaIucMgaqa created_at: !ruby/object:DateTime 2015-11-26 09:44:52.817000000 Z updated_at: !ruby/object:DateTime 2015-11-26 09:44:52.817000000 Z content_type_id: chapter revision: 1 title_internal: 'General: how made, chapter 5' body: These methods of engraving are sometimes combined, as happens in the Sahara where the outline of pecked figures is polished afterwards. Although for the most part the engravings just depict the figures’ contour, on other occasions all or part of the image is infilled with pecking or polishing. In all these techniques, after differing periods of time the engraved surfaces weather and acquire the same darker patina as the original surface. background_images: - sys: id: 5eo1GYHRFS6SYSWoum4Usy created_at: !ruby/object:DateTime 2015-11-26 09:39:59.696000000 Z updated_at: !ruby/object:DateTime 2015-11-26 09:39:59.696000000 Z title: '2013,2034.123' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5eo1GYHRFS6SYSWoum4Usy/c698e0e9d7477b42c5375328abfd5a21/2013_2034.123.jpg" - sys: id: 53weII16ScuU6AQ6qWwIuS created_at: !ruby/object:DateTime 2015-11-26 09:39:59.713000000 Z updated_at: !ruby/object:DateTime 2015-11-26 09:39:59.713000000 Z title: '2013,2034.4108' description: url: "//images.ctfassets.net/xt8ne4gbbocd/53weII16ScuU6AQ6qWwIuS/bceed94a08e062929a8c23605155d23f/2013_2034.4108.jpg" ---<file_sep>/_coll_country_information/namibia-country-introduction.md --- contentful: sys: id: 8t9OseGfHqIgcUCao2ysq created_at: !ruby/object:DateTime 2016-09-26 14:54:01.738000000 Z updated_at: !ruby/object:DateTime 2016-10-17 15:39:27.185000000 Z content_type_id: country_information revision: 2 title: 'Namibia: country introduction' chapters: - sys: id: 4UiO2GnKUMUwso4aYMqCaG created_at: !ruby/object:DateTime 2016-09-26 14:48:35.037000000 Z updated_at: !ruby/object:DateTime 2018-05-09 16:46:01.299000000 Z content_type_id: chapter revision: 3 title: Introduction title_internal: 'Namibia: country, chapter 1' body: 'Namibia is home to over 1,200 rock art sites countrywide. Most of these sites appear to correspond with the hunter-gatherer art tradition found throughout southern Africa, with certain specific regional features. ' - sys: id: 1dABVOGavUAI6goAY8miaA created_at: !ruby/object:DateTime 2016-10-17 15:38:31.464000000 Z updated_at: !ruby/object:DateTime 2018-09-19 14:58:53.570000000 Z content_type_id: chapter revision: 2 title: Geography and rock art distribution title_internal: 'Namibia: country, chapter 2' - sys: id: 5gSXylxGD6eO20EyeOIQSY created_at: !ruby/object:DateTime 2016-09-26 14:49:11.461000000 Z updated_at: !ruby/object:DateTime 2016-09-26 14:49:11.461000000 Z content_type_id: image revision: 1 image: sys: id: 3Xk6O4MMsgEYY0WcaiCYqs created_at: !ruby/object:DateTime 2016-09-26 14:49:06.642000000 Z updated_at: !ruby/object:DateTime 2016-09-26 14:49:06.642000000 Z title: NAMDMB0010001 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3Xk6O4MMsgEYY0WcaiCYqs/fb7f2a4378bb27d56354a99c94ee7624/NAMDMB0010001.jpg" caption: View of the Brandberg, Namibia. 2013,2034.20454 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3729934&partId=1&people=197356&place=17546&museumno=2013,2034.20454+&page=1 - sys: id: 3KVc3so4EMwom64W8mGmUs created_at: !ruby/object:DateTime 2016-09-26 14:49:17.497000000 Z updated_at: !ruby/object:DateTime 2018-05-09 16:51:45.252000000 Z content_type_id: chapter revision: 5 title_internal: 'Namibia: country, chapter 3' body: 'Namibia covers an area of around 815,625km² in the south-west of Africa, bordering Angola and Zambia in the north, Botswana in the east, and South Africa to the south. Namibia’s climate is mainly arid or semi-arid, with the dry environment of the Namib desert covering the entirety of the country’s coastline in the west and bordered by southern Africa’s Great Escarpment, a rocky ridge at the edge of the central plateau running in rough parallel to the coastline. East of the ridge, the central plateau stretches towards the edge of the basin enclosing the western portion of the Kalahari, a semi-desert environment extending into Botswana and South Africa. ' - sys: id: 1uThiykyCAYWWieyOKciQi created_at: !ruby/object:DateTime 2016-09-26 14:49:30.621000000 Z updated_at: !ruby/object:DateTime 2018-05-09 16:53:37.343000000 Z content_type_id: image revision: 2 image: sys: id: 62AXX05gE8yACQgOgW0kqO created_at: !ruby/object:DateTime 2016-09-26 14:49:26.962000000 Z updated_at: !ruby/object:DateTime 2016-09-26 14:49:26.962000000 Z title: NAMDME0040007 description: url: "//images.ctfassets.net/xt8ne4gbbocd/62AXX05gE8yACQgOgW0kqO/0571a6030a608d5c7390cb521681a48e/NAMDME0040007.jpg" caption: Painted tableau showing giraffe, springbok, human figures and a tree. Omandumba, Namibia. 2013,2034.21544 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3767635&partId=1&searchText=2013,2034.21544&page=1 - sys: id: 3v5501rl28sYOwW2Cm8ga2 created_at: !ruby/object:DateTime 2016-09-26 14:49:37.812000000 Z updated_at: !ruby/object:DateTime 2018-05-09 16:57:17.099000000 Z content_type_id: chapter revision: 9 title_internal: 'Namibia: country, chapter 4' body: "Rock art is found across the country from the southern border almost to the northern border, although rock art sites are scarce in the far north. The majority of known rock art sites are found in the rocky and mountainous areas forming the escarpment edge in the west of the country. Particular concentrations of rock art are found in the west-centre of the country, north of the edge of the Namib’s coastal sand sea. Namibia’s most well-known rock art locales are clustered in this area, among them the Brandberg (also known as Dâures) and Erongo mountains and the Spitzkoppe peaks, as well as the well-known engraved rock art complex at Twyfelfontein | /Ui-//aes. \n\nAt approximately 20km wide, the almost circular granitic intrusion of the Brandberg contains Namibia’s highest point at over 2,500 ft., containing around 1,000 rock art sites and around 50,000 individual figures recorded. These include both paintings and engravings but paintings form the majority. The Erongo mountains, a similar but less compact formation around 120km to the south-east, contain a further 80 sites and 50km to the west of this, the Spitzkoppe peaks, a group of granite inselbergs, has a smaller concentration of known sites with 37 so far recorded. Painting sites are most often found on vertical surfaces in rock shelters or the sides of granitic boulders, while engravings may survive in more exposed environments such as on boulders, often dolerite or sandstone. \n\nThe most well-known of the engraving sites is that of Twyfelfontein | /Ui-//aes, around 50 km north of the Brandberg. The rock art complex here is dominated by collections of engraved images, though some paintings are also present. With well over 2,000 individual images, the Twyfelfontein engravings form the largest known discrete collection of engraved rock art in southern Africa. \n" - sys: id: 18lzX7RJb8skMkC0ousqMY created_at: !ruby/object:DateTime 2016-09-26 14:49:45.248000000 Z updated_at: !ruby/object:DateTime 2018-05-09 16:56:06.499000000 Z content_type_id: chapter revision: 5 title: History of research title_internal: 'Namibia: country, chapter 5' body: 'The first published mention of rock art in south-western Africa may be that of <NAME> who mentioned “A strange tale of a rock in which the tracks of…animals are distinctly visible” in his 1856 book Lake Ngami. Further reports came in the 1870s when the <NAME> published an article in a South African periodical reporting rock art in the Erongo Mountains, while Commissioner <NAME> made a report of paintings near Dassiesfontein, along with some the earliest known photographs of rock art in Africa. European public awareness of rock art from the region in Europe was spurred by the January 1910 publication of an article by Oberleutnant <NAME> featuring images from various sites in a German magazine. The first monograph on the rock art of the area then known as South West Africa was published in 1930 (Obermaier & Kühn, 1930), following further reports by officials, including the explorer and geographer <NAME>, who in a 1921 report first noted the existence of engravings at Twyfelfontein. ' - sys: id: 6oW0rqforuI6AQIUaMu4Ks created_at: !ruby/object:DateTime 2016-09-26 14:50:03.966000000 Z updated_at: !ruby/object:DateTime 2016-09-26 14:50:03.966000000 Z content_type_id: image revision: 1 image: sys: id: 4nbVLA22Y0Uw06ICSeGYQm created_at: !ruby/object:DateTime 2016-09-26 14:49:57.411000000 Z updated_at: !ruby/object:DateTime 2016-09-26 14:49:57.411000000 Z title: NAMDMT0010073 description: url: "//images.ctfassets.net/xt8ne4gbbocd/4nbVLA22Y0Uw06ICSeGYQm/b5c26da0464ec9a64fdde76edcc0fa3e/NAMDMT0010073.jpg" caption: Engraved kudu cow with geometric engravings. Twyfelfontein | /Ui-//aes, Namibia. 2013,2034.22095 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3763210&partId=1&searchText=2013,2034.22095&page=1 - sys: id: 25d3VoqJDWy2OGSEM2a8so created_at: !ruby/object:DateTime 2016-09-26 14:50:14.861000000 Z updated_at: !ruby/object:DateTime 2016-09-26 16:36:47.346000000 Z content_type_id: chapter revision: 2 title_internal: 'Namibia: country, chapter 6' body: "During the course of an earlier expedition, Maack had stumbled upon a singular painting in a Brandberg rock shelter. This image came to be well-known as the ‘White Lady’ of the Brandberg, after the renowned rock art researcher the Abbé <NAME>uil, who saw Maack’s copy of it and took a keen interest in the image. Eventually Breuil published a lavishly illustrated volume on the White Lady in 1955, which made it one of the most famous rock painting images in the world. \ During the 1940s and 50s Breuil also explored and published on rock art sites elsewhere in the Brandberg and Erongo mountains. \n\n<NAME>, who had acted as a guide for Breuil, would go on to conduct extensive documentation work throughout the country as part of the comprehensive research project investigating the archaeology of South West Africa run by the University of Cologne and sponsored by the Deutschen Forschungsgemeinschaft. Beginning in 1963, this resulted in the publications of Scherz’s three-volume opus *Felsbilder in Sudwest-Afrika* in 1970, 1975 and 1986, containing site by site descriptions and classifications of painting and engraving sites throughout modern Namibia, along with discussion of theme and context. The Cologne programme also supported the work of several other researchers, including the designer and artist <NAME>, whose meticulous work recording rock paintings in South Africa’s Drakensberg had already gained him recognition in the field of rock art research. From 1977, Pager began a seven year project of recording painted rock art sites in the Brandberg, documenting around 43,000 individual images. Pager’s corpus has been organised by <NAME> and published posthumously in the six-volume *Rock Paintings of the Upper Brandberg*, as a result of which the Brandberg is one of the most comprehensively documented rock art regions on earth.\n" - sys: id: pt0EDsK0SWU2Cg2EkuQKw created_at: !ruby/object:DateTime 2016-09-26 14:50:38.544000000 Z updated_at: !ruby/object:DateTime 2018-05-09 16:59:58.758000000 Z content_type_id: image revision: 2 image: sys: id: 4ZB32q4diwyQMIaOomeQOg created_at: !ruby/object:DateTime 2016-09-26 14:50:26.431000000 Z updated_at: !ruby/object:DateTime 2016-09-26 14:50:26.431000000 Z title: NAMDMB0010016 description: url: "//images.ctfassets.net/xt8ne4gbbocd/4ZB32q4diwyQMIaOomeQOg/5dd2b69e51fa5dd4bcd8f24c1cbe6df2/NAMDMB0010016.jpg" caption: The ‘White Lady’ painting, showing human figures, gemsbok antelope and a therianthrope (part-human, part-animal figure). <NAME>, Brandberg, Namibia. 2013,2034.21340 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3771011&partId=1&searchText=2013,2034.21340&page=1 - sys: id: 2Oc2SJpN9msEGCM0iWUGsw created_at: !ruby/object:DateTime 2016-09-26 14:50:47.116000000 Z updated_at: !ruby/object:DateTime 2018-05-09 16:48:16.058000000 Z content_type_id: chapter revision: 2 title_internal: 'Namibia: country, chapter 7' body: 'The Cologne programme also sponsored the excavation work of archaeologist <NAME>, who between 1968 and 1970 worked at numerous sites investigating Late Stone Age activity in the country. During this time, Wendt recovered seven slabs bearing pigment from a layer in a cave of the Huns Mountains in southern Namibia, which have been scientifically dated to 30,000 years ago. Four of these exhibited pigmented imagery of animals including a possible rhinoceros, a portion of a possible zebra figure and a complete unidentified quadruped formed by two of the plaques fitting together. These remain the oldest known figurative art in Africa. Much further rock art recording and excavation work has been undertaken since the 1980s in the Spitzkoppe, Erongo, Brandberg and other areas, with key research led by archaeologists <NAME>, <NAME>, <NAME>,<NAME> and <NAME>, among others. ' - sys: id: 1pTemf7LfaYckkgiam004s created_at: !ruby/object:DateTime 2016-09-26 14:51:03.951000000 Z updated_at: !ruby/object:DateTime 2018-05-09 16:48:40.803000000 Z content_type_id: chapter revision: 3 title: Themes title_internal: 'Namibia: country, chapter 8' body: "Much of the painted rock art in Namibia may be broadly compared to the wider hunter-gatherer rock art oeuvre found throughout southern Africa, similar in theme and composition and believed to be a part of the same general tradition, which is generally attributed to San&#124;Bushman¹ people and their ancestors. Imagery includes scenes of human figures carrying bows and other implements, wild animals and unidentified shapes in different pigments. Overall, human figures dominate in the paintings of Namibia, making up more than 2/3 of the painted figures, and where the gender can be recognised, they are more commonly male than female. Prominent painting subjects and styles in the rock art of Namibia (particularly the best-studied west-central region) include, at some sites, clearly delineated dots and patterns on human figures, a particular tradition of showing human figures with voluminous decorated hairstyles, and more images of giraffe and kudu, gemsbok and springbok antelope than in other southern African regions. Other images of animals include those of zebras, elephants, rhinoceros and ostriches. More occasional motifs found include plants, cattle, sheep and handprints. \n\n¹ San&#124;Bushmen is a collective term used to describe the many different hunter-gatherer-fisher groups living in southern Africa who have related languages and cultural traditions. Both 'San' and 'Bushmen' are considered offensive terms by some members of these groups, although others have positively adopted them." - sys: id: 3EiSSgVDtCWA4C4EOyW2ai created_at: !ruby/object:DateTime 2016-09-26 14:51:19.714000000 Z updated_at: !ruby/object:DateTime 2018-05-09 17:01:09.262000000 Z content_type_id: image revision: 2 image: sys: id: 3eVwGLF6ooeMySiG8G0a8U created_at: !ruby/object:DateTime 2016-09-26 14:51:15.764000000 Z updated_at: !ruby/object:DateTime 2016-09-26 14:51:15.764000000 Z title: NAMDMB0020012 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3eVwGLF6ooeMySiG8G0a8U/9c2150eacdb954ceb3f56afcbd4a5517/NAMDMB0020012.jpg" caption: Painted women carrying bows and showing detail of white dots (personal ornament or body paint). Brandberg, Namibia. 2013,2034.21364 © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3771040&partId=1&searchText=2013,2034.21364&page=1 - sys: id: 7LqBKmEh1YMWOEymKkiQSk created_at: !ruby/object:DateTime 2016-09-26 14:51:27.064000000 Z updated_at: !ruby/object:DateTime 2018-05-10 10:22:02.825000000 Z content_type_id: chapter revision: 3 title_internal: 'Namibia: country, chapter 9' body: "Within Namibia, paintings come in a variety of styles, ranging from naturalistic to stylised. Paintings found at Spitzkoppe tend to be smaller and cruder than others in the region, where some sites feature tableaux in many colours while others are entirely monochrome. While the majority of rock paintings in Namibia seem to conform to the hunter-gatherer style, there are also some examples of finger paintings in the Brandberg and northern Namibia, which are much more schematic in style and appear to belong to a different tradition altogether. \ \n\nAs with much southern African rock art, the colours visible today may not always accurately reflect the original look. This is particularly true for those used for pale colours or white, which may be ‘fugitive’, meaning that over time they fade or wash away faster than the more stable pigments around them, leaving gaps which were once coloured. Chemical analyses have shown that a major binder (used to coalesce dry pigment powder) for painted rock art in Namibia was blood, and in some cases egg white. \n" - sys: id: 2b4cKiDAbeuKMcO6siYG6Y created_at: !ruby/object:DateTime 2016-09-26 14:51:42.124000000 Z updated_at: !ruby/object:DateTime 2018-05-10 10:23:26.466000000 Z content_type_id: image revision: 2 image: sys: id: 3zUEF7pFUIeqsKeW2wOIkw created_at: !ruby/object:DateTime 2016-09-26 14:51:37.704000000 Z updated_at: !ruby/object:DateTime 2016-09-26 14:51:37.704000000 Z title: NAMDME0070010 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3zUEF7pFUIeqsKeW2wOIkw/15882e5e2123e5477d082edffd38e034/NAMDME0070010.jpg" caption: Painting showing evidence of ‘fugitive’ pigment. Gemsbok or eland antelope with only the red pigment remaining. Omandumba, Erongo Mountains, Namibia. 2013,2034.21647 © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3771309&partId=1&searchText=2013%2c2034.21647&page=1 - sys: id: 1UtWlqa1926kMisQkuimQK created_at: !ruby/object:DateTime 2016-09-26 14:51:49.953000000 Z updated_at: !ruby/object:DateTime 2018-05-09 16:49:27.291000000 Z content_type_id: chapter revision: 2 title_internal: 'Namibia: country, chapter 10' body: 'Engravings are often pecked and sometimes rubbed or polished. Although engravings, like paintings, feature animal figures heavily, with images of ostriches more common than those in paintings, there is a comparative dearth of engraved human figures. There is also less obvious interaction between individual engraved figures in the form of ‘scenes’ than in paintings, but instead more isolated individuals scattered on rock surfaces. Engraved rock art in Namibia also features a particular preponderance of images of spoor (animal hoof or paw prints). Some of these engravings are very naturalistic and may be identified by species whereas others, such as some showing human footprints, can be quite schematic. In addition, many engravings are geometric in nature. ' - sys: id: 6thXaCP5kIYysCy42IUgCC created_at: !ruby/object:DateTime 2016-09-26 14:52:14.154000000 Z updated_at: !ruby/object:DateTime 2018-05-10 10:24:08.309000000 Z content_type_id: image revision: 2 image: sys: id: 6lpq225cZOe0MKaC8cuuy6 created_at: !ruby/object:DateTime 2016-09-26 14:52:07.502000000 Z updated_at: !ruby/object:DateTime 2016-09-26 14:52:07.502000000 Z title: NAMWNK0010002 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6lpq225cZOe0MKaC8cuuy6/9815942f1c318fa7f945eb3075f8b109/NAMWNK0010002.jpg" caption: Examples of engraved spoor corresponding to eland hoof prints, Kalahari, Namibia. 2013,2034.22459 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3770294&partId=1&searchText=2013%2c2034.22459&page=1 - sys: id: 17KwAElNmCIGUoK4os22Gw created_at: !ruby/object:DateTime 2016-09-26 14:52:22.473000000 Z updated_at: !ruby/object:DateTime 2018-05-09 16:49:48.177000000 Z content_type_id: chapter revision: 3 title: Interpretation title_internal: 'Namibia: country, chapter 11' body: "Namibian rock paintings, and most engravings, have largely been interpreted in the vein largely espoused by researchers over the past 30 years. This postulates that much of this rock art reflects the experience of San&#124;Bushman shamans entering trance states and that rather than being scenes from daily life, the depictions of animals and activities are highly symbolic within San&#124;Bushman cosmology, with images acting as reservoirs of spiritual power. This avenue of interpretation originates largely from the study of rock art in South Africa and Lesotho. While it appears broadly applicable here, the fact that direct attributions to known cultural groups in this area are difficult somewhat hinders direct comparisons with Namibian rock art. While hunter-gatherer rock painting production in South Africa was practiced until the recent past, it appears to have ceased in Namibia around a thousand years ago and modern San&#124;Bushman groups in the Kalahari area have no tradition of rock art production. \n\nAdditionally, hundreds of miles and different geographical environments separate the rock art centres of north-western Namibia from those in neighbouring countries. This is particularly apparent in the differences in terms of animal subject matter, with the numerous depictions of gemsbok and springbok, explicable by the rock art creators being semi-desert dwellers where gemsbok and springbok are found locally though largely absent from rock art elsewhere in southern Africa, where these animals are not found. \n" - sys: id: lwcNbhZZy8koW0Uq2KEkq created_at: !ruby/object:DateTime 2016-09-26 14:52:40.163000000 Z updated_at: !ruby/object:DateTime 2018-05-10 10:26:46.067000000 Z content_type_id: image revision: 2 image: sys: id: 5UMcF5DE2siok0k4UakAUW created_at: !ruby/object:DateTime 2016-09-26 14:52:36.239000000 Z updated_at: !ruby/object:DateTime 2016-09-26 14:52:36.239000000 Z title: NAMBRH0010024 description: url: "//images.ctfassets.net/xt8ne4gbbocd/5UMcF5DE2siok0k4UakAUW/91a406ca0cb338ddf1c7e4b98325cd63/NAMBRH0010024.jpg" caption: Examples of painted motifs in rock art of the Brandberg, showing gemsbok antelope, giraffe, human, zebra and ostrich figures. Brandberg, Namibia. 2013,2034.21303 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3768631&partId=1&searchText=2013%2c2034.21303&page=1 - sys: id: 6x77m8o4vuuEMeqiSISGCK created_at: !ruby/object:DateTime 2016-09-26 14:52:47.433000000 Z updated_at: !ruby/object:DateTime 2018-05-10 10:30:06.342000000 Z content_type_id: chapter revision: 2 title_internal: 'Namibia: country, chapter 12' body: "Other differences are found in style and emphasis: the frequency with which giraffe feature in Namibian paintings and engravings contrasts with the South African rock art, where the emphasis is more on the eland antelope. This has led some to propose that the giraffe, similarly, must have held a particular symbolic meaning for the painters of the region. Based on associated imagery, placement of the rock art sites, and some ethnography (written records of insights from contemporary San&#124;Bushman culture compiled by anthropologists) it has been suggested that giraffes may have been linked with rain in local belief systems, with some Namibian rock painting sites associated specifically with rainmaking or healing activities. \n\nWhile the more naturalistic examples of engravings are thought to have also been produced by ancient hunter-gatherers, as with the paintings, it has been suggested that some geometric engravings were produced by herding people, possibly ancestral Khoenkhoen, perhaps in relation to initiation rites. Schematic finger paintings have also been attributed to pastoralist people. All attributions are tentative, however, because the majority of the art is thought to be many hundreds of years old and the historical distinctions between hunter-gatherers and herders is by no means clear-cut in the archaeological record.\n" - sys: id: 6Ljhl9Tm5GGKeU6e6GMSOA created_at: !ruby/object:DateTime 2016-09-26 14:52:59.658000000 Z updated_at: !ruby/object:DateTime 2018-05-09 16:50:17.361000000 Z content_type_id: chapter revision: 5 title: Chronology title_internal: 'Namibia: country, chapter 13' body: "The pieces from the cave Wendt excavated (named ‘Apollo 11 Cave’ after the moon mission which took place during the period of the excavation work) are not thought to have fallen from a cave wall but were made on loose rock pieces. The only parietal art (on a fixed rock surface) dated from excavated deposits in Namiba so far consists of pieces of painted granite from the largest painted shelter in the Brandberg, one of which, found in a sedimentary layer radiocarbon dated to around 2,700 years ago, had clearly fallen from an exposed rock surface into which researchers were able to refit it. Aside from this, estimates at the age of rock art are based on superimposition, patination and associated archaeological finds. \n\nBased on archaeological evidence, it is thought that the majority of the fine-line hunter-gatherer rock art in the Brandberg area was produced between around 4,000 and 2,000 years ago, with the painting tradition in the wider region starting as much as 6,000 years ago. This ceased sometime after the introduction of small domestic stock to the area, although not immediately, as fine-line paintings of sheep and paintings and engravings of cattle testify. Across central Namibia, there appears to be a particularly strong correspondence of finds relating to paintings—such as grinding equipment and pigments—with dated layers from the 1st millennium BC.\n" - sys: id: 3k0RnznV5Yu2uoGgc0UkCC created_at: !ruby/object:DateTime 2016-09-26 14:53:21.292000000 Z updated_at: !ruby/object:DateTime 2018-05-10 10:30:47.494000000 Z content_type_id: image revision: 2 image: sys: id: 5SxIVsUotUcuWoI2iyYOSO created_at: !ruby/object:DateTime 2016-09-26 14:53:15.820000000 Z updated_at: !ruby/object:DateTime 2016-09-26 14:53:15.821000000 Z title: NAMNNO0010020 description: url: "//images.ctfassets.net/xt8ne4gbbocd/5SxIVsUotUcuWoI2iyYOSO/b2b0daf1086aba5ebb54c90b0b1cce42/NAMNNO0010020.jpg" caption: Finger painted rock art, northern Namibia. 2013,2034.22237 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3771279&partId=1&searchText=2013%2c2034.22237&page=1 - sys: id: 7hIopDzZzGI8iMiuEOOOyG created_at: !ruby/object:DateTime 2016-09-26 14:53:29.617000000 Z updated_at: !ruby/object:DateTime 2018-05-09 16:50:37.206000000 Z content_type_id: chapter revision: 2 title_internal: 'Namibia: country, chapter 14' body: 'Engravings are more difficult to obtain dates for scientifically. Superimpositioning and other physical factors can serve to indicate which styles of image are more recent with both paintings and engravings. For example, in the Brandberg, monochrome tableaux appear older than detailed polychrome depictions of individuals, and certain images, such as those of zebras, are thought to be relatively late. Among engravings of central Namibia, a certain style of hoof print appears to overlie some figurative images, leading researchers to believe them younger. Overall it is thought that the engraving and painting traditions were concurrent, with some clear parallels in style, but that engraving probably lasted for several hundred years as a tradition after painting ceased. ' - sys: id: 137eUF3ZZGUGy6SM4cWimS created_at: !ruby/object:DateTime 2016-09-26 14:53:45.520000000 Z updated_at: !ruby/object:DateTime 2018-05-10 10:40:21.998000000 Z content_type_id: image revision: 2 image: sys: id: 4I7MYP97u8AK8YE88UGOKS created_at: !ruby/object:DateTime 2016-09-26 14:53:41.001000000 Z updated_at: !ruby/object:DateTime 2016-09-26 14:53:41.001000000 Z title: NAMSNA0010011 description: url: "//images.ctfassets.net/xt8ne4gbbocd/4I7MYP97u8AK8YE88UGOKS/0b33b94b43c9ba242717ba831d3f7fe3/NAMSNA0010011.jpg" caption: Engraved geometric rock art in the style thought to have been made by herder people. ǁKaras Region, Southern Namibia. 2013,2034.22285 ©TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3772002&partId=1&place=108716&plaA=108716-2-2&page=1 citations: - sys: id: 2Looo7MWBGKQQKAooSausA created_at: !ruby/object:DateTime 2016-09-26 14:53:53.399000000 Z updated_at: !ruby/object:DateTime 2016-09-26 14:53:53.399000000 Z content_type_id: citation revision: 1 citation_line: | CeSMAP- Study Centre and Museum of Prehistoric Art of Pinerolo. 1997. African pictograms. Pinerolo, Centro Studi e Museo di arte preistorica. <NAME>. 2010. The rock art of /Ui-//aes (Twyfelfontein) Namibia’s first World Heritage Site. Adoranten 2010. Tanumshede: Tanums Hällristningsmuseum <NAME>. 1999. Towards an Archaeology of mimesis and rainmaking in Namibian rock art in : <NAME>., & <NAME>. (1999). The Archaeology and Anthropology of Landscape: Shaping your Landscape. London, Routledge pp. 336-357 <NAME>. 2015. IFRAO. Rock art research in Namibia: a synopsis A investigação de arte rupestre na Namíbia: uma visão geral in: Giraldo, H.C. & Arranz, J.J.G (eds.) Symbols in the Landscape: Rock Art and its Context. Proceedings of the XIX International Rock Art Conference IFRAO 2015, Arkeos 37 pp. 1419:1436 <NAME>., Kuhn., & <NAME>. 1930. Bushman art: rock paintings of south-west Africa. London, H. Milford, Oxford University Press <NAME>. 1989-. Rock Paintings of the Upper Brandberg. vols. I-VI. Köln: Heinrich-Barth-Institut <NAME>. & <NAME>: Rock Art in North-Westerpn Central Namibia – its Age and Cultural Background in: <NAME>., & <NAME>. 2008. Heritage and Cultures in modern Namibia: in-depth views of the country : a TUCSIN Festschrift. Windhoek ; Goettingen : Klaus Hess Publishers pp 37:46 <NAME>. 1970, 1975, 1986. Felsbilder in Südwest-Afrika. Teilen I-III. Köln ;Wien: Böhlau ---<file_sep>/_coll_introduction/origins.md --- contentful: sys: id: 6hiXYeBCfYyAgq0uSYYA4q created_at: !ruby/object:DateTime 2015-11-26 10:12:12.305000000 Z updated_at: !ruby/object:DateTime 2016-10-14 13:19:39.829000000 Z content_type_id: introduction revision: 8 title: Origins of rock art in Africa slug: origins lead_image: - sys: id: 2cVEIKXUmwQqwyOwauuGYc created_at: !ruby/object:DateTime 2015-11-26 10:10:14.693000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:10:14.693000000 Z title: Apollo.11.Cave description: url: "//images.ctfassets.net/xt8ne4gbbocd/2cVEIKXUmwQqwyOwauuGYc/7824d383fbab171ac0b32bd9117c066e/Apollo.11.Cave.jpg" chapters: - sys: id: fZLY1sn2JGo800I8oW2us created_at: !ruby/object:DateTime 2015-11-26 10:12:41.393000000 Z updated_at: !ruby/object:DateTime 2016-12-19 17:28:15.527000000 Z content_type_id: chapter revision: 2 title: Introduction title_internal: 'General: origins, chapter 1' body: The oldest scientifically-dated rock art in Africa dates from around 30,000 years ago and is found in Namibia. - sys: id: 3B1nQ7Xsooq6Ae4EyE0Oko created_at: !ruby/object:DateTime 2015-11-26 10:10:47.465000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:10:47.465000000 Z content_type_id: image revision: 1 image: sys: id: 2cVEIKXUmwQqwyOwauuGYc created_at: !ruby/object:DateTime 2015-11-26 10:10:14.693000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:10:14.693000000 Z title: Apollo.11.Cave description: url: "//images.ctfassets.net/xt8ne4gbbocd/2cVEIKXUmwQqwyOwauuGYc/7824d383fbab171ac0b32bd9117c066e/Apollo.11.Cave.jpg" caption: Quartzite slabs depicting animals, Apollo 11 Cave, Namibia. Image courtesy of State Museum of Namibia © State Museum of Namibia - sys: id: 6sHCGiplbG4SuMYmeE8UW2 created_at: !ruby/object:DateTime 2015-11-26 10:13:10.958000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:13:10.958000000 Z content_type_id: chapter revision: 1 title_internal: 'General: origins, chapter 2' body: Between 1969 and 1972, German archaeologist, <NAME>, researching in an area known locally as 'Goachanas', unearthed several painted slabs in a cave he named Apollo 11, after NASA’s successful moon landing mission. Seven painted stone slabs of brown-grey quartzite, depicting a variety of animals painted in charcoal, ochre and white, were located in a Middle Stone Age deposit. These images are not easily identifiable to species level, but have been interpreted variously as felines and/or bovids; one in particular has been observed to be either a zebra, giraffe or ostrich, demonstrating the ambiguous nature of the depictions. - sys: id: 4jqrHFkmpqs8GWogw8cEAU created_at: !ruby/object:DateTime 2015-11-26 10:13:34.687000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:13:34.687000000 Z content_type_id: chapter revision: 1 title: Art and our modern mind title_internal: 'General: origins, chapter 3' body: |- While the Apollo 11 plaques may be the oldest discovered representational art in Africa, this is not the beginning of the story of art. It is now well-established, through genetic and fossil evidence, that anatomically modern humans (Homo sapiens sapiens) developed in Africa more than 100,000 years ago; of these, a small group left the Continent around 60,000-80,000 years ago and spread throughout the rest of the world. Recently discovered examples of patterned stone, ochre and ostrich eggshell, as well as evidence of personal ornamentation emerging from Middle Stone Age Africa (100,000–60,000 years ago), have demonstrated that ‘art’ is not only a much older phenomenon than previously thought, but that it has its roots in the African continent. Africa is where we share a common humanity. The first examples of what we might term ‘art’ in Africa, dating from between 100,000–60,000 years ago, emerge in two very distinct forms: personal adornment in the form of perforated seashells suspended on twine, and incised and engraved stone, ochre and ostrich eggshell. Despite some sites being 8,000km and 40,000 years apart, an intriguing feature of the earliest art is that these first forays appear remarkably similar. It is worth noting here that the term ‘art’ in this context is highly problematic, in that we cannot assume that humans living 100,000 years ago, or even 10,000 years ago, had a concept of art in the same way that we do, particularly in the modern Western sense. However, it remains a useful umbrella term for our purposes here. - sys: id: 4HfDzzg8rC6mA0eU6IQkm2 created_at: !ruby/object:DateTime 2015-11-26 10:14:13.397000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:14:13.397000000 Z content_type_id: chapter revision: 1 title: Pattern and design title_internal: 'General: origins, chapter 4' body: |- The practice of engraving or incising, which emerges around 12,000 years ago in Saharan rock art, has its antecedents much earlier, up to 100,000 years ago. Incised and engraved stone, bone, ochre and ostrich eggshell have been found at sites in southern Africa. These marked objects share features in the expression of design, exhibiting patterns that have been classified as cross-hatching. One of the most iconic and well-publicised sites that have yielded cross-hatch incised patterning on ochre is Blombos Cave, on the southern Cape shore of South Africa. Of the more than 8,500 fragments of ochre deriving from the MSA levels, 15 fragments show evidence of engraving. Two of these, dated to 77,000 years ago, have received the most attention for the design of cross-hatch pattern. - sys: id: 5On76lx0FUGsGGkymAwei4 created_at: !ruby/object:DateTime 2015-11-26 10:11:15.382000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:11:15.382000000 Z content_type_id: image revision: 1 image: sys: id: 4lvOlwlUMwQqe6Cm2ka20c created_at: !ruby/object:DateTime 2015-11-26 10:10:14.666000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:10:14.666000000 Z title: Blombos.Cave description: url: "//images.ctfassets.net/xt8ne4gbbocd/4lvOlwlUMwQqe6Cm2ka20c/fb10d6e20427bbc487de3ee68c9c5a28/Blombos.Cave.jpg" caption: Incised ochre from Blombos Cave, South Africa. Photo by <NAME> © <NAME> - sys: id: jgRuQ2IIAocma4AWygyke created_at: !ruby/object:DateTime 2015-11-26 10:14:30.893000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:14:30.893000000 Z content_type_id: chapter revision: 1 title_internal: 'General: origins, chapter 5' body: |- For many archaeologists, the incised pieces of ochre at Blombos are the most complex and best-formed evidence for early abstract representations, and are unequivocal evidence for symbolic thought and language. The debate about when we became a symbolic species and acquired fully syntactical language – what archaeologists term ‘modern human behaviour’ – is both complex and contested. It has been proposed that these cross-hatch patterns are clear evidence of thinking symbolically, because the motifs are not representational and as such are culturally constructed and arbitrary. Moreover, in order for the meaning of this motif to be conveyed to others, language is a prerequisite. The Blombos engravings are not isolated occurrences, since the presence of such designs occur at more than half a dozen other sites in South Africa, suggesting that this pattern is indeed important in some way, and not the result of idiosyncratic behaviour. It is worth noting, however, that for some scholars, the premise that the pattern is symbolic is not so certain. The patterns may indeed have a meaning, but it is how that meaning is associated, either by resemblance (iconic) or correlation (indexical), that is important for our understanding of human cognition. - sys: id: 4jbiaStTHWG8oUgEUMOisG created_at: !ruby/object:DateTime 2015-11-26 10:11:50.180000000 Z updated_at: !ruby/object:DateTime 2016-12-19 17:29:25.645000000 Z content_type_id: image revision: 2 image: sys: id: 5KFpq9vW9O6k6umooQYiKA created_at: !ruby/object:DateTime 2015-11-26 10:10:14.669000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:10:14.669000000 Z title: ostrich.eggshells description: url: "//images.ctfassets.net/xt8ne4gbbocd/5KFpq9vW9O6k6umooQYiKA/63f65b8d010b1bdcbda0d2fb7049122e/ostrich.eggshells.jpg" caption: "Fragments of engraved ostrich eggshells from the Diepkloof Rock Shelter,\tWestern Cape, South Africa, dated to 60,000 BP. Courtesy of <NAME>, Diepkloof project. © <NAME>" - sys: id: 64NOsXlchaeM2YIEAcQoGw created_at: !ruby/object:DateTime 2015-11-26 10:14:48.739000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:14:48.739000000 Z content_type_id: chapter revision: 1 title_internal: 'General: origins, chapter 6' body: Personal ornamentation and engraved designs are the earliest evidence of art in Africa, and are inextricably tied up with the development of human cognition. For tens of thousands of years, there has been not only a capacity for, but a motivation to adorn and to inscribe, to make visual that which is important. The interesting and pertinent issue in the context of this project is that the rock art we are cataloguing, describing and researching comes from a tradition that goes far back into African prehistory. The techniques and subject matter resonate over the millennia. background_images: - sys: id: 1bstKcKNZqC2ygioEM0uYO created_at: !ruby/object:DateTime 2015-12-07 20:43:37.744000000 Z updated_at: !ruby/object:DateTime 2015-12-07 20:43:37.744000000 Z title: MORATM0130051 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1bstKcKNZqC2ygioEM0uYO/a5392851c49141540957368efbf2fa63/MORATM0130051.jpg" - sys: id: 2q8dJPCe2AKcAeogKWikue created_at: !ruby/object:DateTime 2016-09-12 15:17:06.782000000 Z updated_at: !ruby/object:DateTime 2016-09-12 15:17:06.782000000 Z title: SOASWC0130095 description: url: "//images.ctfassets.net/xt8ne4gbbocd/2q8dJPCe2AKcAeogKWikue/7edea03ab0a677b76edd11bda026ba2c/SOASWC0130095.jpg" ---<file_sep>/_coll_introduction/chronologies.md --- contentful: sys: id: 1Gcunuhia0qYEEqoACkEES created_at: !ruby/object:DateTime 2015-11-26 09:54:46.501000000 Z updated_at: !ruby/object:DateTime 2018-05-25 17:16:46.300000000 Z content_type_id: introduction revision: 6 title: Chronologies slug: chronologies lead_image: - sys: id: 49XE8B9AUwcsyuwKS4qIoS created_at: !ruby/object:DateTime 2016-09-12 15:20:29.384000000 Z updated_at: !ruby/object:DateTime 2016-09-12 15:20:29.384000000 Z title: SOADRB0040015 description: url: "//images.ctfassets.net/xt8ne4gbbocd/49XE8B9AUwcsyuwKS4qIoS/0497ecca68dfaaf3b2656a890cff67dd/SOADRB0040015.jpg" chapters: - sys: id: 45agpJWfsAgAmMCmoiEoQ2 created_at: !ruby/object:DateTime 2015-11-26 09:55:17.375000000 Z updated_at: !ruby/object:DateTime 2015-11-26 09:55:17.375000000 Z content_type_id: chapter revision: 1 title: Introduction title_internal: 'General: chronologies, chapter 1' body: The axiom that rock art is notoriously difficult to date serves only to paint a partial picture of the inconsistent and contested chronological records of rock art in Africa. For example, where research has focused on interpretation, chronology has been less prominent and as such the capacity for judging meaningful relationships between sites and imagery has been inhibited; by contrast where chronologies have led research agendas, the temporal and spatial relationships are much clearer, but chronologies are hotly disputed. A significant obstacle is the challenge in directly dating rock art, and current research is exploring ways forward in refining these techniques. Here, we give an overview of dating methods and developed chronologies to date in rock art regions across the continent. - sys: id: 4VEFhfNAIwYg6OscqIumYA created_at: !ruby/object:DateTime 2015-11-26 09:53:28.667000000 Z updated_at: !ruby/object:DateTime 2016-12-19 17:20:54.393000000 Z content_type_id: image revision: 2 image: sys: id: 5nqN2H6iB2W0GUsOOiuasa created_at: !ruby/object:DateTime 2015-11-26 09:50:19.595000000 Z updated_at: !ruby/object:DateTime 2015-11-26 09:50:19.595000000 Z title: '2013,2034.4260' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5nqN2H6iB2W0GUsOOiuasa/4e1a652b425032483e7d8943a8654f0a/2013_2034.4260.jpg" caption: Superimposition of handprints and other figures. In Awanghet, Tassili n’Ajjer, Algeria. 2013,2034.4260 © TARA/<NAME> col_link: http://bit.ly/2hMkOcV - sys: id: 5Qlnfk7uwgqAcGqEykCAsW created_at: !ruby/object:DateTime 2015-11-26 09:55:43.388000000 Z updated_at: !ruby/object:DateTime 2015-11-26 09:55:43.388000000 Z content_type_id: chapter revision: 1 title: Dating paintings title_internal: 'General: chronologies, chapter 2' body: 'Determining the age of rock art depictions has always been one of the main goals of research, and a wide range of techniques have been developed to try to assign a date for rock art images throughout the world. There are two main approaches to rock art dating: relative and absolute.' - sys: id: 6Qg9RvFgWWo0CKa24CacYC created_at: !ruby/object:DateTime 2015-11-26 09:56:05.387000000 Z updated_at: !ruby/object:DateTime 2015-11-26 09:56:05.387000000 Z content_type_id: chapter revision: 1 title: Relative Dating title_internal: 'General: chronologies, chapter 3' body: |- Relative chronologies aim to organise the images from the oldest to the more recent, even if their exact dates are not known, providing the relative position of groups of depictions over time. It uses methods such as the analysis of superimpositions (the figures on the top have to be younger than those underneath), the study of depictions of animals already extinct or newly introduced in areas (for example, camels in the Sahara) or objects that have a known timeframe of usage, such as ships, firearms, chariots, etc. In some cases, graffiti can be found alongside figures, and linguistic studies can help to determine the age of both texts and depictions. Of course, one of the best ways to establish a relative date for rock art is when it is covered by archaeological deposits that can be dated through radiocarbon methods or archaeological materials. However, that date only states the minimum age of the rock art depictions, as they could have been covered hundreds or thousands of years after the images were painted or engraved. Moreover, these situations are very rare, as most of the time rock art is situated in the open air, without associated archaeological sites. - sys: id: 5N6QhaMeqIGsu2GCk8swc4 created_at: !ruby/object:DateTime 2015-11-26 09:56:25.708000000 Z updated_at: !ruby/object:DateTime 2015-11-26 09:56:25.708000000 Z content_type_id: chapter revision: 1 title: Absolute Dating title_internal: 'General: chronologies, chapter 4' body: The second type of dating is called absolute dating and provides concrete dates (or more often, intervals of age) in which the images were made. Although this could seem the perfect solution for the dating of paintings, the methods of absolute dating can only be used in very specific contexts, and often have serious problems of accuracy and reliability. The most efficient is based on the radiocarbon (carbon-14) method, measuring the amount of carbon remaining in pigments, although in many depictions the remnants of paint are so sparse that the size of the samples is too low to be measured. Besides, this method is destructive, as part of the painting has to be removed from the original site to collect the sample. - sys: id: 4tSeJBVUy4806kiUUaIqQq created_at: !ruby/object:DateTime 2015-11-26 09:53:54.918000000 Z updated_at: !ruby/object:DateTime 2016-12-19 17:25:47.847000000 Z content_type_id: image revision: 2 image: sys: id: 6SWz7d0wSckMi2eMKsWAig created_at: !ruby/object:DateTime 2015-11-26 09:50:19.618000000 Z updated_at: !ruby/object:DateTime 2015-11-26 09:50:19.618000000 Z title: '2013,2034.896' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6SWz7d0wSckMi2eMKsWAig/5b2e71e83e8f25b7883a87b087dfeee5/2013_2034.896.jpg" caption: Round Head period painting radiocarbon dated to 8590±390 BP. Uan Tamuat, Acacus Mountains, Libya. 2013,2034.896 © TARA/<NAME> col_link: http://bit.ly/2gUa6Pu - sys: id: 4FhJjlHvdYKOceWO4aIQ6e created_at: !ruby/object:DateTime 2015-11-26 09:56:47.364000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:04:26.721000000 Z content_type_id: chapter revision: 2 title: Dating engravings title_internal: 'General: chronologies, chapter 5' body: 'The study of engravings is even more difficult, as it is based on the changes that affect their surface after they were made. The most obvious is a progressive change in colour, making the older engravings seems “darker” than the newer. When the changes in colour are due to chemical, internal processes, the term used is *patina*, while when they are caused by the accumulation of particles the process is known as *varnishing*. Finally, the progressive weathering of the engraving’s traces can also be measured. By studying the pace of these natural processes, scientists can propose dates for the engravings. However, as with carbon-14, these methods have several problems that affect their suitability: the study of these natural processes is slow and costly, and the results can only be applied to small, concrete areas. There are also problems with the accuracy of the measurements, and risks of contamination of samples are high. Therefore, although they are promising, the absolute dating methods are still far from providing generalized and relatively easy ways to reliably date rock art.' - sys: id: 1TYOnwIxeIA64mcg08qseE created_at: !ruby/object:DateTime 2015-11-26 09:54:23.552000000 Z updated_at: !ruby/object:DateTime 2015-11-26 09:54:23.552000000 Z content_type_id: image revision: 1 image: sys: id: 4CGawd5fWUaQicOIEk8omA created_at: !ruby/object:DateTime 2015-11-26 09:50:19.593000000 Z updated_at: !ruby/object:DateTime 2015-11-26 09:50:19.593000000 Z title: '2013,2034.285' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4CGawd5fWUaQicOIEk8omA/7253be5000fc61d602f91d5d06680a8c/2013_2034.285.jpg" caption: Giraffe shows darker patina than cattle suggesting it is an older engraving. <NAME>. 2013,2034.285 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3577801&partId=1&museumno=2013,2034.285&page=1 - sys: id: 4O9tyRWy5GeAWiSWouCowY created_at: !ruby/object:DateTime 2015-11-26 09:57:08.516000000 Z updated_at: !ruby/object:DateTime 2015-11-26 09:57:08.516000000 Z content_type_id: chapter revision: 1 title_internal: 'General: chronologies, chapter 6' body: In practice, the dating of rock art is achieved through a combination of relative and - when possible - absolute dating methods, although relative techniques are still the more broadly used. Concepts such as style, technique and iconography are still key tools of analysis, but as absolute dating accuracy and availability grow, the chronological framework of rock art will be substantially improved. As scientific research advances, the techniques of rock art dating become more refined and trustworthy, and in the future, significant progress is expected, which will mean a revolution for world rock art chronologies. - sys: id: 28g8cJSDU8AGkm2C60ay0S created_at: !ruby/object:DateTime 2015-11-26 09:58:41.032000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:02:09.180000000 Z content_type_id: chapter revision: 2 title: Chronologies in northern Africa title_internal: 'General: chronologies, chapter 7' body: |- __Stylistic dating__ The importance of dating has been at the forefront of much research in North African rock art, yet there is no consensus of opinion about the precise dating of the phases of rock art in this region. The construction of rock art sequences has been predicated on stylistic analysis, on which most scholars agree in principle, and broadly conforms to the following: - *Early Hunter*, *Wild Fauna* Period or *Bubalus* Period: 12,000 – 8,000 years ago - *Round Head* Period: 10,000 – 8,000 years ago - *Pastoral* Period: 7,500 – 4,000 years ago - *Horse* Period: 3,000 – 2,000 years ago - *Camel* Period: 2,000 years ago – present For the most part, there is general agreement on the dating of the Horse and Camel period, but the earliest phases of rock art - the *Bubalus*/*Round Head*/*Pastoral* periods, are much more contentious. Researchers <NAME> and <NAME> have argued that the *Pastoral* period begins around 6,000 years ago, while others, such as <NAME>, propose an earlier date of 8,000 years ago. Domestic stock is thought to have existed in the Sahara from around 7,500 years ago, making a date of 8,000 years old for paintings of cattle (which may have been wild) feasible. Dating the end of this period is just as problematic, with Lhote and Mori placing it between 3,000-4,000 years ago and Muzzolini about 1,000 years later. However, the largest discrepancy relates to the *Bubalus* and *Round Head* periods, where significantly disparate chronologies have been proposed by Lhote, Mori and Muzzolini. The most extreme of these is the *Bubalus* period, where Mori advocates an Early/Long chronology proposing that the earliest images date back 12,000 years, while Muzzolini suggests a Recent/Short chronology proposing a much later emergence of art in the region at 6,000 years ago. The application of direct dating will be central in resolving these substantial differences and has yielded some fruitful results on archaeological sites in making meaningful correlations. However, for the time being, the chronologies of Saharan rock art remain ambiguous and contested. - sys: id: 2wBcANxhA08OMYcUQsKIgQ created_at: !ruby/object:DateTime 2015-11-26 10:02:41.150000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:02:41.150000000 Z content_type_id: chapter revision: 1 title: Chronologies in southern Africa title_internal: 'General: chronologies, chapter 8' body: Although a vast amount of work has been undertaken in rock art research in southern Africa, the focus has been largely placed on the meaning of images and their place within a rich ethnographic record. Little attention has been given to investigating temporal and spatial relationships, and as such there is a conspicuous absence of secure regional chronologies for southern African rock art. - sys: id: 38u1tkjkxqq4uoaoscGecU created_at: !ruby/object:DateTime 2015-11-26 10:03:13.893000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:03:13.893000000 Z content_type_id: chapter revision: 1 title_internal: 'General: chronologies, chapter 9' body: |- __Relative dating__ Based on observations in the field, relative sequences were proposed by <NAME> (1976) for the southern region of the Drakensberg and by <NAME> (1933) and <NAME> (1971) for the northern region. Subsequently, several sites in South Africa have been analysed using a method termed the Harris Matrix. In its original context the Harris Matrix was a diagrammatic tool used in archaeological fieldwork to determine the temporal succession of deposits and stratigraphic relationships. Its use in South African rock art has been limited and often on isolated sites, and one of the drawbacks in this methodology is the lack of information on time lapses between successive images. While a few radiocarbon and Accelerator Mass Spectometry (AMS) dates have been secured for some sites, the absolute dates need to be matched with relative chronologies, which to date are still not firmly established. __Stylistic dating__ Much rock art research has focused on the San rock paintings found in southern Africa (Botswana, Lesotho, Malawi, Mozambique, Namibia, South Africa, Swaziland and Zimbabwe). The subject matter of San rock art is extremely varied but regional characteristics can be seen; for example, depictions of eland dominate much of the rock art in South Africa, while kudu and elephants prevail in Zimbabwe. The earliest San art is thought to be up to 10,000 years old and continues possibly well into the twentieth century in the Drakensberg mountains. The spread of farming to South Africa by Bantu-language speakers around 3,500 years ago brought another style of rock art, until it ceased around the mid-1900s. The art is predominantly in white, and applied using fingers, which gives it a rough appearance. Subject matter is varied but dominated by humans and animals. Later rock art reflected contact with European settlers/colonisers, attested to by the numerous depictions of steam trains, soldiers, settlers and guns. - sys: id: 2LSYes3MQMCwCcGoGQyYee created_at: !ruby/object:DateTime 2015-11-26 10:03:58.473000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:03:58.473000000 Z content_type_id: chapter revision: 1 title: Chronologies in central and eastern Africa title_internal: 'General: chronologies, chapter 10' body: |- __Absolute/Relative dating__ Little research has been conducted, either on absolute or relative rock art chronologies in central Africa, and is therefore still poorly understood by comparison with northern and southern Africa. Promising recent radiocarbon dates have been reported from paintings in Angola, but the absence of contextual information with these dates renders them unproductive. Dating rock art by association with archaeological deposits has not proved entirely successful either. Relative chronologies have been suggested, and while there are regional variations, in general two styles of rock art have been identified and associated with a relative chronology: Twa and Sandawe. __Stylistic dating__ Twa-style art dates to around 3,000 to 1,000 years ago and was made by hunter-gatherer groups in eastern and central Africa. Depictions of animals are rare in Twa art and usually consist of geometric designs, often concentric circles. Ancestral Sandawe art, found mainly in central Tanzania, is thought to date from around 9,000 years ago to the recent past, and includes fairly large naturalistic images of animals in both hunting and domestic scenes. Figures are frequently holding bows and arrows, and are often depicted with elaborate hairstyles and/or headdresses. background_images: - sys: id: 4CGawd5fWUaQicOIEk8omA created_at: !ruby/object:DateTime 2015-11-26 09:50:19.593000000 Z updated_at: !ruby/object:DateTime 2015-11-26 09:50:19.593000000 Z title: '2013,2034.285' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4CGawd5fWUaQicOIEk8omA/7253be5000fc61d602f91d5d06680a8c/2013_2034.285.jpg" - sys: id: 6SWz7d0wSckMi2eMKsWAig created_at: !ruby/object:DateTime 2015-11-26 09:50:19.618000000 Z updated_at: !ruby/object:DateTime 2015-11-26 09:50:19.618000000 Z title: '2013,2034.896' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6SWz7d0wSckMi2eMKsWAig/5b2e71e83e8f25b7883a87b087dfeee5/2013_2034.896.jpg" ---<file_sep>/_coll_country/zimbabwe.md --- contentful: sys: id: 5NA4gzQrYW8kYCq60q4GOw created_at: !ruby/object:DateTime 2015-12-08 11:20:37.367000000 Z updated_at: !ruby/object:DateTime 2018-05-17 16:54:03.994000000 Z content_type_id: country revision: 10 name: Zimbabwe slug: zimbabwe col_url: http://www.britishmuseum.org/research/collection_online/search.aspx?people=197356&place=27040 map_progress: true intro_progress: true image_carousel: - sys: id: 6F8PhokaIMSEgUWE6Gyey created_at: !ruby/object:DateTime 2016-09-12 11:54:37.064000000 Z updated_at: !ruby/object:DateTime 2019-02-12 00:58:15.357000000 Z title: ZIMMSL0010017 description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3744522&partId=1&searchText=ZIMMSL0010017&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/6F8PhokaIMSEgUWE6Gyey/4e378677351cb553f2dde45eabe7f03e/ZIMMSL0010017.jpg" - sys: id: 3nKVXhSvWU0USE20UqK4WI created_at: !ruby/object:DateTime 2016-09-12 11:54:45.125000000 Z updated_at: !ruby/object:DateTime 2019-02-12 00:58:53.178000000 Z title: ZIMMSL0020009 description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3775214&partId=1&searchText=ZIMMSL0020009&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/3nKVXhSvWU0USE20UqK4WI/d65ddb73261c7121ce4c094ff49aa826/ZIMMSL0020009.jpg" - sys: id: 4q3Wj7sKA8akoCm4UMYywG created_at: !ruby/object:DateTime 2016-09-12 11:54:51.814000000 Z updated_at: !ruby/object:DateTime 2019-02-12 00:59:30.879000000 Z title: ZIMMSL0040003 description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3775248&partId=1&searchText=ZIMMSL0040003&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/4q3Wj7sKA8akoCm4UMYywG/c038814e5c673d11968394b1aec7070c/ZIMMSL0040003.jpg" - sys: id: 6nxvTO732wKwKwqsuKAEI6 created_at: !ruby/object:DateTime 2016-09-12 11:54:57.743000000 Z updated_at: !ruby/object:DateTime 2019-02-12 00:59:59.013000000 Z title: ZIMMSL0120005 description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3775380&partId=1&searchText=ZIMMSL0120005&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/6nxvTO732wKwKwqsuKAEI6/132210ed54ffddd50db4a1b5579fa58c/ZIMMSL0120005.jpg" - sys: id: 324JkVvbraMsEKEAE6KIUA created_at: !ruby/object:DateTime 2016-09-12 11:55:03.866000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:00:38.414000000 Z title: ZIMMSL0130018 description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3775491&partId=1&searchText=ZIMMSL0130018&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/324JkVvbraMsEKEAE6KIUA/8bfbaf195d294b2afc9fb9d72f663895/ZIMMSL0130018.jpg" - sys: id: z8wO9hnAHeqwmiImUa2gO created_at: !ruby/object:DateTime 2016-09-12 11:55:10.636000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:01:21.543000000 Z title: ZIMMSL0270011 description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3775854&partId=1&searchText=ZIMMSL0270011&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/z8wO9hnAHeqwmiImUa2gO/b46d28c94bdbea7e60759a9c99abaa9c/ZIMMSL0270011.jpg" featured_site: sys: id: 196SFAKyP2Ec0gqcWAkawG created_at: !ruby/object:DateTime 2016-09-12 11:55:26.290000000 Z updated_at: !ruby/object:DateTime 2016-09-13 13:33:48.421000000 Z content_type_id: featured_site revision: 4 title: <NAME>, Zimbabwe slug: matobo chapters: - sys: id: dcn9MCXYc02mqO620qoe8 created_at: !ruby/object:DateTime 2016-09-12 11:53:51.731000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:53:51.731000000 Z content_type_id: chapter revision: 1 title_internal: 'Zimbabwe: featured site, chapter 1' body: 'The Matobo Hills (also spelled as Matopo or Matopos Hills) are located to the south-west of Zimbabwe, in Matabeleland, one of the two main rock art regions in the country. It is a large region, more than 2000 sq. km, characterized by granite hills separated by nearly parallel valleys where the vegetation consists of scattered woodlands and areas covered by grass with an abundance of wild fruits. The region was occupied since at least the Middle Stone Age, but the human presence increased in the last millennia BC. The region holds an incredible amount of rock art; as many as 3,000 sites have been estimated based on the better surveyed areas. Paintings constitute the vast majority of depictions, although occasional engravings have also been reported. Paintings are usually found in rock shelters and associated with archaeological remains, which show an occupation of the area since the Early Stone Age. ' - sys: id: N3RjMUjWecQWss48koUyG created_at: !ruby/object:DateTime 2016-09-12 11:56:26.939000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:56:26.939000000 Z content_type_id: image revision: 1 image: sys: id: Jy8edAwMCGiAywQIyi0KI created_at: !ruby/object:DateTime 2016-09-12 11:56:31.534000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:56:31.534000000 Z title: ZIMMTB0100001 description: url: "//images.ctfassets.net/xt8ne4gbbocd/Jy8edAwMCGiAywQIyi0KI/4d9692d057fadcc525259a3eb75c00ba/ZIMMTB0100001.jpg" caption: Ladscape of the Matobo Hills, Zimbabwe (2013,2034.23586). ©TARA/David Coulson - sys: id: 7Mivw9c0Q8osQi802O6gwO created_at: !ruby/object:DateTime 2016-09-12 11:53:51.437000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:53:51.437000000 Z content_type_id: chapter revision: 1 title_internal: 'Zimbabwe: featured site, chapter 2' body: 'The rock art of the Matobo Hills is as varied as that of the rest of Zimbabwe, mainly consisting of depictions of animals and human figures often grouped in complex scenes, clustered or represented in rows. Human figures are predominant, with males being more numerous than women and children very rare. They are usually depicted in a slender style, facing left or right but with the upper part of the body facing front, and often carrying bows, arrows or other objects. Regarding the animals, mammals dominate, with the kudu antelope being especially numerous although this animal is not commonly found in the Matobo Hills. A wide range of animals such as smaller antelopes, giraffes, zebras, ostriches, monkeys, eland antelope, rhinoceros and to a lesser extent carnivores are also depicted. The animals are represented in very different attitudes and may be depicted standing still, running or lying. Humans and animals are often related in hunting scenes. Along with animals and human figures, a fair number of geometric symbols are present, including a very characteristic type of motif made of a series of narrow oval-like shapes (formlings) usually depicted vertically, and sometimes interpreted as beehives. ' - sys: id: 1ueCDk3QMc40WGC6gk0qsE created_at: !ruby/object:DateTime 2016-09-12 11:56:47.135000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:56:47.135000000 Z content_type_id: image revision: 1 image: sys: id: 4JrH9kFufCQkEwgGqycIQG created_at: !ruby/object:DateTime 2016-09-12 11:56:43.328000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:56:43.328000000 Z title: ZIMMTB0020005 description: url: "//images.ctfassets.net/xt8ne4gbbocd/4JrH9kFufCQkEwgGqycIQG/da276b8b7efba382dc16df58e2c43bef/ZIMMTB0020005.jpg" caption: View of a complex panel including hundreds of human figures, animals, formlings and other unidentified shapes. Inanke Cave, Matabeleland, Zimbabwe (2013,2034.23350). ©TARA/<NAME> - sys: id: 2Kp0Cep9RmeI4gyMAMMaCy created_at: !ruby/object:DateTime 2016-09-12 11:53:51.486000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:53:51.486000000 Z content_type_id: chapter revision: 1 title_internal: 'Zimbabwe: featured site, chapter 3' body: 'One of the characteristics of the Matobo Hills rock art is the incredible variety of colours used, which includes a wide range of reds, purples, oranges, browns and yellows, as well as black, white and grey tones. Colours are often combined, and in some cases particular colours seem to have been chosen for specific animals. A common feature in some types of animals as giraffes and antelopes is the outline of the figure in red or white, with the body infilled in a different colour. ' - sys: id: 3dGEtOvk6k6i6wQSUsu2I created_at: !ruby/object:DateTime 2016-09-12 11:56:54.742000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:56:54.742000000 Z content_type_id: image revision: 1 image: sys: id: 3ZbDDzdXZuKCEEWWm2WUoE created_at: !ruby/object:DateTime 2016-09-12 11:56:59.400000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:56:59.400000000 Z title: ZIMMTB0020022 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3ZbDDzdXZuKCEEWWm2WUoE/67d4eba9ebb89aaf8394676637773ba5/ZIMMTB0020022.jpg" caption: Detail of a bichrome giraffe surrounded by other animals and human figures. <NAME>, Matabeleland, Zimbabwe (2013,2034.23367). ©TARA/David Coulson - sys: id: 7zD4PqA2mQyY0yCYUYS6wk created_at: !ruby/object:DateTime 2016-09-12 11:53:51.426000000 Z updated_at: !ruby/object:DateTime 2016-09-13 13:33:12.839000000 Z content_type_id: chapter revision: 5 title_internal: 'Zimbabwe: featured site, chapter 4' body: "Many of the depictions in the Matobo Hills are associated with hunter-gatherers, providing a great amount of information about the social, economic and spiritual life of these groups. Depictions of daily objects (bows, vessels, digging sticks, cloaks) appear depicted in the rock art, and humans are shown hunting animals, fighting other groups and dancing in what seem to be ritual scenes. In fact, many of the scenes show strong similarities to those found in the Drakensberg (South Africa), and part of the iconography in the Zimbabwean paintings – ‘therianthropes’ (part-human, part-animal figures), elongated figures, rain animals, geometric figures – can be easily related to trance or rain-making activities similar to those seen in South Africa. These paintings have been interpreted as representing the trance experiences of shamans (the term ‘shaman’ is derived from Siberian concepts of Shamanism and its applicability to San&#124;Bushman¹ cultures has been questioned, but it is utilised here on the understanding that it sufficiently represents trancers in this academic context, where it is the most frequently used term to describe them). However, unlike in South Africa, the Matobo Hills rock art is not recent and researchers lack the key ethnographic records that help us to interpret the paintings. Therefore, interpretations cannot be directly extrapolated from the South African paintings to those of the Matobo Hills, and researchers such as <NAME> have broadened the interpretative framework of this art to include social issues in addition to the religious. \n\n" - sys: id: 5njv3ZB8WWG0e2MkM4wuIw created_at: !ruby/object:DateTime 2016-09-12 11:57:11.432000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:57:11.432000000 Z content_type_id: image revision: 1 image: sys: id: 1vZtYjldh2UmCICQEIC8UG created_at: !ruby/object:DateTime 2016-09-12 11:57:17.337000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:57:17.337000000 Z title: ZIMMTB0010007 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1vZtYjldh2UmCICQEIC8UG/18487324c77eb308393d900eb5f4a3c4/ZIMMTB0010007.jpg" caption: Human figures running or seated over a wavy, yellow line outlined in red and infilled in yellow. Maholoholo cave, Matabeleland, Zimbabwe (2013,2034.23327). ©TARA/<NAME> - sys: id: 2MAT92oDegwysmWWecW8go created_at: !ruby/object:DateTime 2016-09-12 11:53:51.570000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:53:51.570000000 Z content_type_id: chapter revision: 1 title_internal: 'Zimbabwe: featured site, chapter 5' body: 'Not all the paintings in the Matobo Hills can be ascribed to groups of hunter gatherers, though. Although fewer, there are some paintings that correspond to a later period which were made by Iron Age farmers. Unlike in South Africa, rock art does not show evidence of interaction between these two groups, and it is probable that the hunter-gatherers that inhabited the area were either displaced or absorbed by these new farmer communities. However, some of the later paintings show some links with the previous hunter-gatherers traditions. This later art consists mainly of schematic figures (usually animals, including domestic ones such as goats and cows) and geometric symbols, mostly depicted in white but also red or black and smeared with the hand or the fingers. ' - sys: id: 1U1ln6bdtSIGYYiKu0M68M created_at: !ruby/object:DateTime 2016-09-12 11:57:35.126000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:57:35.126000000 Z content_type_id: image revision: 1 image: sys: id: 1iRymPGEvYW4YUwsWCuw66 created_at: !ruby/object:DateTime 2016-09-12 11:57:30.948000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:57:30.948000000 Z title: ZIMMTB0070009 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1iRymPGEvYW4YUwsWCuw66/6d6a5a4e658e2c74a771bdf36a8052a8/ZIMMTB0070009.jpg" caption: Iron age white paintings. Zimbabwe (2013,2034.23487). ©TARA/<NAME> - sys: id: 5MtdMVT44MIamC44CmcMog created_at: !ruby/object:DateTime 2016-09-12 11:53:51.463000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:53:51.463000000 Z content_type_id: chapter revision: 1 title_internal: 'Zimbabwe: featured site, chapter 6' body: 'The Matobo Hills constitute a perfect example of how nature and human presence can become imbricated, to create a living landscape in which every hill is recognized individually and many of them are still venerated by the communities living in the area. Undoubtedly, rock art played a significant role in this process of progressive sacralisation of the landscape. The importance of the thousands of sites scattered throughout the hills is an invaluable testimony of the strong spirituality of hunter-gatherers that created it, and their deep relation to the land in which they lived. ' - sys: id: 1Y6kzmIX4AimYGC4AYQM4 created_at: !ruby/object:DateTime 2016-09-12 11:57:43.734000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:57:43.734000000 Z content_type_id: image revision: 1 image: sys: id: AlCcF5GAcC44Q268AUsuq created_at: !ruby/object:DateTime 2016-09-12 11:57:48.037000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:57:48.037000000 Z title: ZIMMTB0100024 description: url: "//images.ctfassets.net/xt8ne4gbbocd/AlCcF5GAcC44Q268AUsuq/1a776553071d70cc070382226c7dc5ab/ZIMMTB0100024.jpg" caption: Antelopes and human figures. Bambata cave, Matabeleland, Zimbabwe (2013,2034.23609). ©TARA/<NAME> - sys: id: 4cN05gyK9aWYwscgeMuA4E created_at: !ruby/object:DateTime 2016-09-13 13:33:44.736000000 Z updated_at: !ruby/object:DateTime 2016-09-13 13:33:44.736000000 Z content_type_id: chapter revision: 1 title_internal: Matobo Chapter 7 body: "¹ San&#124;Bushmen is a collective term used to describe the many different hunter-gatherer-fisher groups living in southern Africa who have related languages and cultural traditions. Both 'San' and 'Bushmen' are considered offensive terms by some members of these groups, although others have positively adopted them." citations: - sys: id: nZhwDQUvyCcK8kYqoWWK2 created_at: !ruby/object:DateTime 2016-09-12 11:54:06.690000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:54:06.690000000 Z content_type_id: citation revision: 1 citation_line: "<NAME>. (2012): The Rock Art of the Matobo Hills, Zimbabwe. Adoranten: 38-59\n\nP<NAME>th (2012): Guide to the Rock Art of the Matopo Hills, Zimbabwe. Bulawayo, AmaBooks Publishers. \n" background_images: - sys: id: Jy8edAwMCGiAywQIyi0KI created_at: !ruby/object:DateTime 2016-09-12 11:56:31.534000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:56:31.534000000 Z title: ZIMMTB0100001 description: url: "//images.ctfassets.net/xt8ne4gbbocd/Jy8edAwMCGiAywQIyi0KI/4d9692d057fadcc525259a3eb75c00ba/ZIMMTB0100001.jpg" - sys: id: 1iRymPGEvYW4YUwsWCuw66 created_at: !ruby/object:DateTime 2016-09-12 11:57:30.948000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:57:30.948000000 Z title: ZIMMTB0070009 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1iRymPGEvYW4YUwsWCuw66/6d6a5a4e658e2c74a771bdf36a8052a8/ZIMMTB0070009.jpg" key_facts: sys: id: 2H6YAlzi1yYIKMia26EGwc created_at: !ruby/object:DateTime 2016-09-12 12:01:05.308000000 Z updated_at: !ruby/object:DateTime 2016-09-12 12:01:05.308000000 Z content_type_id: country_key_facts revision: 1 title_internal: 'Zimbabwe: key facts' image_count: 1150 images date_range: Unknown, but most probably several thousands of years old main_areas: Concentrated to the north around the area of Mashonaland and to the southwest in Matabeleland techniques: Mostly painted in a wide range of colours, sometimes combined main_themes: Wild animals, human figures, hunting or dancing scenes, geometric symbols thematic_articles: - sys: id: 2ULickNOv688OaGigYCWYm created_at: !ruby/object:DateTime 2018-05-09 15:26:39.131000000 Z updated_at: !ruby/object:DateTime 2018-05-09 15:28:31.662000000 Z content_type_id: thematic revision: 2 title: Landscapes of Rock Art slug: landscapes-of-rock-art lead_image: sys: id: 62Htpy9mk8Gw28EuUE6SiG created_at: !ruby/object:DateTime 2015-11-30 16:58:24.956000000 Z updated_at: !ruby/object:DateTime 2015-11-30 16:58:24.956000000 Z title: SOADRB0050042_1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/62Htpy9mk8Gw28EuUE6SiG/9cd9572ea1c079f4814104f40045cfb6/SOADRB0050042.jpg" chapters: - sys: id: Ga9XxWBfqwke88qwUKGc2 - sys: id: 5NCw7svaw0IoWWK2uuYEQG - sys: id: 7ng9hfsvLi2A0eWU6A0gWe - sys: id: 4ptu3L494cEYqk6KaY40o4 - sys: id: 5C3yAo4w24egO2O46UCCQg - sys: id: 5FmuBPI2k0o6aCs8immMWQ - sys: id: 6cU5WF1xaEUIiEEkyoWaoq - sys: id: 1YZyNsFTHWIoYegcigYaik - sys: id: 6fhRJ1NiO4wSwSmqmSGEQA - sys: id: 6EhIOeplUA6ouw2kiOcmWe - sys: id: 2g0O5GIiaESIIGC2OOMeuC - sys: id: 4Zj7sd5KJW4Eq2i4aSmQSS - sys: id: 5I9qkMsO5iqI0s6wqQkisk - sys: id: 6WsItqVm8wawokCiCgE4Gu - sys: id: 1631tf7fv4QUwei0IIEk6I - sys: id: 6ycsEOIb0AgkqoQ4MUOMQi - sys: id: 2aa2jzRtPqwK8egGek6G6 - sys: id: 47L9Y10YHmWY04QWCmI4qe - sys: id: 175X82dwJgqGAqkqCu4CkQ - sys: id: 5CGHVFKSUEA0oqY0cS2Cgo - sys: id: 60mUuKWzEkUMUeg4MEUO68 - sys: id: 5AvLn9pvKoeYW2OKqwkUgQ citations: - sys: id: 5z9VWU8t2MeaiAeQWa0Ake background_images: - sys: id: 1yhBeyGEMYkuay2osswcyg created_at: !ruby/object:DateTime 2018-05-09 15:16:49.135000000 Z updated_at: !ruby/object:DateTime 2018-05-09 15:16:49.135000000 Z title: SOANTC0030004 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1yhBeyGEMYkuay2osswcyg/7cab20823cbc01ae24ae6456d6518dbd/SOANTC0030004.jpg" - sys: id: 1rRAJpaj6UMCs6qMKsGm8K created_at: !ruby/object:DateTime 2018-05-09 15:14:41.480000000 Z updated_at: !ruby/object:DateTime 2018-05-09 15:14:41.480000000 Z title: SOANTC0050054 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1rRAJpaj6UMCs6qMKsGm8K/f92d2174d4c5109237ab00379c2088b7/SOANTC0050054.jpg" - sys: id: 9cRmg60WNGAk6i8Q6WKWm created_at: !ruby/object:DateTime 2018-05-10 14:12:25.736000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:42:15.905000000 Z content_type_id: thematic revision: 2 title: Introduction to rock art in southern Africa slug: rock-art-in-southern-africa lead_image: sys: id: 3cyElw8MaIS24gq8ioCcka created_at: !ruby/object:DateTime 2016-09-12 15:12:39.975000000 Z updated_at: !ruby/object:DateTime 2016-09-12 15:12:39.975000000 Z title: SOADRB0080007 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3cyElw8MaIS24gq8ioCcka/fcea216b7327f325bf27e3cebe49378e/SOADRB0080007.jpg" chapters: - sys: id: 5qv45Cw424smAwqkkg4066 created_at: !ruby/object:DateTime 2016-09-13 13:01:39.329000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:09:20.849000000 Z content_type_id: chapter revision: 6 title_internal: 'Southern Africa: regional, chapter 1' body: |+ The southern African countries of Zimbabwe, South Africa, Lesotho, Swaziland, Mozambique, Botswana and Namibia contain thousands of rock art sites and southern African rock art has been studied extensively. Due to perceived similarities in subject matter, even across great distances, much southern African rock art has been ascribed to hunter-gatherer painters and engravers who appear to have had a shared set of cultural references. These have been linked with beliefs and practices which remain common to modern San&#124;Bushman¹ people, a number of traditional hunter-gatherer groups who continue to live in Southern Africa, principally in Namibia, Botswana and South Africa. There are, however, differences in style and technique between regions, and various rock art traditions are attributed to other cultural groups and their ancestors. As is often the case with rock art, the accurate attribution of authorship, date and motivation is difficult to establish, but the rock art of this region continues to be studied and the richness of the material in terms of subject matter, as well as in the context of the archaeological record, has much to tell us, both about its own provenance and the lives of the people who produced it. - sys: id: r3hNyCQVUcGgGmmCKs0sY created_at: !ruby/object:DateTime 2016-09-13 13:02:04.241000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:09:49.095000000 Z content_type_id: chapter revision: 2 title: Geography and distribution title_internal: 'Southern Africa: regional, chapter 2' - sys: id: 5cKrBogJHiAaCs6mMoyqee created_at: !ruby/object:DateTime 2016-09-13 13:02:27.584000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:10:55.925000000 Z content_type_id: image revision: 4 image: sys: id: 4RBHhRPKHC2s6yWcEeWs0c created_at: !ruby/object:DateTime 2016-09-13 13:02:17.232000000 Z updated_at: !ruby/object:DateTime 2016-09-13 13:02:17.232000000 Z title: ZIMMSL0070001 description: url: "//images.ctfassets.net/xt8ne4gbbocd/4RBHhRPKHC2s6yWcEeWs0c/9d9bc5196cfac491fa099fd737b06e34/ZIMMSL0070001.jpg" caption: Yellow elephant calf painted on the roof of a shelter. Mashonaland, Zimbabwe. 2013,2034.22675 ©TARA/<NAME> col_link: http://bit.ly/2iUgvg0 - sys: id: 69tB5BiRVKG2QQEKoSYw08 created_at: !ruby/object:DateTime 2016-09-13 13:02:41.530000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:11:21.260000000 Z content_type_id: chapter revision: 3 title_internal: 'Southern Africa: regional, chapter 3' body: 'There is wide variation in the physical environments of southern Africa, ranging from the rainforests of Mozambique to the arid Namib Desert of western Namibia, with the climate tending to become drier towards the south and west. The central southern African plateau is divided by the central dip of the Kalahari basin, and bordered by the Great Escarpment, a sharp drop in altitude towards the coast which forms a ridge framing much of southern Africa. The escarpment runs in a rough inland parallel to the coastline, from northern Angola, south around the Cape and up in the east to the border between Zimbabwe and Malawi. Both painted and engraved rock art is found throughout southern Africa, with the type and distribution partially informed by the geographical characteristics of the different regions. Inland areas with exposed boulders, flat rock ‘pavements’ and rocky outcrops tend to feature engraved rock art, whereas paintings are more commonly found in the protective rock shelters of mountainous or hilly areas, often in ranges edging the Great Escarpment. ' - sys: id: 4BJ17cEGyIC6QYSYGAkoaa created_at: !ruby/object:DateTime 2016-09-13 13:03:04.486000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:11:57.877000000 Z content_type_id: image revision: 3 image: sys: id: 1hXbvhDSf2CmOss6ec0CsS created_at: !ruby/object:DateTime 2016-09-13 13:02:59.339000000 Z updated_at: !ruby/object:DateTime 2016-09-13 13:02:59.339000000 Z title: NAMBRG0030001 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1hXbvhDSf2CmOss6ec0CsS/0bb079e491ac899abae435773c74fcf4/NAMBRG0030001.jpg" caption: View out of a rock shelter in the Brandberg, Namibia. 2013,2034.20452 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3729901 - sys: id: 499lI34cAE6KAgKU4mkcqq created_at: !ruby/object:DateTime 2016-09-13 13:03:14.736000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:12:17.831000000 Z content_type_id: chapter revision: 5 title: Types of rock art title_internal: 'Southern Africa: regional, chapter 4' body: "Rock art of the type associated with hunter-gatherers is perhaps the most widely distributed rock art tradition in southern Africa, with numerous known examples in South Africa, Namibia and Zimbabwe, but also with examples found in Botswana and Mozambique. This tradition comprises paintings and engravings, with both techniques featuring images of animals and people. The type and composition varies from region to region. For example, rock art sites of the southern Drakensberg and Maloti mountains in South Africa and Lesotho contain a higher proportion of images of eland antelope, while those in Namibia in turn feature more giraffes. There are also regional variations in style and colour: in some sites and areas paintings are polychrome (multi-coloured) while in others they are not.\n\nDifferences also occur in composition between painting and engraving sites, with paintings more likely to feature multiple images on a single surface, often interacting with one another, while engraving sites more often include isolated images on individual rocks and boulders. \ However, there are commonalities in both imagery and style, with paintings throughout southern Africa often including depictions of people, particularly in procession and carrying items such as bows and arrows. Also heavily featured in both paintings and engravings are animals, in particular large ungulates which are often naturalistically depicted, sometimes in great detail. Additionally, images may include people and animals which appear to have the features of several species and are harder to identify. Some hunter-gatherer type paintings are described as ‘fine-line’ paintings because of the delicacy of their rendering with a thin brush. \n" - sys: id: 4NfdPoVtFKaM6K4w8I8ckg created_at: !ruby/object:DateTime 2016-09-13 13:22:13.102000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:12:40.860000000 Z content_type_id: image revision: 4 image: sys: id: 20oHYa0oEcSEMOyM8IcCcO created_at: !ruby/object:DateTime 2016-09-13 13:22:08.653000000 Z updated_at: !ruby/object:DateTime 2016-09-13 13:22:08.653000000 Z title: NAMBRT0010002 description: url: "//images.ctfassets.net/xt8ne4gbbocd/20oHYa0oEcSEMOyM8IcCcO/67a69f9814e8ec994003bfacff0962cc/NAMBRT0010002.jpg" caption: " Fine-line paintings of giraffes and line patterns, Brandberg, Namibia. \ It is thought that giraffes may have been associated with rain in local belief systems. 2013,2034.21324 © TARA/<NAME>" col_link: http://bit.ly/2j9778d - sys: id: 2nqpXdHTeoyKakEEOMUSA0 created_at: !ruby/object:DateTime 2016-09-13 13:03:40.877000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:13:26.231000000 Z content_type_id: chapter revision: 9 title_internal: 'Southern Africa: regional, chapter 5' body: "Hunter-gatherer rock paintings are found in particular concentrations in the Drakensberg-Maloti and Cape Fold Mountains in South Africa and Lesotho, the Brandberg and Erongo Mountains in Namibia and the Matobo Hills in Zimbabwe, while engraving sites are found throughout the interior, often near water courses. \n\nA different form of rock painting from the hunter-gatherer type, found mainly in the north-eastern portion of southern Africa is that of the ‘late whites’. Paintings in this tradition are so-called because they are usually associated with Bantu language-speaking Iron Age farming communities who entered the area from the north from around 2,000 years ago and many of these images are thought to have been painted later than some of the older hunter-gatherer paintings. ‘Late white’ paintings take many forms, but have generally been applied with a finger rather than a brush, and as the name suggests, are largely white in colour. These images represent animals, people and geometric shapes, often in quite schematic forms, in contrast to the generally more naturalistic depictions of the hunter-gatherer art. \n\nSometimes ‘late white’ art images relate to dateable events or depict objects and scenes which could only have taken place following European settlement, such as trains. \ Other forms of southern African rock art also depict European people and objects. These include images from the Western Cape in South Africa of a sailing ship, estimated to date from after the mid-17th century, as well as painted and engraved imagery from throughout South Africa showing people on horseback with firearms. Such images are sometimes termed ‘contact art’ as their subject matter demonstrates that they follow the period of first contact between European and indigenous people. \n" - sys: id: 1NrA6Z43fWIgwGoicy2Mw2 created_at: !ruby/object:DateTime 2016-09-13 13:03:57.014000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:13:43.550000000 Z content_type_id: image revision: 2 image: sys: id: 6QHTRqNGXmWic6K2cQU8EA created_at: !ruby/object:DateTime 2016-09-13 13:03:52.426000000 Z updated_at: !ruby/object:DateTime 2016-09-13 13:03:52.426000000 Z title: SOASWC0110006 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6QHTRqNGXmWic6K2cQU8EA/3d924964d904e34e6711c6224a7429e6/SOASWC0110006.jpg" caption: Painting of a ship from the south Western Cape in South Africa. 2013,2034.19495 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3730142&partId=1&searchText=2013%2c2034.19495&page=1 - sys: id: 4JVHOgrOyAAI8GWAuoyGY created_at: !ruby/object:DateTime 2016-09-13 13:24:14.217000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:17:20.511000000 Z content_type_id: chapter revision: 5 title_internal: 'Southern Africa: regional, chapter 6' body: "This kind of imagery is found in a variety of styles, and some of those producing ‘contact’ images in the Cape may have been people of Khoekhoen heritage. The Khoekhoen were traditionally cattle and sheep herders, culturally related to modern Nama people and more loosely to San&#124;Bushman hunter-gatherers. \ A distinct tradition of rock art has been suggested to be of ancestral Khoekhoen origin. This art is predominantly geometric in form, with a particular focus on circle and dotted motifs, and engravings in this style are often found near watercourses. \n" - sys: id: 3zUtkjM57Omyko6Q2O0YMG created_at: !ruby/object:DateTime 2016-09-13 13:04:05.564000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:17:47.538000000 Z content_type_id: chapter revision: 6 title: History of research title_internal: 'Southern Africa: regional, chapter 7' body: 'The first known reports of African rock art outside of the continent appear to come from the Bishop of Mozambique, who in 1721 reported sightings of paintings on rocks to the Royal Academy of History in Lisbon. Following this, reports, copies and publications of rock art from throughout modern South Africa were made with increasing frequency by officials and explorers. From the mid-19th century onwards, rock art from present-day Namibia, Zimbabwe and Botswana began to be documented, and during the first few decades of the twentieth century global public interest in the art was piqued by a series of illustrated publications. The hunter-gatherer rock art in particular had a strong aesthetic and academic appeal to western audiences, and reports, photographs and copied images attracted the attention of prominent figures in archaeology and ethnology such as <NAME>, <NAME> and the Abbé Breuil, researchers whose interest in rock art worldwide let them to visit and write about southern African rock art sites. A further intensification of archaeological and anthropological research and recording in the 1950s-70s, resulted in new insights into the interpretations and attributions for southern African rock art. Rock art research continues throughout the area today. ' - sys: id: 5bPZwsgp3qOGkogYuCIQEs created_at: !ruby/object:DateTime 2016-09-13 13:04:30.652000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:18:07.313000000 Z content_type_id: image revision: 3 image: sys: id: 3BLPJ6SPMcccCE2qIG4eQG created_at: !ruby/object:DateTime 2016-09-13 13:04:26.508000000 Z updated_at: !ruby/object:DateTime 2016-09-13 13:04:26.508000000 Z title: BOTTSD0300015 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3BLPJ6SPMcccCE2qIG4eQG/639dd24028612b985042ea65536eef2e/BOTTSD0300015.jpg" caption: Rhinoceros and cattle painting, Tsodilo Hills, Botswana. 2013,2034.20848 © TARA/<NAME> col_link: http://bit.ly/2i5xfUJ - sys: id: 1QaeG3pF1KOEaooucoMUeE created_at: !ruby/object:DateTime 2016-09-13 13:04:37.305000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:18:34.546000000 Z content_type_id: chapter revision: 4 title: Interpretation title_internal: 'Southern Africa: regional, chapter 8' body: Rather than showing scenes from daily life, as was once assumed, it is now usually accepted that hunter-gatherer art in southern Africa shows images and motifs of spiritual and cultural importance. In particular, it is thought that some images reflect trance visions of San&#124;Bushman spiritual leaders, or shamans, during which they are considered to enter the world of spirits, where they are held to perform tasks for themselves and their communities, such as healing the sick or encouraging rain. This interpretation, which has been widely accepted, explains certain features of the art, for example the predominance of certain animals like eland antelope (due to their special cultural significance) and themes such as dot patterns and zigzag lines (interpreted as geometric patterns that shamans may see upon entering a trance state). - sys: id: 1YgT9SlSNeU8C6Cm62602E created_at: !ruby/object:DateTime 2016-09-13 13:04:53.447000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:19:08.779000000 Z content_type_id: image revision: 2 image: sys: id: 5Zk1QhSjEAOy8U6kK4yS4c created_at: !ruby/object:DateTime 2016-09-13 13:04:48.941000000 Z updated_at: !ruby/object:DateTime 2016-09-13 13:04:48.941000000 Z title: SOADRB0030002 description: url: "//images.ctfassets.net/xt8ne4gbbocd/5Zk1QhSjEAOy8U6kK4yS4c/5896c3d088678257f9acd01bd59c4b26/SOADRB0030002.jpg" caption: 'Painting of an eland and an ambiguous figure in the Drakensberg, South Africa. Both the eland and this kind of human-like figure are thought to have had symbolic associations with beliefs about gender and power. 2013,2034.18187© TARA/<NAME> ' col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3738250&partId=1&searchText=2013,2034.18187&page=1 - sys: id: 5byxQopdNCqEC2kCa0OqCm created_at: !ruby/object:DateTime 2016-09-13 13:05:00.899000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:19:37.565000000 Z content_type_id: chapter revision: 4 title_internal: 'Southern Africa: regional, chapter 9' body: "The rock art attributed to ancestral San&#124;Bushman hunter-gatherers has many varied motifs, some of which may also relate to specific themes such as initiation or rainmaking (indeed within its cultural context one image may have several significances). San&#124;Bushman informants in the 19th century told researchers that certain ambiguously shaped animals in the rock art repertoire represented animals related to water. Images such as these are known to researchers as 'rain animals' and it has been suggested that certain images could reflect—or prompt—the shaman's attempt to control rainfall. Some 'late white' art has also been proposed to have associations with rainmaking practices, and indeed the proximity of some geometric rock art images, proposed to be of possible Khoekhoen origin, to watercourses appears to emphasise the practical and spiritual significance of water among historical southern African communities. It has also been proposed that some forms of geometric art attributed to Khoekhoen people may be linked by tradition and motif to the schematic art traditions of central Africa, themselves attributed to hunter-gatherers and possibly made in connection with beliefs about water and fertility. Much in the “late white” corpus of paintings appears to be connected to initiation practices, part of a larger set of connected traditions extending north as far as Kenya. \n\nThe long time periods, cultural connections, and movements involved can make attribution difficult. For example, the idiosyncratic rock paintings of Tsodilo Hills in Botswana which appear to have similarities with the hunter-gatherer style include images of domesticates and may have been the work of herders. More localised traditions, such as that of engravings in north-western South Africa representing the homesteads of ancestral Nguni or Sotho-Tswana language speakers, or the focus on engravings of animal tracks found in Namibia, demonstrate more specific regional significances. Research continues and in recent decades, researchers, focusing on studying individual sites and sets of sites within the landscape and the local historical context, have discussed how their placement and subject matter may reflect the shifting balances of power, and changes in their communities over time. \n" - sys: id: L9AkWhM1WwUKWC4MQ4iMe created_at: !ruby/object:DateTime 2016-09-13 13:05:15.123000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:21:01.026000000 Z content_type_id: image revision: 5 image: sys: id: ETDpJFg6beKyyOmQGCsKI created_at: !ruby/object:DateTime 2016-09-13 13:05:11.473000000 Z updated_at: !ruby/object:DateTime 2016-09-13 13:05:11.473000000 Z title: NAMSNH0030006 description: url: "//images.ctfassets.net/xt8ne4gbbocd/ETDpJFg6beKyyOmQGCsKI/3dabb2ba8a3abaa559a6652eb10ea1eb/NAMSNH0030006.jpg" caption: 'Geometric rock engravings of the type suggested by some to be the work of Khoekhoen pastoralists and their ancestors. 2013,2034.22405 © TARA/David Coulson ' col_link: http://bit.ly/2iVIIoL - sys: id: ayvCEQLjk4uUk8oKikGYw created_at: !ruby/object:DateTime 2016-09-13 13:05:22.665000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:21:16.059000000 Z content_type_id: chapter revision: 6 title: Dating title_internal: 'Southern Africa: regional, chapter 10' body: "Although dating rock art is always difficult, the study of rock art sites from southern Africa has benefitted from archaeological study and excavations at rock art sites have sometimes revealed useful information for ascribing dates. Some of the oldest reliably dated examples of rock art in the world have been found in the region, with the most well-known examples probably being the painted plaques from Apollo 11 Cave in Namibia, dated to around 30,000 years ago. A portion of an engraved animal found in South Africa’s Northern Cape is estimated to be 10,200 years old and painted spalls from shelter walls in Zimbabwe have been dated to 12,000 years ago or older. However, it is thought that the majority of existing rock art was made more recently. \ As ever, subject matter is also helpful in ascribing maximum date ranges. \ We know, for example,that images of domestic animals are probably less than 2,000 years old. The condition of the art may also help to establish relative ages, particularly with regards to engravings, which may be in some cases be categorised by the discolouration of the patina that darkens them over time. \n\nThe multiplicity of rock art sites throughout southern Africa form a major component of southern Africa’s archaeological record, with many interesting clues about the lives of past inhabitants and, in some cases, continuing religious and cultural importance for contemporary communities. \ Many sites are open to the public, affording visitors the unique experience of viewing rock art in situ. Unfortunately, the exposed nature of rock art in the field leaves it open to potential damage from the environment and vandalism. \ Many major rock art sites in southern Africa are protected by law in their respective countries and the Maloti-Drakensberg Park in South Africa and Lesotho, Twyfelfontein/ǀUi-ǁAis in Namibia, Tsodilo Hills in Botswana and the Matobo Hills in Zimbabwe are all inscribed on the UNESCO World Heritage list. \n" - sys: id: 3Kjcm7V1dYoCuyaqKga0GM created_at: !ruby/object:DateTime 2016-09-13 13:05:38.418000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:25:17.372000000 Z content_type_id: image revision: 2 image: sys: id: 58V5qef3pmMGu2aUW4mSQU created_at: !ruby/object:DateTime 2016-09-13 13:05:34.865000000 Z updated_at: !ruby/object:DateTime 2016-09-13 13:05:34.865000000 Z title: NAMDME0080012 description: url: "//images.ctfassets.net/xt8ne4gbbocd/58V5qef3pmMGu2aUW4mSQU/dec59cd8209d3d04b13447e9c985574a/NAMDME0080012.jpg" caption: Engraved human footprints, Erongo Region, Namibia. 2013,2034.20457 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3729958&partId=1&searchText=2013,2034.20457+&page=1 - sys: id: 1kwt8c4P0gSkYOq8CO0ucq created_at: !ruby/object:DateTime 2016-09-13 13:28:16.189000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:25:44.294000000 Z content_type_id: chapter revision: 2 title_internal: 'Southern Africa: regional, chapter 11' body: "¹ San&#124;Bushmen is a collective term used to describe the many different hunter-gatherer-fisher groups living in southern Africa who have related languages and cultural traditions. Both 'San' and 'Bushmen' are considered offensive terms by some members of these groups, although others have positively adopted them." citations: - sys: id: 6GlTdq2WbeIQ6UoeOeUM84 created_at: !ruby/object:DateTime 2016-10-17 10:45:36.418000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:39:37.963000000 Z content_type_id: citation revision: 2 citation_line: |+ <NAME>., <NAME>. and <NAME>. 2010. Tsodilo Hills: Copper Bracelet of the Kalahari. East Lansing: Michigan State University Press. Garlake, <NAME>. 1995. The Hunter's Vision: The Prehistoric Art of Zimbabwe. London: British Museum Press. Lewis-Williams, J.D. 1981. Believing and Seeing: Symbolic Meanings in San&#124;BushmanRock Paintings. Johannesburg: University of Witwatersrand Press <NAME>. 1995. 'Neglected Rock Art: The Rock Engravings of Agriculturist Communities in South Africa'. South African Archaeological Bulletin. Vol. 50 No. 162. pp. 132.142. <NAME>. 1989. Rock Paintings of the Upper Brandberg. vols. I-VI. Köln: Heinrich-Barth-Institut <NAME>. & <NAME>. 2008. 'Beyond Development - Global Visions and Local Adaptations of a Contested Concept' in Limpricht, C., & M. Biesele (eds) Heritage and Cultures in modern Namibia: in-depth views of the country: a TUCSIN Festschrift. Goettingen : Klaus Hess Publishers. pp 37:46. <NAME>. 2013. 'Rock Art Research in Africa' in Mitchell, P. and P. Lane (eds), The Oxford Handbook of African Archaeology. Oxford, Oxford University Press. <NAME>. & <NAME>. 2004. 'Taking Stock: Identifying Khoekhoen Herder Rock Art in Southern Africa'. Current Anthropology Vol. 45, No. 4. pp 499-52. background_images: - sys: id: 6oQGgfcXZYWGaeaiyS44oO created_at: !ruby/object:DateTime 2016-09-13 13:05:47.458000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:41:12.556000000 Z title: ZIMMSL0120015.tiff description: url: "//images.ctfassets.net/xt8ne4gbbocd/6oQGgfcXZYWGaeaiyS44oO/c8bc0d9d1ceee0d23517a1bc68276b24/ZIMMSL0120015.tiff.jpg" - sys: id: 69ouDCLqDKo4EQWa6QCECi created_at: !ruby/object:DateTime 2016-09-13 13:05:55.993000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:41:44.910000000 Z title: SOAEFS0030008 description: url: "//images.ctfassets.net/xt8ne4gbbocd/69ouDCLqDKo4EQWa6QCECi/9c5da3bf755188e90003a9bc55550f6f/SOAEFS0030008.jpg" country_introduction: sys: id: 57nTuvCZRm2kQIWosYeEQq created_at: !ruby/object:DateTime 2016-09-12 11:58:22.969000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:58:22.969000000 Z content_type_id: country_information revision: 1 title: 'Zimbabwe: country introduction' chapters: - sys: id: 7wG2jigwgw4cGsusgAeCGc created_at: !ruby/object:DateTime 2016-09-12 11:53:52.433000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:53:52.433000000 Z content_type_id: chapter revision: 1 title: Introduction - Geography and rock art distribution title_internal: 'Zimbabwe: country, chapter 1' body: 'Zimbabwe is a landlocked country surrounded by Mozambique, Zambia, Botswana and South Africa, occupying a large, granitic high plateau between the Zambezi and Limpopo river systems, with a tropical climate moderated by altitude. The highest part of the country is the eastern Highlands; a north-south mountain range reaching altitudes of 2,500 m. Rock art is located in two main areas, the northern region of Mashonaland and the south-western area of Matabeleland. These areas are full of granite hills and boulders that provide excellent shelters for the paintings. The Matobo hills in Matabeleland constitute one of the most outstanding examples of rock art in Southern Africa. The total number of Zimbabwean rock art sites is unknown, but estimations made point to thousands of sites throughout the country, with more being discovered annually. ' - sys: id: 1vTYjbXbXuoWIu8Og2Ga6u created_at: !ruby/object:DateTime 2016-09-12 11:58:16.773000000 Z updated_at: !ruby/object:DateTime 2019-02-12 00:40:06.610000000 Z content_type_id: image revision: 2 image: sys: id: 40o6cuVD1mg0GcouA8Iaym created_at: !ruby/object:DateTime 2016-09-12 12:06:48.519000000 Z updated_at: !ruby/object:DateTime 2016-09-12 12:06:48.519000000 Z title: ZIMMSL0280001 description: url: "//images.ctfassets.net/xt8ne4gbbocd/40o6cuVD1mg0GcouA8Iaym/32da0eecea127afbf2c5f839534485da/ZIMMSL0280001.jpg" caption: Rocky outcrop in Mashonaland, Zimbabwe. 2013,2034.23240 ©TARA/David Coulson col_link: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3775899&partId=1&searchText=2013,2034.23240&page=1 - sys: id: 2P8CUhzioUcQ2WQUCmy4eK created_at: !ruby/object:DateTime 2016-09-12 11:53:52.382000000 Z updated_at: !ruby/object:DateTime 2016-09-12 18:50:57.591000000 Z content_type_id: chapter revision: 2 title: History of the research title_internal: 'Zimbabwe: country, chapter 2' body: 'Zimbabwean rock art was first reported by Europeans in 1927, when Miles Burkitt visited southern Africa, but is especially linked to <NAME>ius, one of the most renowned researchers in the first decades of the 20th century. Le<NAME> travelled to the region in 1928 with a German team and thoroughly documented numerous paintings, identifying many of the most characteristic features of Zimbabwean rock art. However, he failed in identifying the authors of the paintings, ascribing them to external influences of “high civilizations” instead to the local communities who made them. Subsequently, work was continued by <NAME>, who for forty years documented rock art paintings constituting a huge corpus of tracings, but without developing an interpretative framework for them. In the 1950s, another historic researcher, the <NAME> Breuil, visited Zimbabwe and studied the paintings, again suggesting an Egyptian or Minoan origin. It wasn’t until the 1960s and 1970s when a more objective approach to the study of rock art started, with <NAME> the most prominent figure in research from the 1980s onwards. Garlake wrote the first comprehensive books on Zimbabwean rock art (Garlake 1987), integrating it within the general framework of southern Africa and raising awareness about the importance of these archaeological expressions. In 2003 the Matobo Hills were included in the World Heritage List acknowledging the relevance of Zimbabwean rock art for African heritage. ' - sys: id: cUUCZ3TJ1mmO48egCGE2k created_at: !ruby/object:DateTime 2016-09-12 11:58:33.564000000 Z updated_at: !ruby/object:DateTime 2019-02-12 00:41:14.221000000 Z content_type_id: image revision: 2 image: sys: id: 2fUMJJmhu0gAW4Kkoscw2i created_at: !ruby/object:DateTime 2016-09-12 11:58:30.277000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:58:30.277000000 Z title: ZIMMSL0070001 description: url: "//images.ctfassets.net/xt8ne4gbbocd/2fUMJJmhu0gAW4Kkoscw2i/6c0c5908e2526dae2378c771a641e1f0/ZIMMSL0070001.jpg" caption: Yellow elephant calf painted on the roof of a shelter. Mashonaland, Zimbabwe. 2013,2034.22675 ©TARA/<NAME>son col_link: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3775294&partId=1&searchText=2013,2034.22675&page=1 - sys: id: 1GwWneVcV2OGekOmYsisAk created_at: !ruby/object:DateTime 2016-09-12 11:53:52.340000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:53:52.340000000 Z content_type_id: chapter revision: 1 title: Themes title_internal: 'Zimbabwe: country, chapter 3' body: The rock art of Zimbabwe is some of the richest in Africa both in variety and complexity, the vast majority being painted figures infilled or outlined usually with just one colour, although bichrome examples are also known. The human figure is the most often represented engaged in different activities -hunting, walking, dancing- either isolated or in groups of up to forty people. The figures are depicted in different styles, from the very schematic to relatively naturalistic outlines, with men far more represented than women, and usually depicted carrying bows and arrows. In some cases, these figures are part of very complex scenes including animals and geometric symbols, some of which have been interpreted as trance-like scenes similar to those in South Africa with figures bleeding from their noses, crouching or dancing in groups or sharing animal traits. A very specific type of depiction is human figures with hugely distended abdomens, a trait that is associated either with fertility or mystic potency concepts. - sys: id: 7cZfHMXB84oouoceeswCUQ created_at: !ruby/object:DateTime 2016-09-12 11:58:40.649000000 Z updated_at: !ruby/object:DateTime 2019-02-12 00:42:32.233000000 Z content_type_id: image revision: 3 image: sys: id: 51wED0wl4cSWQAWcEqAKek created_at: !ruby/object:DateTime 2016-09-12 11:58:45.461000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:58:45.461000000 Z title: ZIMMSL0230014 description: url: "//images.ctfassets.net/xt8ne4gbbocd/51wED0wl4cSWQAWcEqAKek/7e367c5c29de4def2fd4fbc4f81b7dd1/ZIMMSL0230014.jpg" caption: Complex scene of human figures and antelopes. Mashonaland, Zimbabwe. 2013,2034.23055 ©TARA/<NAME> col_link: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3775708&partId=1&searchText=2013,2034.23055&page=1 - sys: id: 2JiGtVlFnOqOUEqWcOyCms created_at: !ruby/object:DateTime 2016-09-12 11:53:52.331000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:53:52.331000000 Z content_type_id: chapter revision: 1 title_internal: 'Zimbabwe: country, chapter 4' body: 'Along with human figures, animals are widely represented in Zimbabwean rock art, with kudu depictions dominating, but also with zebra, tsessebe and sable antelopes commonly represented. Surprisingly, other antelopes such as eland, waterbucks or wildebeest are very rarely represented, while other animals (lions, cheetah, birds, ant bears, porcupines, baboons or warthogs) are very scarce. Fish and crocodiles are relatively common, the latter represented as if seen from above or below. There seems to be a preference for the depiction of females rather than males, especially in the case of antelopes or elephants. Regardless of the type of animal, the depictions seem to have a deep symbolism far beyond the representation of animals just hunted and consumed, often being surrounded by dots, flecks or networks of lines. That symbolism is especially important in the case of the elephant, which is often depicted being hunted by groups of men. ' - sys: id: 60AofQXYWsUsusmsKwaGyS created_at: !ruby/object:DateTime 2016-09-12 11:58:54.647000000 Z updated_at: !ruby/object:DateTime 2019-02-12 00:43:25.464000000 Z content_type_id: image revision: 2 image: sys: id: 37IO99TlpSsMKoCoOskwyO created_at: !ruby/object:DateTime 2016-09-12 11:58:59.626000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:58:59.626000000 Z title: ZIMMSL0210014 description: url: "//images.ctfassets.net/xt8ne4gbbocd/37IO99TlpSsMKoCoOskwyO/5156a40344d65934a2c8bdf86d3f78b9/ZIMMSL0210014.jpg" caption: Group of human figures and different types of animals including giraffes, antelopes and warthogs. 2013,2034.22962 ©TARA/<NAME> col_link: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3775615&partId=1&searchText=2013,2034.22962&page=1 - sys: id: 36YlRmgg8EIiueMgCamy6e created_at: !ruby/object:DateTime 2016-09-12 11:53:52.275000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:53:52.275000000 Z content_type_id: chapter revision: 1 title_internal: 'Zimbabwe: country, chapter 5' body: 'Human figures and animals are accompanied by many geometric symbols, usually related to trance-like contexts and include dots, wavy lines or stripes. One of the most original types of symbols known as ‘formlings’, are oblong figures divided in clusters and frequently combining several colours. These are difficult to interpret but could be associated with complex ideas related to trance states, although some other interpretations, such as their relating to beehives, have been suggested (Garlake 1995: 97).' - sys: id: 5icNtVo3wWOg2EA62yK0gI created_at: !ruby/object:DateTime 2016-09-12 11:59:08.602000000 Z updated_at: !ruby/object:DateTime 2019-02-12 00:44:25.781000000 Z content_type_id: image revision: 2 image: sys: id: nRXWoI9Gk8uy2go42GomE created_at: !ruby/object:DateTime 2016-09-12 11:59:12.467000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:59:12.467000000 Z title: ZIMMTB0060005 description: url: "//images.ctfassets.net/xt8ne4gbbocd/nRXWoI9Gk8uy2go42GomE/2bb4e21572df0610dfa429bb8b6f4bf2/ZIMMTB0060005.jpg" caption: Depiction of a formling surrounding by animals. Matabeleland, Zimbabwe. 2013,2034.23465 ©TARA/<NAME> col_link: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3763606&partId=1&searchText=2013,2034.23465&page=1 - sys: id: 5RnaGufDxeImKGM0msMOs6 created_at: !ruby/object:DateTime 2016-09-12 11:53:52.292000000 Z updated_at: !ruby/object:DateTime 2016-09-12 22:03:55.089000000 Z content_type_id: chapter revision: 6 title_internal: 'Zimbabwe: country, chapter 6' body: |- Traditionally, the themes expressed in Zimbabwean rock art have been identified as the same as those of the San&#124;Bushmen¹ from South Africa and in many cases are undoubtedly related, and provide key hints for their interpretation. However, there are also differences, such as the emphasis given to different animals, the higher presence of trees and plants in Zimbabwe or the smaller presence of trance scenes in the north compared to that of the Drakensberg. Moreover, the lack of ethnographic information for Zimbabwean paintings and their older chronology make it difficult to establish the same type of associations as those made for other areas with more direct connections rock art to known cultures, as happens in South Africa. Although in a minority, rock art of a later chronology can be attributed to Iron Age farmers, characterized by more schematic figures, usually white and painted thickly with the finger or the hand. As is the case in other areas in Central Africa, some of these later depictions are related to rain making and initiation ceremonies. ¹ San&#124;Bushmen is a collective term used to describe the many different hunter-gatherer-fisher groups living in southern Africa who have related languages and cultural traditions. Both 'San' and 'Bushmen' are considered offensive terms by some members of these groups, although others have positively adopted them. - sys: id: 62IspwBATCWA6aAe2Ymya8 created_at: !ruby/object:DateTime 2016-09-12 11:59:32.651000000 Z updated_at: !ruby/object:DateTime 2019-02-12 00:45:17.976000000 Z content_type_id: image revision: 2 image: sys: id: 4sy93JCmHKCso2muMWoOc0 created_at: !ruby/object:DateTime 2016-09-12 11:59:28.407000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:59:28.407000000 Z title: ZIMMSL0120052 description: url: "//images.ctfassets.net/xt8ne4gbbocd/4sy93JCmHKCso2muMWoOc0/ac69dd7a46cecd5c4ca9663931e915ed/ZIMMSL0120052.jpg" caption: Iron Age painting depicting a zebra. Mashonaland, Zimbabwe. 2013,2034.22780 ©TARA/<NAME> col_link: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3775418&partId=1&searchText=2013,2034.22780&page=1 - sys: id: 1ovLRkQ1IMUeuGQMoEaymO created_at: !ruby/object:DateTime 2016-09-12 11:53:51.470000000 Z updated_at: !ruby/object:DateTime 2016-09-12 19:02:39.778000000 Z content_type_id: chapter revision: 3 title: Chronology title_internal: 'Zimbabwe: country, chapter 6' body: "As with much rock art, the dating of Zimbabwe paintings is a challenging subject, although there is a consensus about them being significantly older than those of the Drakensberg and probably dated at before 2,000 years ago. The lack of any type of agriculture-related images in the paintings, which was established by the 1st millennium AD, sets a relative dating for the depictions, while the scarcity of sheep (introduced by the second half of the first millennium BC in the area) points to a time period in which these animals were still uncommon. These hints and the fact that, unlike in other areas there are not historical subjects represented in the paintings, seems to indicate that Zimbabwean paintings are at least 1,000 years old. However, archaeological evidence (Walker 2012: 44) suggests that rock art could be significantly older than that, at least several thousands of years old. \n\n" - sys: id: 6j6wS0WtRmsKI20YK80AKC created_at: !ruby/object:DateTime 2016-09-12 11:59:48.982000000 Z updated_at: !ruby/object:DateTime 2019-02-12 00:46:14.971000000 Z content_type_id: image revision: 3 image: sys: id: 6J08sWPtfOs88AmM20u02u created_at: !ruby/object:DateTime 2016-09-12 12:00:29.957000000 Z updated_at: !ruby/object:DateTime 2016-09-12 12:00:29.957000000 Z title: ZIMMSL0220013 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6J08sWPtfOs88AmM20u02u/a3611f2b43b406427bd87003e5341612/ZIMMSL0220013.jpg" caption: Sable antelope, crocodile or lizard and human figure. Mashonaland, Zimbabwe. 2013,2034.23028 ©TARA/<NAME> col_link: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3775685&partId=1&searchText=2013,2034.23028&page=1 citations: - sys: id: MXZ2L6VLmU2KqsWqcqO2u created_at: !ruby/object:DateTime 2016-09-12 11:54:06.696000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:54:06.696000000 Z content_type_id: citation revision: 1 citation_line: "<NAME>. (1995): The hunter's vision: the prehistoric art of Zimbabwe. British Museum Press, London.\n\n<NAME>. (1987): The painted caves: an introduction to the prehistoric art of Zimbabwe. Modus Publications, Harare. \n\n<NAME>. & <NAME> (1959): Prehistoric rock art of the Federation of Rhodesia & Nyasaland. National Publications Trust, Rhodesia and Nyasaland, Salisbury [Harare].\n\nWalker, N. (2012): The Rock Art of the Matobo Hills, Zimbabwe. Adoranten: 38-59\n" background_images: - sys: id: Jy8edAwMCGiAywQIyi0KI created_at: !ruby/object:DateTime 2016-09-12 11:56:31.534000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:56:31.534000000 Z title: ZIMMTB0100001 description: url: "//images.ctfassets.net/xt8ne4gbbocd/Jy8edAwMCGiAywQIyi0KI/4d9692d057fadcc525259a3eb75c00ba/ZIMMTB0100001.jpg" - sys: id: 4UQayqgP9SoOGMKAwEqcq8 created_at: !ruby/object:DateTime 2015-12-08 13:38:10.784000000 Z updated_at: !ruby/object:DateTime 2015-12-08 13:38:10.784000000 Z title: ZIMMSL0020009 description: url: "//images.ctfassets.net/xt8ne4gbbocd/4UQayqgP9SoOGMKAwEqcq8/0ab1b26bc1803c68c7a29aed52b523ad/ZIMMSL0020009.jpg" - sys: id: 4q3Wj7sKA8akoCm4UMYywG created_at: !ruby/object:DateTime 2016-09-12 11:54:51.814000000 Z updated_at: !ruby/object:DateTime 2019-02-12 00:59:30.879000000 Z title: ZIMMSL0040003 description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3775248&partId=1&searchText=ZIMMSL0040003&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/4q3Wj7sKA8akoCm4UMYywG/c038814e5c673d11968394b1aec7070c/ZIMMSL0040003.jpg" region: Southern Africa ---<file_sep>/_coll_country/angola/tchitundu-hulu.md --- breadcrumbs: - label: Countries url: "../../" - label: Angola url: "../" layout: featured_site contentful: sys: id: 4COYtGhxoAuK82cGysc2cu created_at: !ruby/object:DateTime 2016-07-27 07:45:12.121000000 Z updated_at: !ruby/object:DateTime 2017-11-29 19:47:47.835000000 Z content_type_id: featured_site revision: 3 title: Tchitundu-Hulu slug: tchitundu-hulu chapters: - sys: id: 26QSCtJ2726k0U4WG4uCS2 created_at: !ruby/object:DateTime 2016-07-27 07:45:13.927000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:45:13.927000000 Z content_type_id: chapter revision: 1 title_internal: 'Angola: featured site, chapter 1' body: 'Tchitundu-Hulu is the generic name for a group of four rock art sites located in the Namibe province on the south-west corner of Angola, by the edge of the Namib desert, about 120 km from the sea. It is a semi-arid plain characterized by the presence of several inselbergs (isolated hills rising from the plain), the most important of which is Tchitundu-Hulu Mulume. The group of rock art sites are surrounded by several seasonal rivers, within a maximum distance of 1 km. Tchitundu-Hulu was first documented by <NAME> in 1953, and since then it has become one of the most studied rock art sites in Angola, attracting the interest of renowned researchers such as <NAME>, J. <NAME> and Santos Junior. In 2014 one of the sites was the subject of a Masters dissertation (Caema 2014), the latest addition to the long term research on the site. ' - sys: id: 4gU0r5PSy4CC8Q00ccMMuY created_at: !ruby/object:DateTime 2016-07-27 07:45:15.741000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:45:15.741000000 Z content_type_id: image revision: 1 image: sys: id: 7MqUsgyUhi8IIoM8sGKKAO created_at: !ruby/object:DateTime 2016-07-27 07:46:36.210000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:36.210000000 Z title: ANGTCH0010003 description: url: "//images.ctfassets.net/xt8ne4gbbocd/7MqUsgyUhi8IIoM8sGKKAO/01aa753abbbd4fa8224263f644d78b1c/ANGTCH0010003.jpg" caption: "landscape showing an inselberg in the background. Tchitundu-Hulu, Angola. 2013,2034.21206 © TARA/<NAME> \t" col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3744327&partId=1 - sys: id: 3PYi7QceDKQa44gamOE0o4 created_at: !ruby/object:DateTime 2016-07-27 07:45:13.877000000 Z updated_at: !ruby/object:DateTime 2018-05-09 16:30:01.864000000 Z content_type_id: chapter revision: 2 title_internal: 'Angola: featured site, chapter 2' body: 'As forementioned, Tchitundu-Hulu comprises four rock art sites: Tchitundu-Hulu Mulume, Tchitundu-Hulu Mucai, Pedra das Zebras and Pedra da Lagoa. The first two combine paintings and engravings, while the latter only have engravings. Pedra das Zebras and Pedra da Lagoa are Portuguese names which can be translated as the Rock of the Zebras and the Rock of the Pond, but the name of Tchitundu-Hulu has different interpretations in the local languages –the hill of heaven, the hill of the souls or the sacred hill- while Mulume and Mucai are translated as man and woman, respectively. Therefore, the local names of the site point to a deep meaning within the communities that inhabited the region. ' - sys: id: fm44bXnRYc0OiwS4Ywogw created_at: !ruby/object:DateTime 2016-07-27 07:45:13.865000000 Z updated_at: !ruby/object:DateTime 2018-05-09 16:30:34.170000000 Z content_type_id: chapter revision: 2 title_internal: 'Angola: featured site, chapter 3' body: 'Of the four sites, Tchitundu-Hulu Mulume is the largest , located at the top of the inselberg, 726m in height. The slopes of the outcrop are covered by large engravings, most of them consisting of circle-like shapes (simple or concentric circles, solar-like images), although some depictions of human figures or animals are also present. In a shelter on the top of the outcrop more than 180 images can be found painted in red or white, with geometric shapes being again widely predominant. The depictions have abundant superimpositions and cover the walls, roof and base of the shelter. ' - sys: id: 35UGg2OapGC2qG4O4Eo2I0 created_at: !ruby/object:DateTime 2016-07-27 07:45:15.726000000 Z updated_at: !ruby/object:DateTime 2018-05-09 16:42:06.863000000 Z content_type_id: image revision: 2 image: sys: id: 2KFJl6V2WsekUsMaq8M4Ga created_at: !ruby/object:DateTime 2016-07-27 07:46:36.151000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:36.151000000 Z title: ANGTCH0010019 description: url: "//images.ctfassets.net/xt8ne4gbbocd/2KFJl6V2WsekUsMaq8M4Ga/8fd5bad6be6601f1a589674820b0770d/ANGTCH0010019.jpg" caption: Pecked concentric lines. Tchitundu-Hulu Mulume, Angola. 2013,2034.21222 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3744352&partId=1 - sys: id: 4RvVnpbsXK0YcYSUUYyw68 created_at: !ruby/object:DateTime 2016-07-27 07:45:13.862000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:45:13.862000000 Z content_type_id: chapter revision: 1 title_internal: 'Angola: featured site, chapter 4' body: 'In comparison, Tchitundu-Hulu Mucai is situated on the plain around 1,000 m from the inselberg, in a rock outcrop containing engravings on the top and a shelter at its base covered by painted rock art. The characteristics of both engravings and paintings are similar to those of Tchitundu-Hulu Mulume, although some black figures are present, too. Paintings often combine two, three or even more colours, and consist mainly of geometric signs, although there are anthropomorphs and zoomorphs, in some cases grouped in what seem hunting scenes. The other two sites (the Rock of the Zebras and the Rock of the Pond) consist of engravings similar to those of Tchitundu-Hulu Mulume, and in some cases their different patinas show that they were made in different periods. ' - sys: id: iZUL3BpxqEII82IQGGGGC created_at: !ruby/object:DateTime 2016-07-27 07:45:14.951000000 Z updated_at: !ruby/object:DateTime 2018-05-09 16:42:37.270000000 Z content_type_id: image revision: 2 image: sys: id: 1HfdgOK6lC4aCke6we2UGW created_at: !ruby/object:DateTime 2016-07-27 07:46:36.033000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:36.033000000 Z title: ANGTCH0010005 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1HfdgOK6lC4aCke6we2UGW/308f6b611eeec141c864e431073bf615/ANGTCH0010005.jpg" caption: Paintings at Tchitundu-Hulu Mulume, Angola. 2013,2034.21208 © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3744324&partId=1 - sys: id: 5ngD52eGekKEMI2UMeGUWs created_at: !ruby/object:DateTime 2016-07-27 07:45:13.771000000 Z updated_at: !ruby/object:DateTime 2016-07-27 09:29:43.491000000 Z content_type_id: chapter revision: 2 title: '' title_internal: 'Angola: featured site, chapter 5' body: 'The chronology of the Tchitundu-Hulu rock art is difficult to establish, and it is unclear if the four sites are of the same period at all. Theories based on the lithic tools dispersed throughout the area ascribed the paintings to an ancient time period, possibly tens of thousands of years old. Radiocarbon samples coming from the excavation of Tchitundu-Hulu Mulume showed a date in the early 1st millennium BC, although the relation of the archaeological remains and the paintings has not been proved and archaeological materials of a more modern period were also located. A sample taken from the pigments at the site rendered a date of the beginning of the first centuries of the 1st millennium AD. In any case, Tchitundu-Hulu hosts some of the oldest examples of rock art in the country, and it has been linked to the schematic traditions that characterize the rock art of Central Africa, more abundant in central Mozambique and Malawi. ' - sys: id: 6MjjzjwufSQ6QqMqwweiaE created_at: !ruby/object:DateTime 2016-07-27 07:45:14.829000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:45:14.829000000 Z content_type_id: image revision: 1 image: sys: id: 6u3Ewi14cgUU28MWOQ0WMI created_at: !ruby/object:DateTime 2016-07-27 07:46:36.182000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:36.182000000 Z title: ANGTCH0010011 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6u3Ewi14cgUU28MWOQ0WMI/6b84b50d8dd0daaefff6ac33cf7799a3/ANGTCH0010011.jpg" caption: Red and white oval-like figure (bird?). 2013,2034.21214 © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3744318&partId=1 - sys: id: 4pyURXLHpYAWm8m882EKqw created_at: !ruby/object:DateTime 2016-07-27 07:45:13.737000000 Z updated_at: !ruby/object:DateTime 2016-07-27 09:30:49.386000000 Z content_type_id: chapter revision: 2 title: '' title_internal: 'Angola: featured site, chapter 6' body: The question of who made the engravings or paintings is another complex issue for the interpretation of the Tchitundu-Hulu depictions. The harsh conditions of this semi-desert area probably favoured a seasonal occupation of the region during the rainy season. The location of Tchitundu-Hulu at the edge of the desert could also have made this place a strategic site for the communities living in the region. Several local groups - Kwisi, Kuvale - have traditionally inhabited the area, but the authorship of these engravings and paintings and the motives for creating them remains obscure, as does the purpose and cultural context of the complex images of Tchitundu-Hulu. citations: - sys: id: txWp29xSGOSkuqgOYgeSi created_at: !ruby/object:DateTime 2016-07-27 07:45:30.621000000 Z updated_at: !ruby/object:DateTime 2016-07-27 09:59:36.553000000 Z content_type_id: citation revision: 3 citation_line: "<NAME>, <NAME>. (2014): 'As pinturas do abrigo do Tchitundu-Hulu Mucai. Um contributo para o conhecimento da arte rupestre da região.' Unpublished Masters dissertation \nInstituto Politécnico de Tomar – Universidade de Trás-os-Montes e Alto Douro. Available at <http://comum.rcaap.pt/handle/10400.26/8309>\n" background_images: - sys: id: 60WuYok9POoqaG2QuksOWI created_at: !ruby/object:DateTime 2016-07-27 07:46:34.096000000 Z updated_at: !ruby/object:DateTime 2019-02-12 02:16:12.785000000 Z title: '2013,2034.21210' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3744322&partId=1&searchText=ANGTCH0010007&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/60WuYok9POoqaG2QuksOWI/0786f5b209c940eb57e2fa98b10f6cfb/ANGTCH0010007.jpg" - sys: id: 40lIKwvi8gwo4ckmuKguYk created_at: !ruby/object:DateTime 2016-07-27 07:47:54.905000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:47:54.905000000 Z title: ANGTCH0010022` description: url: "//images.ctfassets.net/xt8ne4gbbocd/40lIKwvi8gwo4ckmuKguYk/074e930f8099bbfdf9dd872f874c3a32/ANGTCH0010022.jpg" ---<file_sep>/Rakefile # frozen_string_literal: true require 'colorize' require 'html-proofer' require 'mkmf' require 'open-uri' require 'rubocop/rake_task' require 'yaml' CONTENTFUL_LABELS = { '2MFOT4WINOAOokOw2ma6aS': 'featured_site', '3NZwbeG360yGuoKUUCU8Oy': 'image', '4WLq0TTLleEcMmEYw66Q8w': 'thematic', '4avEHZ2i4EkkmWQGg6Cc0c': 'embeded_media', '4fXS1cA1XGKq4a6IM86Wm': 'country_key_facts', '5BpsmbwGhUi8wYwIEKO0Oa': 'introduction', '76etbn9kNUiAY0q6YYu0SY': 'project_page', '7Ak9U6HXygSaUMmQQWIGQu': 'chapter', '7Kul7fgXh6YSseagSee8co': 'regional_introduction', '7bbOALHvAQ8cQ6yS2wOmw0': 'citation', 'Q4XNev9Iom0uGquue2eoS': 'country_information', 'fS8J0UehVuo8YuO2AswYS': 'country' }.freeze CONTENTFUL_IGNORED_CONTENT_TYPES = %w[ chapter citation country_key_facts embeded_media featured_site image project_page ].freeze IMAGES_PATH = 'assets/images/site' # ----------------------------------------------------------------------------- # Default task # ----------------------------------------------------------------------------- task default: %w[test] # ----------------------------------------------------------------------------- # Rubocop tasks # ----------------------------------------------------------------------------- RuboCop::RakeTask.new # ----------------------------------------------------------------------------- # Jekyll tasks # ----------------------------------------------------------------------------- # Usage: rake serve, rake serve:prod task serve: ['serve:dev'] namespace :serve do desc 'Serve development Jekyll site locally' task :dev do puts 'Starting up development Jekyll site server...'.yellow ENV['JEKYLL_ENV'] = 'development' system 'bundle exec jekyll serve --config _config.yml,_config.local.yml' end desc 'Serve production Jekyll site locally' task :prod do puts 'Starting up production Jekyll site server...'.yellow ENV['JEKYLL_ENV'] = 'production' system 'bundle exec jekyll serve --no-watch' end end # Usage: rake build, rake build:prod task build: ['build:dev'] namespace :build do desc 'Regenerate files for development' task :dev do puts 'Regenerating files for development...'.yellow ENV['JEKYLL_ENV'] = 'development' system 'bundle exec jekyll build '\ '--trace --config _config.yml,_config.local.yml --profile' end desc 'Regenerate files for production' task :prod do puts 'Regenerating files for production...'.yellow ENV['JEKYLL_ENV'] = 'production' system 'bundle exec jekyll build --trace' end end # Usage: rake test, rake test:prod task test: ['test:all'] namespace :test do options = { allow_hash_href: true, cache: { timeframe: '30d' }, assume_extension: true, disable_external: true, internal_domains: ['kingsdigitallab.github.io'], empty_alt_ignore: true, url_swap: { %r{/african-rock-art/?} => '/' } } desc 'Test development and production sites' task :all do puts 'Testing development and production sites'.yellow Rake::Task['test:dev'].invoke puts '---'.yellow Rake::Task['test:prod'].invoke end desc 'Test development site' task :dev do puts 'Validating development HTML output in _site...'.yellow Rake::Task['build:dev'].invoke HTMLProofer.check_directory('./_site', options).run end desc 'Test production site' task :prod do puts 'Validating production HTML output in _site...'.yellow Rake::Task['build:prod'].invoke HTMLProofer.check_directory('./_site', options).run end end # ----------------------------------------------------------------------------- # Contentful tasks # ----------------------------------------------------------------------------- # Usage: rake contentful, rake contentful:import, rake:process task contentful: ['contentful:all'] namespace :contentful do desc 'Import and process data from Contentful' task :all do puts 'Contentful data import and processing...'.yellow Rake::Task['contentful:import'].invoke puts '---'.yellow Rake::Task['contentful:process'].invoke puts '---'.yellow Rake::Task['contentful:assets'].invoke puts '---'.yellow Rake::Task['contentful:resize'].invoke end desc 'Import data from Contentful' task :import do puts 'Contentful data import...'.yellow system '. ./env.sh && bundle exec jekyll contentful' end desc 'Process imported data: '\ 're-maps Contentful content types and creates content pages' task :process do puts 'Contentful data processing...'.yellow yaml_path = File.join(Dir.pwd, '_data/ara.yaml') yaml_data = File.read(yaml_path) # some terms are encoded in the content using | which should not be # converted into HTML tables, so they need to be escaped yaml_data = yaml_data.gsub(/(\w*)\|([a-zA-Z]\w+)/, '\1&#124;\2') CONTENTFUL_LABELS.each do |key, value| yaml_data = yaml_data.gsub(Regexp.quote(key), value) end File.open(yaml_path, 'w') do |f| f.write(yaml_data) f.close end yaml = YAML.load_file(yaml_path) yaml.each do |key, value| unless CONTENTFUL_IGNORED_CONTENT_TYPES.include?(key) create_content_pages(key, value) end end end desc 'Import assets from Contentful; '\ 'by default it only downloads new images, '\ 'to overwrite existing images do `rake contentful:assets[true]`' task :assets, [:force] do |_t, args| args.with_defaults(force: false) force = args[:force] puts 'Contentful assets import...'.yellow Dir.mkdir(IMAGES_PATH) unless File.exist?(IMAGES_PATH) Rake::Task['contentful:process'].invoke yaml_path = File.join(Dir.pwd, '_data/ara.yaml') yaml = YAML.load_file(yaml_path) yaml.each do |key, value| case key when 'image' value.each do |item| download_image(item['image'], force) if item['image'] end when 'country' value.each do |country| next unless country['image_carousel'] || country['background_images'] images = [] images += country['image_carousel'] if country['image_carousel'] images += country['background_images'] if country['background_images'] images.each do |image| download_image(image, force) end end when 'thematic' value.each do |theme| next unless theme['lead_image'] || theme['background_images'] images = [] images += [theme['lead_image']] if theme['lead_image'] images += theme['background_images'] if theme['background_images'] images.each do |image| download_image(image, force) end end end end end desc 'Resizes the images imported from Contentful to a maximum of 500k' task :resize do puts 'Resizing images...'.yellow low_quality_path = "#{IMAGES_PATH}/low" Dir.mkdir(low_quality_path) unless File.exist?(low_quality_path) if find_executable('mogrify') %w[jpg].each do |ext| puts "Resizing #{ext}s...".yellow system "mogrify -resize 540x560 -quality 100 \ -define jpeg:extent=500kb #{IMAGES_PATH}/*.#{ext}" system "mogrify -path #{low_quality_path} \ -quality 10 #{IMAGES_PATH}/*.#{ext}" %w[140x140 300x180].each do |size| puts "Creating #{size} surrogates...".green size_path = "#{IMAGES_PATH}/#{size}" Dir.mkdir(size_path) unless File.exist?(size_path) low_quality_path = "#{size_path}/low" Dir.mkdir(low_quality_path) unless File.exist?(low_quality_path) system "mogrify -path #{size_path} -resize #{size}^ \ -gravity center -extent #{size} #{IMAGES_PATH}/*.#{ext}" system "mogrify -path #{low_quality_path} \ -quality 10 #{size_path}/*.#{ext}" end end system "rm -f #{IMAGES_PATH}/*.*~" else puts 'Imagemagick not found'.red end end end # ----------------------------------------------------------------------------- # Gallery tasks # ----------------------------------------------------------------------------- desc 'Creates surrogates for the gallery images' task :gallery do puts 'Processing gallery images...'.yellow gallery_images_path = 'assets/images/gallery' low_quality_path = "#{gallery_images_path}/low" Dir.mkdir(low_quality_path) unless File.exist?(low_quality_path) if find_executable('mogrify') %w[jpg].each do |ext| puts "Resizing #{ext}s...".yellow system "mogrify -resize 540x560 -quality 100 \ -define jpeg:extent=500kb #{gallery_images_path}/*.#{ext}" system "mogrify -path #{low_quality_path} \ -quality 10 #{gallery_images_path}/*.#{ext}" %w[140x140 196x196].each do |size| puts "Creating #{size} surrogates...".green size_path = "#{gallery_images_path}/#{size}" Dir.mkdir(size_path) unless File.exist?(size_path) low_quality_path = "#{size_path}/low" Dir.mkdir(low_quality_path) unless File.exist?(low_quality_path) system "mogrify -path #{size_path} \ -resize #{size} -background white -gravity center -extent #{size} \ #{gallery_images_path}/*.#{ext}" system "mogrify -path #{low_quality_path} \ -quality 10 #{size_path}/*.#{ext}" end end system "rm -f #{gallery_images_path}/*.*~" else puts 'Imagemagick not found'.red end end def create_content_pages(key, data) # Creates content specific directory (collection) dir_name = '_coll_' + key dir_path = File.join(Dir.pwd, dir_name) Dir.mkdir(dir_path) unless File.exist?(dir_path) # Creates one content file per item data.each do |item| item_hash = { 'contentful' => item } slug = item['sys']['id'] %w[slug title name].each do |field| next unless item.include?(field) && !item[field].empty? slug = slugify(item[field]) break end file_path = File.join(dir_path, slug + '.md') File.open(file_path, 'w') do |f| f.write(YAML.dump(item_hash)) f.write('---') end next unless item.include?('featured_site') create_featured_site(dir_name, slug, item) end end def slugify(str) str.strip.downcase.gsub(/\W+/, '-') end def create_featured_site(country_dir_name, country_slug, data) featured_dir_name = country_dir_name + '/' + country_slug featured_dir_path = File.join(Dir.pwd, featured_dir_name) Dir.mkdir(featured_dir_path) unless File.exist?(featured_dir_path) featured_slug = data['featured_site']['slug'] featured_item_hash = { 'breadcrumbs' => [ { 'label' => 'Countries', 'url' => '../../' }, { 'label' => data['name'], 'url' => '../' } ], 'layout' => 'featured_site', 'contentful' => data['featured_site'] } featured_file_path = File.join(featured_dir_path, featured_slug + '.md') File.open(featured_file_path, 'w') do |f| f.write(YAML.dump(featured_item_hash)) f.write('---') end end def download_image(image, force) return unless image['url'] url = "https:#{image['url']}?fm=jpg&fl=progressive&w=540&h=560" filename = url.split('/')[-1].split('?')[0] filename = File.basename(filename, File.extname(filename)) filename = "#{IMAGES_PATH}/#{filename}.jpg" return unless force || !File.file?(filename) puts "Downloading #{url}:".green puts " into #{filename}".blue download = open(url) IO.copy_stream(download, filename) end <file_sep>/_layouts/country.html --- layout: default --- <article class="country"> {% assign self = page.contentful %} {% assign chapters = self.country_introduction.chapters %} {% assign introduction = chapters[0] %} {% assign introduction_image = chapters | where: "sys.content_type_id", "image" | first %} <header class="container"> <h1 class="page-heading">{{ self.name | escape }}</h1> </header> <div class="container featured-chapter"> <div class="column-five-twelveth"> <p>{{ introduction.body | markdownify }}</p> {% if self.featured_site %} <a class="button orange more" href="{{ self.featured_site.slug }}/">View featured rock art site</a> {% endif %} </div> <div class="column-seven-twelveth"> {% include image.html image=introduction_image.image caption=introduction_image.caption link=introduction_image.col_link class="full-width" %} </div> </div> <div class="container"> <div class="column-one-third"> <h2 class="baskerville">Highlight images</h2> </div> <div class="column-one-third"> <p class="heading-sibling"> {% if self.slug == 'nigeria' %} <a href="images/">Explore rock art</a> {% else %} <a href="{{ self.col_url }}" target="_blank">Explore rock art</a> {% endif %} </p> </div> </div> <div class="container"> {% for image in self.image_carousel limit:3 %} <div class="column-one-third"> <div class="card"> <div class="five-three"> <div class="card-image"> <a href=""> {% include image.html image=image %} </a> </div> </div> {% if image.description %} <div class="card-content"> <a href="{{ image.description }}" class="more">Read more about this image</a> </div> {% endif %} </div> </div> {% endfor %} </div> <div class="container chapter"> <div class="column-three-quarters"> <h2 class="chapter-title">Country overview</h2> {% for field in self.key_facts offset: 2 %} <h3>{{ field[0] | split: "_" | join: " " | capitalize }}</h3> <p>{{ field[1] }}</p> {% endfor %} </div> </div> <div class="container chapter accordion"> <div class="column-three-quarters"> {% include chapters.html chapters=chapters %} </div> </div> {% if self.thematic_articles %} <div class="container"> <h2>Related content</h2> {% for related in self.thematic_articles limit:3 %} <div class="column-one-third"> <div class="card"> {% assign url = "/thematic/" | append: related.slug | append: "/" | relative_url %} <div class="five-three"> <div class="card-image"> <a href="{{ url }}"> {% include image.html image=related.lead_image %} </a> </div> </div> <div class="card-content"> <h3><a href="{{ url }}">{{ related.title }}</a></h3> <a href="{{ url }}" class="more hr">Find out more</a> </div> </div> </div> {% endfor %} </div> {% endif %} </article> <file_sep>/_coll_thematic/country-of-standing-stones.md --- contentful: sys: id: 2KyCxSpMowae0oksYsmawq created_at: !ruby/object:DateTime 2015-11-25 18:32:33.269000000 Z updated_at: !ruby/object:DateTime 2019-02-21 14:57:42.412000000 Z content_type_id: thematic revision: 5 title: 'The Country of the Standing Stones: Stela in Southern Ethiopia' slug: country-of-standing-stones lead_image: sys: id: 5N30tsfHVuW0AmIgeQo8Kk created_at: !ruby/object:DateTime 2015-11-25 18:01:40.103000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:01:40.103000000 Z title: ETHTBU0050002 description: url: "//images.ctfassets.net/xt8ne4gbbocd/5N30tsfHVuW0AmIgeQo8Kk/ad2ce21e5a6a89a0d4ea07bee897b525/ETHTBU0050002.jpg" chapters: - sys: id: 7lbvgOvsBO0sgeSkwU68K8 created_at: !ruby/object:DateTime 2015-11-25 18:28:36.149000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:48:54.764000000 Z content_type_id: chapter revision: 2 title_internal: 'Stela: thematic, chapter 1' body: Ethiopia is home to some of the most impressive archaeological remains in Africa, such as the rock-hewn churches of Lalibela, the Axumite kingdom monoliths or the Gondar palaces. Most of these sites are located in northern Ethiopia, but to the south of the country there are also some remarkable archaeological remains, less well-known but which deserve attention. One of them is the dozens of graveyards located along the Rift Valley and marked by hundreds of stone stelae of different types, usually decorated. Ethiopia holds the biggest concentration of steale in all Africa, a testimony of the complexity of the societies which inhabited the Horn of Africa at the beginning of the second millennium AD. - sys: id: 3q8L69s3O8YOWsS4MAI0gk created_at: !ruby/object:DateTime 2015-11-25 18:03:36.680000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:51:45.367000000 Z content_type_id: image revision: 2 image: sys: id: 3lhKPWDnSwEIKmoGaySEIy created_at: !ruby/object:DateTime 2015-11-25 18:02:34.448000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:02:34.448000000 Z title: ETHTBU0090003 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3lhKPWDnSwEIKmoGaySEIy/a330ae393d066149e80155b81694f6d3/ETHTBU0090003.jpg" caption: Engraved stela from Silté (now in the Addis Ababa National Museum), probably of a historic period, completely covered by symbols and human figures. 2013,2034.16388 ©TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3704087&partId=1&searchText=2013,2034.16388&view=list&page=1 - sys: id: wMW6zfth1mIgEiSqIy04S created_at: !ruby/object:DateTime 2015-11-25 18:28:55.931000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:52:16.164000000 Z content_type_id: chapter revision: 2 title_internal: 'Stela: thematic, chapter 2' body: Although some of the most impressive stelae are located to the north-east of Ethiopia, in the region where the Axumite Kingdom flourished between the 1st and the 10th centuries AD, the area with the highest concentration of stelae is to the south-west of the country, from the Manz region to the north of Addis Ababa to the border with Kenya. It is an extensive area which approximately follows the Rift Valley and the series of lakes that occupy its floor, and which roughly covers the Soddo, Wolayta and Sidamo regions. The region has a tropical climate and is fertile, with warm conditions being predominant and rainfall being quite abundant, with annual rates of 1200-1500 mm in the lower areas while in the highlands the rainfall reaches 2.000 mm per year. - sys: id: 5BGRogcCPeYgq2SY62eyUk created_at: !ruby/object:DateTime 2015-11-25 18:24:59.375000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:53:36.787000000 Z content_type_id: image revision: 2 image: sys: id: 3HHuQorm12WGUu0kC0Uce created_at: !ruby/object:DateTime 2015-11-25 18:02:09.630000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:02:09.630000000 Z title: ETHTBU0080002 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3HHuQorm12WGUu0kC0Uce/cf9d160fced55a45a8cb0cc9db8cbd54/ETHTBU0080002.jpg" caption: Two stelae on which are carved human figures. The faces have carved stripes, sometimes interpreted as masks. Ambet, Soddo. 2013,2034.16385 ©TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3704090&partId=1&searchText=2013,2034.16385&view=list&page=1 - sys: id: 3CBiLCh7ziUkMC264I4oSw created_at: !ruby/object:DateTime 2015-11-25 18:29:16.601000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:58:41.825000000 Z content_type_id: chapter revision: 2 title_internal: 'Stela: thematic, chapter 3' body: 'Ethiopian stelae have been known to western scholars since the end of the 19th century, with the first examples documented in 1885 to the north of Addis Ababa and the news about the main group to the south arriving in 1905. The first archaeological works in the southern area took place in the 1920’s carried out by French and German researchers. The work of <NAME>ïs was especially remarkable, with four expeditions undertaken between 1922 and 1926 which were partially published in 1931. Along with Azaïs, a German team from the Frobénius Institute started to study the site of Tuto Fela, a huge cemetery with hundreds of phallic and anthropomorphic stelae located in the Sidamo region. Since these early studies the archaeological remains were left unattended until the 1970’s, when Francis Anfray excavated the site of Gattira-Demma and organized a far more systematic survey in the area which documented dozens of stelae of different sizes and types. In the 1980’s, another French team started to study first Tiya and then Tuto Fela and another important site, Chelba-Tutitti, in a long-term project which has been going on for thirty years and has been paramount to understand the types, chronologies and distribution of these archaeological remains. The historical importance of these stelae was universally recognized in 1980, when Tiya was listed as a UNESCO World Heritage Site. ' - sys: id: 3OqDncSoogykaUgAyW0Mei created_at: !ruby/object:DateTime 2015-11-25 18:25:18.604000000 Z updated_at: !ruby/object:DateTime 2018-05-15 16:00:14.418000000 Z content_type_id: image revision: 2 image: sys: id: 5Zt1z4iJ44c2MWmWcGy4Ey created_at: !ruby/object:DateTime 2015-11-25 18:01:40.088000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:01:40.088000000 Z title: ETHSID0010002 description: url: "//images.ctfassets.net/xt8ne4gbbocd/5Zt1z4iJ44c2MWmWcGy4Ey/7a08db34b4eba7530b9efb69f42fec36/ETHSID0010002.jpg" caption: View of the Tuto Fela site, showing some of the stelae standing over the burials. The stelae are anthropomorphic, corresponding to the second phase of the cemetery. 2013,2034.16196 ©TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3703783&partId=1&searchText=2013,2034.16196&view=list&page=1 - sys: id: 5NnJiqSSNGkOuooYIEYIWO created_at: !ruby/object:DateTime 2015-11-25 18:25:38.253000000 Z updated_at: !ruby/object:DateTime 2018-05-15 16:01:28.688000000 Z content_type_id: image revision: 2 image: sys: id: 5N30tsfHVuW0AmIgeQo8Kk created_at: !ruby/object:DateTime 2015-11-25 18:01:40.103000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:01:40.103000000 Z title: ETHTBU0050002 description: url: "//images.ctfassets.net/xt8ne4gbbocd/5N30tsfHVuW0AmIgeQo8Kk/ad2ce21e5a6a89a0d4ea07bee897b525/ETHTBU0050002.jpg" caption: Back of the Tiya stelae, showing the graves attached to them. 2013,2034.16345 ©TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3704130&partId=1&searchText=2013,2034.16345&view=list&page=1 - sys: id: 66kOG829XiiESyKSYUcOkI created_at: !ruby/object:DateTime 2015-11-25 18:29:40.626000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:29:40.626000000 Z content_type_id: chapter revision: 1 title_internal: 'Stela: thematic, chapter 4' body: 'The Ethiopian stelae show a great variability in shapes and decorations, but at least three main groups could be defined. The first corresponds to the so-called phallic stelae, long cylindrical stones with a hemispherical top delimited by a groove or ring (Jossaume 2012: 97). The body of the stela is sometimes decorated with simple geometric patterns. A second type is known as anthropomorphic, with the top of the piece carved to represent a face and the rest of the piece decorated with crossed patterns. These two types are common to the east of the Rift Valley lakes, while to the south of Addis Ababa and to the west of these lakes several other types are present, most of them representing anthropomorphs but sometimes plain instead of cylindrical. These figures are usually classified depending on the shape and especially the features engraved on them –masks, pendants, swords- with the most lavishly carved considered the most recent. Probably the best known group is that with swords represented, such as those of Tiya, characterized by plain stones in which groups of swords (up to nineteen) are depicted along with dots and other unidentified symbols. Not all the stelae have these weapons, although those that don’t are otherwise identical in shape and have other common signs engraved on them. Regarding their chronology the Ethiopian stela seem to be relatively new, dated from the 10th to the 13th centuries, sometimes with one type of stela superimposed on another and in other cases with old types being reused in later tombs.' - sys: id: 66jbDvBWhykGwIOOmaYesY created_at: !ruby/object:DateTime 2015-11-25 18:26:18.279000000 Z updated_at: !ruby/object:DateTime 2018-05-15 16:04:13.365000000 Z content_type_id: image revision: 4 image: sys: id: 5Bpxor1k1GMmUOoEWWqK2k created_at: !ruby/object:DateTime 2015-11-25 18:02:34.437000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:02:34.437000000 Z title: ETHSOD0050002 description: url: "//images.ctfassets.net/xt8ne4gbbocd/5Bpxor1k1GMmUOoEWWqK2k/a6ec0e80da1e2b1c7cecdf2ee7951b9e/ETHSOD0050002.jpg" caption: Example of a phallic cylindrical stela, Gido Wamba, Ethiopia. 2013,2034.16290 ©TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3703913&partId=1&searchText=2013,2034.16290&&page=1 - sys: id: 3gftSkoIHSsmeCU6M8EkcE created_at: !ruby/object:DateTime 2015-11-25 18:27:02.886000000 Z updated_at: !ruby/object:DateTime 2018-05-15 16:06:02.999000000 Z content_type_id: image revision: 2 image: sys: id: 6WDEsfzmqQGkyyGImgYmcU created_at: !ruby/object:DateTime 2015-11-25 18:02:24.547000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:02:24.547000000 Z title: ETHTBU0050025 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6WDEsfzmqQGkyyGImgYmcU/5055128d6e0e0b51216e0daeb59c6728/ETHTBU0050025.jpg" caption: Examples of a plain stela with swords at Tiya, Ethiopia. 2013,2034.16365 ©TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3704110&partId=1&searchText=2013,2034.16365&page=1 - sys: id: 41cBMB2SpOEqy0m66k64Gc created_at: !ruby/object:DateTime 2015-11-25 18:29:58.521000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:29:58.521000000 Z content_type_id: chapter revision: 1 title_internal: 'Stela: thematic, chapter 5' body: 'Regardless of their chronology and shape, most of the stela seem to have a funerary function, marking the tombs of deceased which were buried in cemeteries sometimes reaching hundreds of graves. The information collected from sites of such as Tuto Fela show that not all the burials had an attached stela, and considering the amount of work necessary to prepare them those which had could be interpreted as belonging to high status people. In some cases, such as in Tiya, it seems evident that the stela marked the graves of important personalities within their communities. It is difficult to determine who the groups that carved these stelae were, but given their chronology it seems that they could have been Cushitic or Nilotic-speaking pastoralist communities absorbed by the Oromo expansion that took place in the sixteenth century. A lot of research has still to be done about these graveyards and their associated living spaces, and undoubtedly many groups of stelae are yet to be discovered. Those studied show, however, the potential interest of ancient communities still poorly known but which were able to develop complex societies and these material expressions of authority and power. ' - sys: id: 5DJsnYIbRKiAiOqYMWICau created_at: !ruby/object:DateTime 2015-11-25 18:27:29.739000000 Z updated_at: !ruby/object:DateTime 2018-05-15 16:07:15.282000000 Z content_type_id: image revision: 2 image: sys: id: 5zepzVfNDiOQy8gOyAkGig created_at: !ruby/object:DateTime 2015-11-25 18:02:34.369000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:02:34.369000000 Z title: ETHTBU0010003 description: url: "//images.ctfassets.net/xt8ne4gbbocd/5zepzVfNDiOQy8gOyAkGig/3131691f0940b7f5c823ec406b1acd03/ETHTBU0010003.jpg" caption: Stela graveyard in Meskem. 2013,2034.16330 ©TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3704143&partId=1&searchText=2013,2034.16330&page=1 citations: - sys: id: 6LBJQl0eT62A06YmiSqc4W created_at: !ruby/object:DateTime 2015-11-25 18:28:00.511000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:28:00.511000000 Z content_type_id: citation revision: 1 citation_line: | <NAME> (dir.) (1995): *Tiya, l'Éthiopie des Mégalithes, du Biface a l'Art Rupestre dans la Corne d'Afrique*. Paris, UNESCO/CNS. <NAME>. (2007): Tuto Fela et les stèles du sud de l'Ethiopie. Paris, Éditions recherche sur les civilisations. <NAME>. (2012): The Superimposed Cemeteries of Tuto Fela in Gedeo Country (Ethiopia), and Thoughts on the Site of Chelba-Tutitti. *Palethnology*, 4, 87-110. background_images: - sys: id: 3HHuQorm12WGUu0kC0Uce created_at: !ruby/object:DateTime 2015-11-25 18:02:09.630000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:02:09.630000000 Z title: ETHTBU0080002 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3HHuQorm12WGUu0kC0Uce/cf9d160fced55a45a8cb0cc9db8cbd54/ETHTBU0080002.jpg" - sys: id: 5zepzVfNDiOQy8gOyAkGig created_at: !ruby/object:DateTime 2015-11-25 18:02:34.369000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:02:34.369000000 Z title: ETHTBU0010003 description: url: "//images.ctfassets.net/xt8ne4gbbocd/5zepzVfNDiOQy8gOyAkGig/3131691f0940b7f5c823ec406b1acd03/ETHTBU0010003.jpg" ---<file_sep>/_coll_country/somalia-somaliland.md --- contentful: sys: id: 6ctwAeSEfKaiA04M2gcoiE created_at: !ruby/object:DateTime 2015-11-26 18:45:07.680000000 Z updated_at: !ruby/object:DateTime 2018-05-17 17:08:34.246000000 Z content_type_id: country revision: 14 name: Somalia/Somaliland slug: somalia-somaliland col_url: http://www.britishmuseum.org/research/collection_online/search.aspx?people=197356&place=41067|27048|1665 map_progress: true intro_progress: true image_carousel: - sys: id: 2B3KeNQ9LGYi4cIIKIwQKo created_at: !ruby/object:DateTime 2015-11-30 14:13:03.568000000 Z updated_at: !ruby/object:DateTime 2018-09-19 15:16:29.787000000 Z title: SOMGAB0090007 description: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3711116&partId=1&searchText=Dhaga+Koure,+Somaliland&page=2 url: "//images.ctfassets.net/xt8ne4gbbocd/2B3KeNQ9LGYi4cIIKIwQKo/56e8da3b0064e326038cdd962be05c3a/SOMGAB0090007.jpg" - sys: id: 49L0OyhjGU8EoqII8owGag created_at: !ruby/object:DateTime 2015-11-30 14:13:20.179000000 Z updated_at: !ruby/object:DateTime 2018-09-19 15:17:42.967000000 Z title: SOMGABNAS010032 description: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3711662&partId=1&searchText=Dhaga+Koure,+Somaliland&page=2 url: "//images.ctfassets.net/xt8ne4gbbocd/49L0OyhjGU8EoqII8owGag/2f4dfd1236e1a7d018656e300e835bd1/SOMGABNAS010032.jpg" - sys: id: 43FnN5HXGwASkcWo6I6Ms created_at: !ruby/object:DateTime 2015-11-30 14:13:12.689000000 Z updated_at: !ruby/object:DateTime 2018-09-19 15:18:47.949000000 Z title: SOMDHA0020008 description: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3711457&partId=1&searchText=Dhaymoole,+Somaliland&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/43FnN5HXGwASkcWo6I6Ms/2fed53c5ac3b0365d453cd04ff021bff/SOMDHA0020008.jpg" featured_site: sys: id: c899JmsteEUGcImgK6coE created_at: !ruby/object:DateTime 2015-11-25 12:15:21.374000000 Z updated_at: !ruby/object:DateTime 2015-12-07 20:53:38.667000000 Z content_type_id: featured_site revision: 5 title: Laas Geel, Somaliland slug: laas-geel chapters: - sys: id: 1JcxOsFcCYMqGCWuu8G2Oo created_at: !ruby/object:DateTime 2015-11-25 12:40:46.141000000 Z updated_at: !ruby/object:DateTime 2017-01-12 16:51:05.773000000 Z content_type_id: chapter revision: 2 title_internal: 'Somaliland: featured site, chapter 1' body: Laas Geel, one of the most important rock art sites in the region, is located in the north-western part of the Horn of Africa, in Somaliland, in the road that links Hargeisa and Berbera. The site is placed on a granite outcrop that rises from a plateau at an altitude of 950 meters above sea level, at the confluence of two seasonal rivers, a key fact to explain the existence of rock art in the outcrop. Even today, the name of the site (“the camel’s well” in Somali) makes reference to the availability of water near the surface of the wadis. The panels are placed at three different levels and distributed mostly throughout the eastern flank of the outcrop, although isolated depictions can be found in other slopes. images_and_captions: - sys: id: 6DXjMuJy2AeE0uMuQMOiYQ created_at: !ruby/object:DateTime 2015-11-25 12:17:16.995000000 Z updated_at: !ruby/object:DateTime 2017-01-12 16:52:45.006000000 Z content_type_id: image revision: 2 image: sys: id: 31GgY4I8aIMi6wscCMaysq created_at: !ruby/object:DateTime 2015-11-25 11:48:33.941000000 Z updated_at: !ruby/object:DateTime 2015-11-25 11:48:33.941000000 Z title: '2013,2034.15841' description: url: "//images.ctfassets.net/xt8ne4gbbocd/31GgY4I8aIMi6wscCMaysq/38ee13ba0978feca8e05b9e9f6ad9ecb/SOMLAG0020021.jpg" caption: View of Laas Geel landscape seen from one of the shelters. Laas Geel, Somaliland. 2013,2034.15841 © TARA/<NAME> col_link: http://bit.ly/2ih7AbC - sys: id: 6DXjMuJy2AeE0uMuQMOiYQ created_at: !ruby/object:DateTime 2015-11-25 12:17:16.995000000 Z updated_at: !ruby/object:DateTime 2017-01-12 16:52:45.006000000 Z content_type_id: image revision: 2 image: sys: id: 31GgY4I8aIMi6wscCMaysq created_at: !ruby/object:DateTime 2015-11-25 11:48:33.941000000 Z updated_at: !ruby/object:DateTime 2015-11-25 11:48:33.941000000 Z title: '2013,2034.15841' description: url: "//images.ctfassets.net/xt8ne4gbbocd/31GgY4I8aIMi6wscCMaysq/38ee13ba0978feca8e05b9e9f6ad9ecb/SOMLAG0020021.jpg" caption: View of Laas Geel landscape seen from one of the shelters. Laas Geel, Somaliland. 2013,2034.15841 © TARA/<NAME> col_link: http://bit.ly/2ih7AbC - sys: id: 5bW01VLoU0e8MW0QA8UEIc created_at: !ruby/object:DateTime 2015-11-25 12:41:31.266000000 Z updated_at: !ruby/object:DateTime 2015-11-25 12:41:31.266000000 Z content_type_id: chapter revision: 1 title_internal: 'Somaliland: featured site, chapter 2' body: The site was discovered in 2002 by a French team led by <NAME> which studied the beginning of Pastoralism in the Horn of Africa. Along with the paintings, lithic tools were found scattered throughout the site, and tombs marked with stelae and mounds can be seen in the neighbourhood. The paintings are distributed along 20 rock shelters, the biggest being around 10 meters long. Most of them correspond to humpless cows with curved or lyre-like white horns (sometimes with reddish tips) and marked udders. Paintings are enormously colourful, including red, white, black, violet, brown and yellow both isolated and combined. However, the most distinctive feature of these cows is their necks, depicted rectangular, abnormally wide and either blank or infilled with red and white stripes, either straight or wavy. These strange necks have been interpreted as mats hanging from the actual neck, in what could be interpreted as a ceremonial ornament. images_and_captions: - sys: id: 4MkPzhKn1KcGAqsYI2KAM4 created_at: !ruby/object:DateTime 2015-11-25 12:38:47.035000000 Z updated_at: !ruby/object:DateTime 2017-01-12 16:54:21.792000000 Z content_type_id: image revision: 2 image: sys: id: 4oUCCQM2xiEaa0WIKyAoIm created_at: !ruby/object:DateTime 2015-11-25 11:48:53.979000000 Z updated_at: !ruby/object:DateTime 2015-11-25 11:48:53.979000000 Z title: '2013,2034.16068' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4oUCCQM2xiEaa0WIKyAoIm/68d05107d238d784fb598eb52c5a3f29/SOMLAG0090043.jpg" caption: View of one of the main Lass Geel main panels, taken with a fish eye lens. <NAME>, Somaliland. 2013,2034.16068 © TARA/<NAME>oulson col_link: http://bit.ly/2iLyTXN - sys: id: 4MkPzhKn1KcGAqsYI2KAM4 created_at: !ruby/object:DateTime 2015-11-25 12:38:47.035000000 Z updated_at: !ruby/object:DateTime 2017-01-12 16:54:21.792000000 Z content_type_id: image revision: 2 image: sys: id: 4oUCCQM2xiEaa0WIKyAoIm created_at: !ruby/object:DateTime 2015-11-25 11:48:53.979000000 Z updated_at: !ruby/object:DateTime 2015-11-25 11:48:53.979000000 Z title: '2013,2034.16068' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4oUCCQM2xiEaa0WIKyAoIm/68d05107d238d784fb598eb52c5a3f29/SOMLAG0090043.jpg" caption: View of one of the main Lass Geel main panels, taken with a fish eye lens. Laas Geel, Somaliland. 2013,2034.16068 © TARA/David Coulson col_link: http://bit.ly/2iLyTXN - sys: id: 3NlNPDdYMUy2WyKIKAAyyQ created_at: !ruby/object:DateTime 2015-11-25 12:42:09.252000000 Z updated_at: !ruby/object:DateTime 2015-12-11 12:16:01.889000000 Z content_type_id: chapter revision: 2 title: title_internal: 'Somaliland: featured site, chapter 3' body: 'Cows appear isolated or in groups of up to fifteen, although no clear representation of herds can be made out, and they are often associated with human figures with a very standardized shape: frontally depicted with arms outstretched to the sides, and wearing a kind of shirt, usually white. Heads are small and sometimes surrounded by a halo of radial dashes as a crown. These figures always appear related to the cows, either under the neck, between the legs or behind the hindquarters. In some cases they carry a bow, a stick or a shield. Along with humans and cows, dogs are well represented too, usually positioned near the human figures. Other animals are much scarcer: there are some figures that could correspond to antelopes, monkeys and two lonely depictions of a giraffe. Throughout most of the panels, geometric symbols are also represented, often surrounding the cows.' images_and_captions: - sys: id: 6iWCErs5moI0koSeU4KCow created_at: !ruby/object:DateTime 2015-11-25 12:39:17.751000000 Z updated_at: !ruby/object:DateTime 2017-01-12 16:55:44.228000000 Z content_type_id: image revision: 2 image: sys: id: 4VTvKF1G52eSUicC2wuu8e created_at: !ruby/object:DateTime 2015-11-25 11:49:13.227000000 Z updated_at: !ruby/object:DateTime 2015-11-25 11:49:13.227000000 Z title: '2013,2034.15894' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4VTvKF1G52eSUicC2wuu8e/35bd5996e54375f75258f75aca92a208/SOMLAG0050018.jpg" caption: View of panel with painted depictions of cattle, antelopes and a giraffe. Laas Geel, Somaliland. 2013,2034.15894 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3709550 - sys: id: 6iWCErs5moI0koSeU4KCow created_at: !ruby/object:DateTime 2015-11-25 12:39:17.751000000 Z updated_at: !ruby/object:DateTime 2017-01-12 16:55:44.228000000 Z content_type_id: image revision: 2 image: sys: id: 4VTvKF1G52eSUicC2wuu8e created_at: !ruby/object:DateTime 2015-11-25 11:49:13.227000000 Z updated_at: !ruby/object:DateTime 2015-11-25 11:49:13.227000000 Z title: '2013,2034.15894' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4VTvKF1G52eSUicC2wuu8e/35bd5996e54375f75258f75aca92a208/SOMLAG0050018.jpg" caption: View of panel with painted depictions of cattle, antelopes and a giraffe. <NAME>, Somaliland. 2013,2034.15894 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3709550 - sys: id: 2L6Reqb06ImeEUeKq0mI4A created_at: !ruby/object:DateTime 2015-11-25 12:42:51.276000000 Z updated_at: !ruby/object:DateTime 2015-12-11 12:16:39.344000000 Z content_type_id: chapter revision: 2 title_internal: 'Somaliland: featured site, chapter 4' body: Unlike many other rock art sites, Laas Geel has been dated quite precisely thanks to the excavations carried out in one of the shelters by the French team that documented the site. During the excavation parts of the painted rock wall were recovered, and therefore the archaeologists have proposed a chronology of mid-4th to mid-3rd millennia, being one of the oldest evidences of cattle domestication in the Horn of Africa and the oldest known rock art site in this region. Unfortunately, although bovine bones were recovered from the excavation, they were too poorly preserved to determine whether they correspond to domestic or wild animals. images_and_captions: - sys: id: 7MwGPprSpiIeQOmmuOgcYg created_at: !ruby/object:DateTime 2015-11-25 12:39:41.223000000 Z updated_at: !ruby/object:DateTime 2017-01-12 16:58:47.282000000 Z content_type_id: image revision: 2 image: sys: id: 65ttuyQSS4C4CC62kSKeaQ created_at: !ruby/object:DateTime 2015-11-25 11:49:30.632000000 Z updated_at: !ruby/object:DateTime 2015-11-25 11:49:30.632000000 Z title: '2013,2034.15821' description: url: "//images.ctfassets.net/xt8ne4gbbocd/65ttuyQSS4C4CC62kSKeaQ/b8267145843996f0f0846f54ea8a1272/SOMLAG0020001.jpg" caption: View of cow and human figure painted at the middle of the rock art panel, with other cows depicted to the lower left. Laas Geel, Somaliland. 2013,2034.15821 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3691509 - sys: id: 7MwGPprSpiIeQOmmuOgcYg created_at: !ruby/object:DateTime 2015-11-25 12:39:41.223000000 Z updated_at: !ruby/object:DateTime 2017-01-12 16:58:47.282000000 Z content_type_id: image revision: 2 image: sys: id: 65ttuyQSS4C4CC62kSKeaQ created_at: !ruby/object:DateTime 2015-11-25 11:49:30.632000000 Z updated_at: !ruby/object:DateTime 2015-11-25 11:49:30.632000000 Z title: '2013,2034.15821' description: url: "//images.ctfassets.net/xt8ne4gbbocd/65ttuyQSS4C4CC62kSKeaQ/b8267145843996f0f0846f54ea8a1272/SOMLAG0020001.jpg" caption: View of cow and human figure painted at the middle of the rock art panel, with other cows depicted to the lower left. Laas Geel, Somaliland. 2013,2034.15821 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3691509 - sys: id: 5VTa7vIoIoIa2eS08ysAMU created_at: !ruby/object:DateTime 2015-11-25 12:43:38.752000000 Z updated_at: !ruby/object:DateTime 2015-11-25 12:43:38.752000000 Z content_type_id: chapter revision: 1 title_internal: 'Somaliland: featured site, chapter 5' body: When discovered, Laas Geel was considered a unique site, and although its general characteristics corresponded to the so-called Ethiopian-Arabic style, its specific stylistic features had no parallels in the rock art of the region. As research has increased, some other sites, such as <NAME>, Dhambalin and <NAME>, have provided similar depictions to those of Laas Geel, thus reinforcing the idea of a distinctive “Laas Geel” style which nevertheless must be interpreted within the broader regional context. images_and_captions: - sys: id: YFu4EthxsG8kEsA6IIQoK created_at: !ruby/object:DateTime 2015-11-25 12:40:04.102000000 Z updated_at: !ruby/object:DateTime 2017-01-12 16:59:56.493000000 Z content_type_id: image revision: 2 image: sys: id: Le7MwhlqWA8omCGckqeC0 created_at: !ruby/object:DateTime 2015-11-25 11:49:46.453000000 Z updated_at: !ruby/object:DateTime 2015-11-25 11:49:46.453000000 Z title: '2013,2034.15446' description: url: "//images.ctfassets.net/xt8ne4gbbocd/Le7MwhlqWA8omCGckqeC0/b715080968450f4bbcde78c1186b022e/SOMGAB0010009.jpg" caption: Group of painted cows with curved horns and marked udders, superimposed by more modern, white geometric signs. <NAME>, Somaliland. 2013,2034.15446 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3710609 - sys: id: YFu4EthxsG8kEsA6IIQoK created_at: !ruby/object:DateTime 2015-11-25 12:40:04.102000000 Z updated_at: !ruby/object:DateTime 2017-01-12 16:59:56.493000000 Z content_type_id: image revision: 2 image: sys: id: Le7MwhlqWA8omCGckqeC0 created_at: !ruby/object:DateTime 2015-11-25 11:49:46.453000000 Z updated_at: !ruby/object:DateTime 2015-11-25 11:49:46.453000000 Z title: '2013,2034.15446' description: url: "//images.ctfassets.net/xt8ne4gbbocd/Le7MwhlqWA8omCGckqeC0/b715080968450f4bbcde78c1186b022e/SOMGAB0010009.jpg" caption: Group of painted cows with curved horns and marked udders, superimposed by more modern, white geometric signs. <NAME>, Somaliland. 2013,2034.15446 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3710609 - sys: id: 4yBgBkRUdWGgICeIMua8Am created_at: !ruby/object:DateTime 2015-11-25 12:44:09.364000000 Z updated_at: !ruby/object:DateTime 2015-12-11 12:17:05.456000000 Z content_type_id: chapter revision: 2 title_internal: 'Somaliland: featured site, chapter 6' body: 'Laas Geel is a marvellous example of the potential of African rock art still waiting to be discovered and studied. Not only the quality of the images depicted is astonishing, but the archaeological data associated with the site and the landscape itself help to reconstruct a key episode in human history elsewhere: the moment in which animals started to be domesticated. The strong symbolism which surrounds the figures of cows and humans is a permanent testimony of the reverence these communities paid to the animals that provided their sustenance.' citations: - sys: id: 5M3Fqrd5bGqyUGegSo4U84 created_at: !ruby/object:DateTime 2015-11-25 12:44:40.978000000 Z updated_at: !ruby/object:DateTime 2015-11-25 12:44:40.978000000 Z content_type_id: citation revision: 1 citation_line: |- <NAME>., <NAME>. y <NAME>. (2003b): The Discovery of New Rock Art Paintings in the Horn of Africa: The Rock Shelters of Laas Geel, Republic of Somaliland. *Journal of African Archaeology*, 1 (2): 227-236. <NAME>. and <NAME>. (eds.) (2010): The decorated shelters of Laas Geel and the rock art of Somaliland. Presses universitaires de la Méditerranée, Montpellier University background_images: - sys: id: 4VTvKF1G52eSUicC2wuu8e created_at: !ruby/object:DateTime 2015-11-25 11:49:13.227000000 Z updated_at: !ruby/object:DateTime 2015-11-25 11:49:13.227000000 Z title: '2013,2034.15894' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4VTvKF1G52eSUicC2wuu8e/35bd5996e54375f75258f75aca92a208/SOMLAG0050018.jpg" - sys: id: 31GgY4I8aIMi6wscCMaysq created_at: !ruby/object:DateTime 2015-11-25 11:48:33.941000000 Z updated_at: !ruby/object:DateTime 2015-11-25 11:48:33.941000000 Z title: '2013,2034.15841' description: url: "//images.ctfassets.net/xt8ne4gbbocd/31GgY4I8aIMi6wscCMaysq/38ee13ba0978feca8e05b9e9f6ad9ecb/SOMLAG0020021.jpg" key_facts: sys: id: 7HCV8tMs6IUYAQ0KECeIWK created_at: !ruby/object:DateTime 2015-11-26 18:33:48.354000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:33:48.354000000 Z content_type_id: country_key_facts revision: 1 title_internal: 'Somalia/Somaliland: key facts' image_count: 788 images date_range: Mostly 3,000 BC onwards main_areas: North-west, north-east, south. techniques: Engravings, brush paintings main_themes: Cattle, anthropomorphs, geometric symbols thematic_articles: - sys: id: 1KwPIcPzMga0YWq8ogEyCO created_at: !ruby/object:DateTime 2015-11-26 16:25:56.681000000 Z updated_at: !ruby/object:DateTime 2015-12-07 20:49:15.151000000 Z content_type_id: thematic revision: 5 title: 'Sailors on sandy seas: camels in Saharan rock art' slug: camels-in-saharan-rock-art lead_image: sys: id: 46X3vtG1faouSYYws0Aywu created_at: !ruby/object:DateTime 2015-11-26 16:07:51.521000000 Z updated_at: !ruby/object:DateTime 2019-02-12 02:30:35.572000000 Z title: View of camel salt caravan crossing the Ténéré desert. Niger. ©David Coulson/TARA description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3652083&partId=1&searchText=2013,2034.10379&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/46X3vtG1faouSYYws0Aywu/6ff8cc3f26c918c81157746e1b2b3131/Fig._1._Camel.jpg" chapters: - sys: id: 1Q7xHD856UsISuceGegaqI created_at: !ruby/object:DateTime 2015-11-26 16:19:29.618000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:19:29.618000000 Z content_type_id: chapter revision: 1 title_internal: 'Camels: thematic, chapter 1' body: 'If we were to choose a defining image for the Sahara Desert, it would probably depict an endless sea of yellow dunes under a blue sky and, off in the distance, a line of long-legged, humped animals whose profiles have become synonymous with deserts: the one-humped camel (or dromedary). Since its domestication, the camel’s resistance to heat and its ability to survive with small amounts of water and a diet of desert vegetation have made it a key animal for inhabitants of the Sahara, deeply bound to their economy, material culture and lifestyle.' - sys: id: 4p7wUbC6FyiEYsm8ukI0ES created_at: !ruby/object:DateTime 2015-11-26 16:09:23.136000000 Z updated_at: !ruby/object:DateTime 2019-02-12 02:30:19.986000000 Z content_type_id: image revision: 3 image: sys: id: 46X3vtG1faouSYYws0Aywu created_at: !ruby/object:DateTime 2015-11-26 16:07:51.521000000 Z updated_at: !ruby/object:DateTime 2019-02-12 02:30:35.572000000 Z title: View of camel salt caravan crossing the Ténéré desert. Niger. ©David Coulson/TARA description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3652083&partId=1&searchText=2013,2034.10379&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/46X3vtG1faouSYYws0Aywu/6ff8cc3f26c918c81157746e1b2b3131/Fig._1._Camel.jpg" caption: Camel salt caravan crossing the Ténéré desert in Niger. 2013,2034.10487 ©<NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3652360&partId=1&searchText=2013,2034.10487&page=1 - sys: id: 1LsXHHPAZaIoUksC2US08G created_at: !ruby/object:DateTime 2015-11-26 16:19:46.820000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:19:46.820000000 Z content_type_id: chapter revision: 1 title_internal: 'Camels: thematic, chapter 2' body: Yet, surprising as it seems, the camel is a relative newcomer to the Sahara – at least when compared to other domestic animals such as cattle, sheep, horses and donkeys. Although the process is not yet fully known, camels were domesticated in the Arabian Peninsula around the third millennium BC, and spread from there to the Middle East, North Africa and Somalia from the 1st century AD onwards. The steps of this process from Egypt to the Atlantic Ocean have been documented through many different historical sources, from Roman texts to sculptures or coins, but it is especially relevant in Saharan rock art, where camels became so abundant that they have given their name to a whole period. The depictions of camels provide an incredible amount of information about the life, culture and economy of the Berber and other nomadic communities from the beginnings of the Christian era to the Muslim conquest in the late years of the 7th century. - sys: id: j3q9XWFlMOMSK6kG2UWiG created_at: !ruby/object:DateTime 2015-11-26 16:10:00.029000000 Z updated_at: !ruby/object:DateTime 2018-05-17 14:21:07.255000000 Z content_type_id: image revision: 2 image: sys: id: 6afrRs4VLUS4iEG0iwEoua created_at: !ruby/object:DateTime 2015-11-26 16:07:34.273000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:34.273000000 Z title: EA26664 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6afrRs4VLUS4iEG0iwEoua/e00bb3c81c6c9b44b5e224f5a8ce33a2/EA26664.jpg" caption: Roman terracotta camel with harness, 1st – 3rd century AD, Egypt. British Museum 1891,0403.31 © Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?museumno=1891,0430.31&objectId=118725&partId=1 - sys: id: NxdAnazJaUkeMuyoSOy68 created_at: !ruby/object:DateTime 2015-11-26 16:20:03.948000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:20:03.948000000 Z content_type_id: chapter revision: 1 title_internal: 'Camels: thematic, chapter 3' body: 'What is it that makes camels so suited to deserts? It is not only their ability to transform the fat stored in their hump into water and energy, or their capacity to eat thorny bushes, acacia leaves and even fish and bones. Camels are also able to avoid perspiration by manipulating their core temperature, enduring fluctuations of up to six degrees that could be fatal for other mammals. They rehydrate very quickly, and some of their physical features (nostrils, eyebrows) have adapted to increase water conservation and protect the animals from dust and sand. All these capacities make camels uniquely suited to hot climates: in temperatures of 30-40 °C, they can spend up to 15 days without water. In addition, they are large animals, able to carry loads of up to 300kg, over long journeys across harsh environments. The pads on their feet have evolved so as to prevent them from sinking into the sand. It is not surprising that dromedaries are considered the ‘ships of the desert’, transporting people, commodities and goods through the vast territories of the Sahara.' - sys: id: 2KjIpAzb9Kw4O82Yi6kg2y created_at: !ruby/object:DateTime 2015-11-26 16:10:36.039000000 Z updated_at: !ruby/object:DateTime 2018-05-17 14:39:34.523000000 Z content_type_id: image revision: 2 image: sys: id: 6iaMmNK91YOU00S4gcgi6W created_at: !ruby/object:DateTime 2015-11-26 16:07:51.477000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:51.477000000 Z title: Af1937,0105.16 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6iaMmNK91YOU00S4gcgi6W/4a850695b34c1766d1ee5a06f61f2b36/Af1937_0105.16.jpg" caption: Clay female dromedary (possibly a toy), Somalia. British Museum Af1937,0105.16 © Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?assetId=1088379&objectId=590967&partId=1 - sys: id: 12mIwQ0wG2qWasw4wKQkO0 created_at: !ruby/object:DateTime 2015-11-26 16:11:00.578000000 Z updated_at: !ruby/object:DateTime 2018-05-17 14:45:29.810000000 Z content_type_id: image revision: 2 image: sys: id: 4jTR7LKYv6IiY8wkc2CIum created_at: !ruby/object:DateTime 2015-11-26 16:07:51.505000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:51.505000000 Z title: Fig. 4. Man description: url: "//images.ctfassets.net/xt8ne4gbbocd/4jTR7LKYv6IiY8wkc2CIum/3dbaa11c18703b33840a6cda2c2517f2/Fig._4._Man.jpg" caption: Man leading a camel train through the Ennedi Plateau, Chad. 2013,2034.6134 ©<NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3636989&partId=1&searchText=2013,2034.6134&page=1 - sys: id: 6UIdhB0rYsSQikE8Yom4G6 created_at: !ruby/object:DateTime 2015-11-26 16:20:29.219000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:20:29.219000000 Z content_type_id: chapter revision: 1 title_internal: 'Camels: thematic, chapter 4' body: As mentioned previously, camels came from the Arabian Peninsula through Egypt, where bone remains have been dated to the early 1st millennium BC. However, it took hundreds of years to move into the rest of North Africa due to the River Nile, which represented a major geographical and climatic barrier for these animals. The expansion began around the beginning of the Christian era, and probably took place both along the Mediterranean Sea and through the south of the Sahara. At this stage, it appears to have been very rapid, and during the following centuries camels became a key element in the North African societies. They were used mainly for riding, but also for transporting heavy goods and even for ploughing. Their milk, hair and meat were also used, improving the range of resources available to their herders. However, it seems that the large caravans that crossed the desert searching for gold, ivory or slaves came later, when the Muslim conquest of North Africa favoured the establishment of vast trade networks with the Sahel, the semi-arid region that lies south of the Sahara. - sys: id: YLb3uCAWcKm288oak4ukS created_at: !ruby/object:DateTime 2015-11-26 16:11:46.395000000 Z updated_at: !ruby/object:DateTime 2018-05-17 14:46:15.751000000 Z content_type_id: image revision: 2 image: sys: id: 5aJ9wYpcHe6SImauCSGoM8 created_at: !ruby/object:DateTime 2015-11-26 16:06:48.336000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:06:48.336000000 Z title: '1923,0401.850' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5aJ9wYpcHe6SImauCSGoM8/74efd37612ec798fd91c2a46c65587f7/1923_0401.850.jpg" caption: Glass paste gem imitating beryl, engraved with a short, bearded man leading a camel with a pack on its hump. Roman Empire, 1st – 3rd century AD. 1923,0401.850 ©Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=434529&partId=1&museumno=1923,0401.850&page=1 - sys: id: 3uitqbkcY8s8GCcicKkcI4 created_at: !ruby/object:DateTime 2015-11-26 16:20:45.582000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:20:45.582000000 Z content_type_id: chapter revision: 1 title_internal: 'Camels: thematic, chapter 5' body: Rock art can be extremely helpful in learning about the different ways in which camels were used in the first millennium AD. Images of camels are found in both engravings and paintings in red, white or – on rare occasions – black; sometimes the colours are combined to achieve a more impressive effect. They usually appear in groups, alongside humans, cattle and, occasionally, dogs and horses. Sometimes, even palm trees and houses are included to represent the oases where the animals were watered. Several of the scenes show female camels herded or taking care of their calves, showing the importance of camel-herding and breeding for the Libyan-Berber communities. - sys: id: 5OWosKxtUASWIO6IUii0EW created_at: !ruby/object:DateTime 2015-11-26 16:12:17.552000000 Z updated_at: !ruby/object:DateTime 2018-05-17 15:11:49.775000000 Z content_type_id: image revision: 2 image: sys: id: 3mY7XFQW6QY6KekSQm6SIu created_at: !ruby/object:DateTime 2015-11-26 16:06:48.343000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:06:48.343000000 Z title: '2013,2034.383' description: url: "//images.ctfassets.net/xt8ne4gbbocd/3mY7XFQW6QY6KekSQm6SIu/85c0b70ab40ead396c695fe493081801/2013_2034.383.jpg" caption: Painted scene of a village, depicting a herd or caravan of camels guided by riders and dogs. Wadi Teshuinat, Acacus Mountains, Libya. 2013,2034.383 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3579914&partId=1&museumno=2013,2034.383&page=1 - sys: id: 2Ocb7A3ig8OOkc2AAQIEmo created_at: !ruby/object:DateTime 2015-11-26 16:12:48.147000000 Z updated_at: !ruby/object:DateTime 2018-05-17 15:12:22.249000000 Z content_type_id: image revision: 2 image: sys: id: 2xR2nZml7mQAse8CgckCa created_at: !ruby/object:DateTime 2015-11-26 16:07:51.480000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:51.480000000 Z title: '2013,2034.5117' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2xR2nZml7mQAse8CgckCa/984e95b65ebdc647949d656cb08c0fc9/2013_2034.5117.jpg" caption: Engravings of a female camel with calves. Oued Djerat, Algeria. 2013,2034.5117 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3624292&partId=1&museumno=2013,2034.5117&page=1 - sys: id: 4iTHcZ38wwSyGK8UIqY2yQ created_at: !ruby/object:DateTime 2015-11-26 16:13:13.897000000 Z updated_at: !ruby/object:DateTime 2018-05-17 15:31:09.339000000 Z content_type_id: image revision: 2 image: sys: id: 1ecCbVeHUGa2CsYoYSQ4Sm created_at: !ruby/object:DateTime 2015-11-26 16:07:34.241000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:34.241000000 Z title: Fig. 8. Painted description: url: "//images.ctfassets.net/xt8ne4gbbocd/1ecCbVeHUGa2CsYoYSQ4Sm/21b2aebd215d0691482411608ad5682f/Fig._8._Painted.jpg" caption: " Painted scene of Libyan-Berber warriors riding camels, accompanied by infantry and cavalrymen. Kozen Pass, Chad. 2013,2034.7295 © <NAME>/TARA" col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3655154&partId=1&searchText=2013,2034.7295&page=1 - sys: id: 2zqiJv33OUM2eEMIK2042i created_at: !ruby/object:DateTime 2015-11-26 16:21:08.068000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:21:08.068000000 Z content_type_id: chapter revision: 1 title_internal: 'Camels: thematic, chapter 6' body: |- That camels were used to transport goods is obvious, and depictions of long lines of animals are common, sometimes with saddles on which to place the packs and ropes to tie the animals together. However, if rock art depictions are some indication of camel use, it seems that until the Muslim conquest the main function of one-humped camels was as mounts, often linked to war. The Sahara desert contains dozens of astonishingly detailed images of warriors riding camels, armed with spears, long swords and shields, sometimes accompanied by infantry soldiers and horsemen. Although camels are not as good as horses for use as war mounts (they are too tall and make insecure platforms for shooting arrows), they were undoubtedly very useful in raids – the most common type of war activity in the desert – as well as being a symbol of prestige, wealth and authority among the desert warriors, much as they still are today. Moreover, the extraordinary detail of some of the rock art paintings has provided inestimable help in understanding how (and why) camels were ridden in the 1st millennium AD. Unlike horses, donkeys or mules, one-humped camels present a major problem for riders: where to put the saddle. Although it might be assumed that the saddle should be placed over the hump, they can, in fact, also be positioned behind or in front of the hump, depending on the activity. It seems that the first saddles were placed behind the hump, but that position was unsuitable for fighting, quite uncomfortable, and unstable. Subsequently, a new saddle was invented in North Arabia around the 5th century BC: a framework of wood that rested over the hump and provided a stable platform on which to ride and fight more effectively. The North Arabian saddle led to a revolution in the domestication of one-humped camels, allowed a faster expansion of the use of these animals, and it is probably still the most used type of saddle today. - sys: id: 6dOm7ewqmA6oaM4cK4cy8c created_at: !ruby/object:DateTime 2015-11-26 16:14:25.900000000 Z updated_at: !ruby/object:DateTime 2018-05-17 15:31:33.078000000 Z content_type_id: image revision: 2 image: sys: id: 5qXuQrcnUQKm0qCqoCkuGI created_at: !ruby/object:DateTime 2015-11-26 16:06:48.345000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:06:48.345000000 Z title: As1974,29.17 description: url: "//images.ctfassets.net/xt8ne4gbbocd/5qXuQrcnUQKm0qCqoCkuGI/2b279eff2a6f42121ab0f6519d694a92/As1974_29.17.jpg" caption: North Arabian-style saddle, with a wooden framework designed to be put around the hump. Jordan. British Museum As1974,29.17 © Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3320111&partId=1&object=23696&page=1 - sys: id: 5jE9BeKCBUEK8Igg8kCkUO created_at: !ruby/object:DateTime 2015-11-26 16:21:27.156000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:21:27.156000000 Z content_type_id: chapter revision: 1 title_internal: 'Camels: thematic, chapter 7' body: 'Although North Arabian saddles are found throughout North Africa and are often depicted in rock art paintings, at some point a new kind of saddle was designed in North Africa: one placed in front of the hump, with the weight over the shoulders of the camel. This type of shoulder saddle allows the rider to control the camel with the feet and legs, thus improving the ride. Moreover, the rider is seated in a lower position and thus needs shorter spears and swords that can be brandished more easily, making warriors more efficient. This new kind of saddle, which is still used throughout North Africa today, appears only in the western half of the Sahara and is well represented in the rock art of Algeria, Niger and Mauritania. And it is not only saddles that are recognizable in Saharan rock art: harnesses, reins, whips or blankets are identifiable in the paintings and show astonishing similarities to those still used today by desert peoples.' - sys: id: 6yZaDQMr1Sc0sWgOG6MGQ8 created_at: !ruby/object:DateTime 2015-11-26 16:14:46.560000000 Z updated_at: !ruby/object:DateTime 2018-05-17 15:33:25.754000000 Z content_type_id: image revision: 2 image: sys: id: 40zIycUaTuIG06mgyaE20K created_at: !ruby/object:DateTime 2015-11-26 16:07:51.466000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:51.466000000 Z title: Fig. 10. Painting description: url: "//images.ctfassets.net/xt8ne4gbbocd/40zIycUaTuIG06mgyaE20K/1736927ffb5e2fc71d1f1ab04310a73f/Fig._10._Painting.jpg" caption: Painting of rider on a one-humped camel. Note the North Arabian saddle on the hump, similar to the example from Jordan above. Terkei, Ennedi plateau, Chad. 2013,2034.6568 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3640623&partId=1&searchText=2013,2034.6568&page=1 - sys: id: 5jHyVlfWXugI2acowekUGg created_at: !ruby/object:DateTime 2015-11-26 16:15:13.926000000 Z updated_at: !ruby/object:DateTime 2018-05-17 15:36:07.603000000 Z content_type_id: image revision: 2 image: sys: id: 6EvwTsiMO4qoiIY4gGCgIK created_at: !ruby/object:DateTime 2015-11-26 16:07:34.249000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:34.249000000 Z title: '2013,2034.4471' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6EvwTsiMO4qoiIY4gGCgIK/1db47ae083ff605b9533898d9d9fb10d/2013_2034.4471.jpg" caption: Camel-rider using a North African saddle (in front of the hump), surrounded by warriors with spears and swords, with Libyan-Berber graffiti. <NAME>, <NAME>. 2013,2034.4471 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3602860&partId=1&museumno=2013,2034.4471&page=1 - sys: id: 57goC8PzUs6G4UqeG0AgmW created_at: !ruby/object:DateTime 2015-11-26 16:16:51.920000000 Z updated_at: !ruby/object:DateTime 2019-02-12 02:33:53.275000000 Z content_type_id: image revision: 3 image: sys: id: 5JDO7LrdKMcSEOMEG8qsS8 created_at: !ruby/object:DateTime 2015-11-26 16:07:34.250000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:34.250000000 Z title: Fig. 12. Tuaregs description: url: "//images.ctfassets.net/xt8ne4gbbocd/5JDO7LrdKMcSEOMEG8qsS8/76cbecd637724d549db8a7a101553280/Fig._12._Tuaregs.jpg" caption: Tuaregs at <NAME>, an annual meeting of desert peoples. Note the saddles in front of the hump and the camels' harnesses, similar to the rock paintings above such as the image from Terkei. Ingal, Northern Niger. 2013,2034.10523 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3652377&partId=1&searchText=2013,2034.10523&page=1 - sys: id: 3QPr46gQP6sQWswuSA2wog created_at: !ruby/object:DateTime 2015-11-26 16:21:50.767000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:21:50.767000000 Z content_type_id: chapter revision: 1 title_internal: 'Camels: thematic, chapter 8' body: Since their introduction to the Sahara during the first centuries of the Christian era, camels have become indispensable for desert communities, providing a method of transport for people and commodities, but also for their milk, meat and hair for weaving. They allowed the improvement of wide cultural and economic networks, transforming the Sahara into a key node linking the Mediterranean Sea with Sub-Saharan Africa. A symbol of wealth and prestige, the Libyan-Berber peoples recognized camels’ importance and expressed it through paintings and engravings across the desert, leaving a wonderful document of their societies. The painted images of camel-riders crossing the desert not only have an evocative presence, they are also perfect snapshots of a history that started two thousand years ago and seems as eternal as the Sahara. - sys: id: 54fiYzKXEQw0ggSyo0mk44 created_at: !ruby/object:DateTime 2015-11-26 16:17:13.884000000 Z updated_at: !ruby/object:DateTime 2018-05-17 16:01:13.379000000 Z content_type_id: image revision: 2 image: sys: id: 3idPZkkIKAOWCiKouQ8c8i created_at: !ruby/object:DateTime 2015-11-26 16:07:34.244000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:34.244000000 Z title: Fig. 13. Camel-riders description: url: "//images.ctfassets.net/xt8ne4gbbocd/3idPZkkIKAOWCiKouQ8c8i/4527b1eebe112ef9c38da1026e7540b3/Fig._13._Camel-riders.jpg" caption: Camel-riders galloping. Butress cave, Archael Guelta, Chad. 2013,2034.6077 ©<NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3637992&partId=1&searchText=2013,2034.6077&page=1 - sys: id: 1ymik3z5wMUEway6omqKQy created_at: !ruby/object:DateTime 2015-11-26 16:17:32.501000000 Z updated_at: !ruby/object:DateTime 2018-05-17 16:02:41.679000000 Z content_type_id: image revision: 2 image: sys: id: 4Y85f5QkVGQiuYEaA2OSUC created_at: !ruby/object:DateTime 2015-11-26 16:07:06.194000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:06.194000000 Z title: Fig. 14. Tuareg description: url: "//images.ctfassets.net/xt8ne4gbbocd/4Y85f5QkVGQiuYEaA2OSUC/4fbca027ed170b221daefdff0ae7d754/Fig._14._Tuareg.jpg" caption: Tuareg rider galloping at the Cure Salee meeting. Ingal, northern Niger. 2013,2034.10528 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3652371&partId=1&searchText=2013,2034.10528&page=1 background_images: - sys: id: 3mhr7uvrpesmaUeI4Aiwau created_at: !ruby/object:DateTime 2015-12-07 18:13:48.396000000 Z updated_at: !ruby/object:DateTime 2015-12-07 18:13:48.396000000 Z title: CHAENP0340003 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3mhr7uvrpesmaUeI4Aiwau/65c691f09cd60bb7aa08457e18eaa624/CHAENP0340003_1_.JPG" - sys: id: BPzulf3QNqMC4Iqs4EoCG created_at: !ruby/object:DateTime 2015-12-07 18:13:31.094000000 Z updated_at: !ruby/object:DateTime 2015-12-07 18:13:31.094000000 Z title: CHAENP0340001 description: url: "//images.ctfassets.net/xt8ne4gbbocd/BPzulf3QNqMC4Iqs4EoCG/356b921099bfccf59008b69060d20d75/CHAENP0340001_1_.JPG" - sys: id: 6h9anIEQRGmu8ASywMeqwc created_at: !ruby/object:DateTime 2015-11-25 17:07:20.920000000 Z updated_at: !ruby/object:DateTime 2015-12-07 20:49:54.244000000 Z content_type_id: thematic revision: 4 title: Geometric motifs and cattle brands slug: geometric-motifs lead_image: sys: id: 5yD7fOuAdU4cemkewCqCMO created_at: !ruby/object:DateTime 2015-11-25 16:56:44.778000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:56:44.778000000 Z title: '2013,2034.12976' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5yD7fOuAdU4cemkewCqCMO/4d203afb0318bee69decb23327864c79/2013_2034.12976.jpg" chapters: - sys: id: 5plObOxqdq6MuC0k4YkCQ8 created_at: !ruby/object:DateTime 2015-11-25 17:02:35.234000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:05:34.964000000 Z content_type_id: chapter revision: 3 title_internal: 'Geometric motifs: thematic, chapter 1' body: |- The rock art of eastern Africa is characterised by a wide range of non-figurative images, broadly defined as geometric. Occurring in a number of different patterns or designs, they are thought to have been in existence in this region for thousands of years, although often it is difficult to attribute the art to particular cultural groups. Geometric rock art is difficult to interpret, and designs have been variously associated with sympathetic magic, symbols of climate or fertility and altered states of consciousness (Coulson and Campbell, 2010:220). However, in some cases the motifs painted or engraved on the rock face resemble the same designs used for branding livestock and are intimately related to people’s lives and world views in this region. First observed in Kenya in the 1970s with the work of Gramly (1975) at <NAME> and Lynch and Robbins (1977) at Namoratung’a, some geometric motifs seen in the rock art of the region were observed to have had their counterparts on the hides of cattle of local communities. Although cattle branding is known to be practised by several Kenyan groups, Gramly concluded that “drawing cattle brands on the walls of rock shelters appears to be confined to the regions formerly inhabited by the Maa-speaking pastoralists or presently occupied by them”&dagger;(Gramly, 1977:117). - sys: id: 71cjHu2xrOC8O6IwSmMSS2 created_at: !ruby/object:DateTime 2015-11-25 16:57:39.559000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:06:07.592000000 Z content_type_id: image revision: 2 image: sys: id: 5yD7fOuAdU4cemkewCqCMO created_at: !ruby/object:DateTime 2015-11-25 16:56:44.778000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:56:44.778000000 Z title: '2013,2034.12976' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5yD7fOuAdU4cemkewCqCMO/4d203afb0318bee69decb23327864c79/2013_2034.12976.jpg" caption: White symbolic designs possibly representing Maa clans and livestock brands, Laikipia, Kenya. 2013,2034.12976 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3693276&partId=1&searchText=2013,2034.12976&page=1 - sys: id: 36QhSWVHKgOeMQmSMcGeWs created_at: !ruby/object:DateTime 2015-11-25 17:03:05.920000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:03:05.920000000 Z content_type_id: chapter revision: 1 title: title_internal: 'Geometric motifs: thematic, chapter 2' body: In the case of Lukenya Hill, the rock shelters on whose walls these geometric symbols occur are associated with meat-feasting ceremonies. Meat-feasting shelters exist from northern Tanzania through Kenya to Lake Turkana, and are places where Maa-speaking initiated men, who are not permitted to eat meat in their homes, gather to kill and feast on animals, predominantly cattle. During or after feasting, symbols of the animals that had been eaten were painted on the shelter ceiling in white or less often red. Maa speakers brand their cattle and camels with symbols that signify the lineage of their owners, but may also indicate if an animal has been treated for a particular disease. Different symbols may be used for male and female animals. - sys: id: 4t76LZy5zaSMGM4cUAsYOq created_at: !ruby/object:DateTime 2015-11-25 16:58:35.447000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:07:35.181000000 Z content_type_id: image revision: 2 image: sys: id: 1lBqQePHxK2Iw8wW8S8Ygw created_at: !ruby/object:DateTime 2015-11-25 16:56:44.764000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:56:44.764000000 Z title: '2013,2034.12846' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1lBqQePHxK2Iw8wW8S8Ygw/68fffb37b845614214e96ce78879c0b0/2013_2034.12846.jpg" caption: View of the long rock shelter below the waterfall showing white abstract Maasai paintings made probably quite recently during meat feasting ceremonies, Enkinyoi, Kenya. 2013,2034.12846 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3694558&partId=1&searchText=2013,2034.12846&page=1 - sys: id: 3HGWtlhoS424kQCMo6soOe created_at: !ruby/object:DateTime 2015-11-25 17:03:28.158000000 Z updated_at: !ruby/object:DateTime 2016-05-19 07:35:38.155000000 Z content_type_id: chapter revision: 2 title_internal: 'Geometric motifs: thematic, chapter 3' body: The sites of Namoratung’a near Lake Turkana in northern Kenya showed a similar visible relationship. The southernmost site is well known for its 167 megalithic stones marking male burials on which are engraved hundreds of geometric motifs. Some of these motifs bear a striking resemblance to the brand marks that the Turkana mark on their cattle, camels, donkeys and other livestock in the area, although local people claim no authorship for the funerary engravings (Russell, 2013:4). - sys: id: kgoyTkeS0oQIoaOaaWwwm created_at: !ruby/object:DateTime 2015-11-25 16:59:05.484000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:08:12.169000000 Z content_type_id: image revision: 2 image: sys: id: 19lqDiCw7UOomiMmYagQmq created_at: !ruby/object:DateTime 2015-11-25 16:56:44.756000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:56:44.756000000 Z title: '2013,2034.13006' description: url: "//images.ctfassets.net/xt8ne4gbbocd/19lqDiCw7UOomiMmYagQmq/6f54d106aaec53ed9a055dc7bf3ac014/2013_2034.13006.jpg" caption: Ndorobo man with bow and quiver of arrows kneels at a rock shelter adorned with white symbolic paintings suggesting meat-feasting rituals. Laikipia, Kenya. 2013,2034.13006 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3700172&partId=1&searchText=2013,2034.13006&page=1 - sys: id: 2JZ8EjHqi4U8kWae8oEOEw created_at: !ruby/object:DateTime 2015-11-25 17:03:56.190000000 Z updated_at: !ruby/object:DateTime 2016-05-19 07:35:15.319000000 Z content_type_id: chapter revision: 2 title_internal: 'Geometric motifs: thematic, chapter 4' body: Recent research (Russell, 2013) has shown that at Namoratung’a the branding of animals signifies a sense of belonging rather than a mark of ownership as we understand it in a modern farming context; all livestock, cattle, camel, goats, sheep and donkeys are branded according to species and sex (Russell, 2013:7). Ethnographic accounts document that clan membership can only be determined by observing someone with their livestock (Russell, 2013:9). The symbol itself is not as important as the act of placing it on the animal’s skin, and local people have confirmed that they never mark rock with brand marks. Thus, the geometric motifs on the grave markers may have been borrowed by local Turkana to serve as identity markers, but in a different context. In the Horn of Africa, some geometric rock art is located in the open landscape and on graves. It has been suggested that these too are brand or clan marks, possibly made by camel keeping pastoralists to mark achievement, territory or ownership (Russell, 2013:18). Some nomadic pastoralists, further afield, such as the Tuareg, place their clan marks along the routes they travel, carved onto salt blocks, trees and wells (Mohamed, 1990; Landais, 2001). - sys: id: 3sW37nPBleC8WSwA8SEEQM created_at: !ruby/object:DateTime 2015-11-25 16:59:47.649000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:59:47.649000000 Z content_type_id: image revision: 1 image: sys: id: 5yUlpG85GMuW2IiMeYCgyy created_at: !ruby/object:DateTime 2015-11-25 16:56:44.766000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:56:44.766000000 Z title: '2013,2034.13451' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5yUlpG85GMuW2IiMeYCgyy/a234f96f9931ec3fdddcf1ab54a33cd9/2013_2034.13451.jpg" caption: Borana cattle brands. Namoratung’a, Kenya. 2013,2034.13451. © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3660359&partId=1&searchText=2013,2034.13451&page=1 - sys: id: 6zBkbWkTaEoMAugoiuAwuK created_at: !ruby/object:DateTime 2015-11-25 17:04:38.446000000 Z updated_at: !ruby/object:DateTime 2016-05-19 07:34:17.646000000 Z content_type_id: chapter revision: 3 title_internal: 'Geometric motifs: thematic, chapter 5' body: "However, not all pastoralist geometric motifs can be associated with meat-feasting or livestock branding; they may have wider symbolism or be symbolic of something else (Russell, 2013:17). For example, informants from the Samburu people reported that while some of the painted motifs found at Samburu meat-feasting shelters were of cattle brands, others represented female headdresses or were made to mark an initiation, and in some Masai shelters there are also clear representations of warriors’ shields. In Uganda, a ceremonial rock in Karamoja, shows a dung painting consisting of large circles bisected by a cross which is said to represent cattle enclosures (Robbins, 1972). Geometric symbols, painted in fat and red ochre, on large phallic-shaped fertility stones on the Mesakin and Korongo Hills in south Sudan indicate the sex of the child to whom prayers are offered (Bell, 1936). A circle bisected by a line or circles bisected by two crosses represent boys. Girls are represented by a cross (drawn diagonally) or a slanting line (like a forward slash)(Russell, 2013: 17).\n\nAlthough pastoralist geometric motifs are widespread in the rock art of eastern Africa, attempting to find the meaning behind geometric designs is problematic. The examples discussed here demonstrate that motifs can have multiple authors, even in the same location, and that identical symbols can be the products of very different behaviours. \n" citations: - sys: id: 2oNK384LbeCqEuSIWWSGwc created_at: !ruby/object:DateTime 2015-11-25 17:01:10.748000000 Z updated_at: !ruby/object:DateTime 2016-05-19 07:33:26.748000000 Z content_type_id: citation revision: 3 citation_line: |- <NAME>. 1936. ‘Nuba fertility stones’, in *Sudan Notes and Records* 19(2), pp.313–314. Gramly R 1975. ‘Meat-feasting sites and cattle brands: Patterns of rock-shelter utilization in East Africa’ in *Azania*, 10, pp.107–121. <NAME>. 2001. ‘The marking of livestock in traditional pastoral societies’, *Scientific and Technical Review of the Office International des Epizooties* (Paris), 20 (2), pp.463–479. <NAME>. and <NAME>. 1977. ‘Animal brands and the interpretation of rock art in East Africa’ in *Current Anthropology *18, pp.538–539. <NAME>H (1972) Archaeology in the Turkana district, Kenya. Science 176(4033): 359–366 <NAME>. 2013. ‘Through the skin: exploring pastoralist marks and their meanings to understand parts of East African rock art’, in *Journal of Social Archaeology* 13:1, pp.3-30 &dagger; The term Maa relates to a group of closely related Eastern Nilotic languages, which historically dominated the east African hinterland; and today is spoken by around a million people. background_images: - sys: id: 1TDQd4TutiKwIAE8mOkYEU created_at: !ruby/object:DateTime 2015-12-07 19:16:42.825000000 Z updated_at: !ruby/object:DateTime 2015-12-07 19:16:42.825000000 Z title: KENLOK0030053 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1TDQd4TutiKwIAE8mOkYEU/718ff84615930ddafb1f1fdc67b5e479/KENLOK0030053.JPG" - sys: id: 2SCvEkDjAcIewkiu6iSGC4 created_at: !ruby/object:DateTime 2015-12-07 19:16:42.845000000 Z updated_at: !ruby/object:DateTime 2015-12-07 19:16:42.845000000 Z title: KENKAJ0030008 description: url: "//images.ctfassets.net/xt8ne4gbbocd/2SCvEkDjAcIewkiu6iSGC4/b2e2e928e5d9a6a25aca5c99058dfd76/KENKAJ0030008.jpg" - sys: id: 5HZTuIVN8AASS4ikIea6m6 created_at: !ruby/object:DateTime 2017-12-19 12:27:08.508000000 Z updated_at: !ruby/object:DateTime 2017-12-19 12:27:08.508000000 Z content_type_id: thematic revision: 1 title: Introduction to rock art in central and eastern Africa slug: rock-art-in-central-and-east-africa lead_image: sys: id: 3esXNapo5GOWIKSImcY4QW created_at: !ruby/object:DateTime 2015-11-25 18:56:43.836000000 Z updated_at: !ruby/object:DateTime 2017-12-15 17:01:05.082000000 Z title: '2013,2034.12982' description: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3776396 url: "//images.ctfassets.net/xt8ne4gbbocd/3esXNapo5GOWIKSImcY4QW/6436b2034659eccb953844b21a400070/2013_2034.12982.jpg" chapters: - sys: id: 4ln5fQLq2saMKsOA4WSAgc created_at: !ruby/object:DateTime 2015-11-25 19:09:33.580000000 Z updated_at: !ruby/object:DateTime 2015-12-11 11:17:25.155000000 Z content_type_id: chapter revision: 4 title: Central and East Africa title_internal: 'East Africa: regional, chapter 1' body: |- Central Africa is dominated by vast river systems and lakes, particularly the Congo River Basin. Characterised by hot and wet weather on both sides of the equator, central Africa has no regular dry season, but aridity increases in intensity both north and south of the equator. Covered with a forest of about 400,000 m² (1,035,920 km²), it is one of the greenest parts of the continent. The rock art of central Africa stretches from the Zambezi River to the Angolan Atlantic coast and reaches as far north as Cameroon and Uganda. Termed the ‘schematic rock art zone’ by <NAME> (1959), it is dominated by finger-painted geometric motifs and designs, thought to extend back many thousands of years. Eastern Africa, from the Zambezi River Valley to Lake Turkana, consists largely of a vast inland plateau with the highest elevations on the continent, such as Mount Kilimanjaro (5,895m above sea level) and Mount Kenya (5,199 m above sea level). Twin parallel rift valleys run through the region, which includes the world’s second largest freshwater lake, Lake Victoria. The climate is atypical of an equatorial region, being cool and dry due to the high altitude and monsoon winds created by the Ethiopian Highlands. The rock art of eastern Africa is concentrated on this plateau and consists mainly of paintings that include animal and human representations. Found mostly in central Tanzania, eastern Zambia and Malawi; in comparison to the widespread distribution of geometric rock art, this figurative tradition is much more localised, and found at just a few hundred sites in a region of less than 100km in diameter. - sys: id: 4nyZGLwHTO2CK8a2uc2q6U created_at: !ruby/object:DateTime 2015-11-25 18:57:48.121000000 Z updated_at: !ruby/object:DateTime 2017-12-15 17:05:00.916000000 Z content_type_id: image revision: 2 image: sys: id: 3esXNapo5GOWIKSImcY4QW created_at: !ruby/object:DateTime 2015-11-25 18:56:43.836000000 Z updated_at: !ruby/object:DateTime 2017-12-15 17:01:05.082000000 Z title: '2013,2034.12982' description: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3776396 url: "//images.ctfassets.net/xt8ne4gbbocd/3esXNapo5GOWIKSImcY4QW/6436b2034659eccb953844b21a400070/2013_2034.12982.jpg" caption: <NAME>. 2013,2034.12982 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3776396 - sys: id: 1OvIWDPyXaCO2gCWw04s06 created_at: !ruby/object:DateTime 2015-11-25 19:10:23.723000000 Z updated_at: !ruby/object:DateTime 2015-12-11 11:18:19.325000000 Z content_type_id: chapter revision: 2 title_internal: 'East Africa: regional, chapter 2' body: This collection from Central and East Africa comprises rock art from Kenya, Uganda and Tanzania, as well as the Horn of Africa; although predominantly paintings, engravings can be found in most countries. - sys: id: 4JqI2c7CnYCe8Wy2SmesCi created_at: !ruby/object:DateTime 2015-11-25 19:10:59.991000000 Z updated_at: !ruby/object:DateTime 2016-10-17 13:34:14.653000000 Z content_type_id: chapter revision: 3 title: History of research title_internal: 'East Africa: regional, chapter 3' body: |- The rock art of East Africa, in particular the red paintings from Tanzania, was extensively studied by Mary and Louis Leakey in the 1930s and 1950s. <NAME> observed Sandawe people of Tanzania making rock paintings in the mid-20th century, and on the basis of oral traditions argued that the rock art was made for three main purposes: casual art; magic art (for hunting purposes or connected to health and fertility) and sacrificial art (to appease ancestral spirits). Subsequently, during the 1970s Fidelis Masao and <NAME> recorded numerous sites, classifying the art in broad chronological and stylistic categories, proposing tentative interpretations with regard to meaning. There has much debate and uncertainty about Central African rock art. The history of the region has seen much mobility and interaction of cultural groups and understanding how the rock art relates to particular groups has been problematic. Pioneering work in this region was undertaken by <NAME> in central Malawi in the early 1920s, <NAME> visited Zambia in 1936 and attempted to provide a chronological sequence and some insight into the meaning of the rock art. Since the 1950s (Clarke, 1959), archaeologists have attempted to situate rock art within broader archaeological frameworks in order to resolve chronologies, and to categorise the art with reference to style, colour, superimposition, subject matter, weathering, and positioning of depictions within the panel (Phillipson, 1976). Building on this work, our current understanding of rock in this region has been advanced by <NAME> (1995, 1997, 2001) with his work in Zambia and Malawi. - sys: id: 35HMFoiKViegWSY044QY8K created_at: !ruby/object:DateTime 2015-11-25 18:59:25.796000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:51:25.789000000 Z content_type_id: image revision: 5 image: sys: id: 6KOxC43Z9mYCuIuqcC8Qw0 created_at: !ruby/object:DateTime 2015-11-25 18:57:00.077000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:57:00.077000000 Z title: '2013,2034.17450' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6KOxC43Z9mYCuIuqcC8Qw0/e25141d07f483d0100c4cf5604e3e525/2013_2034.17450.jpg" caption: This painting of a large antelope is possibly one of the earliest extant paintings. <NAME> believes similar paintings could be more than 28,000 years old. 2013,2034.17450 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3711689 - sys: id: 1dSBI9UNs86G66UGSEOOkS created_at: !ruby/object:DateTime 2015-12-09 11:56:31.754000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:50:18.203000000 Z content_type_id: chapter revision: 5 title: East African Rock Art title_internal: Intro to east africa, chapter 3.5 body: "Rock art of East Africa consists mainly of paintings, most of which are found in central Tanzania, and are fewer in number in eastern Zambia and Malawi; scholars have categorised them as follows:\n\n*__Red Paintings__*: \nRed paintings can be sub-divided into those found in central Tanzania and those found stretching from Zambia to the Indian Ocean.\nTanzanian red paintings include large, naturalistic animals with occasional geometric motifs. The giraffe is the most frequently painted animal, but antelope, zebra, elephant, rhino, felines and ostrich are also depicted. Later images show figures with highly distinctive stylised human head forms or hairstyles and body decoration, sometimes in apparent hunting and domestic scenes. The Sandawe and Hadza, hunter-gatherer groups, indigenous to north-central and central Tanzania respectively, claim their ancestors were responsible for some of the later art.\n\nThe area in which Sandawe rock art is found is less than 100km in diameter and occurs at just a few hundred sites, but corresponds closely to the known distribution of this group. There have been some suggestions that Sandawe were making rock art early into the 20th century, linking the art to particular rituals, in particular simbo; a trance dance in which the Sandawe communicate with the spirit world by taking on the power of an animal. The art displays a range of motifs and postures, features that can be understood by reference to simbo and to trance experiences; such as groups of human figures bending at the waist (which occurs during the *simbo* dance), taking on animal features such as ears and tails, and floating or flying; reflecting the experiences of those possessed in the dance." - sys: id: 7dIhjtbR5Y6u0yceG6y8c0 created_at: !ruby/object:DateTime 2015-11-25 19:00:07.434000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:51:51.887000000 Z content_type_id: image revision: 5 image: sys: id: 1fy9DD4BWwugeqkakqWiUA created_at: !ruby/object:DateTime 2015-11-25 18:57:11.188000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:57:11.188000000 Z title: '2013,2034.16849' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1fy9DD4BWwugeqkakqWiUA/9f8f1330c6c0bc0ff46d744488daa152/2013_2034.16849.jpg" caption: Three schematic figures formed by the use of multiple thin parallel lines. The shape and composition of the heads suggests either headdresses or elaborate hairstyles. Kondoa, Tanzania. 2013,2034.16849 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3709812 - sys: id: 1W573pi2Paks0iA8uaiImy created_at: !ruby/object:DateTime 2015-11-25 19:12:00.544000000 Z updated_at: !ruby/object:DateTime 2015-12-11 11:21:09.647000000 Z content_type_id: chapter revision: 8 title_internal: 'East Africa: regional, chapter 4' body: "Zambian rock art does not share any similarities with Tanzanian rock art and can be divided into two categories; animals (with a few depictions of humans), and geometric motifs. Animals are often highly stylised and superimposed with rows of dots. Geometric designs include, circles, some of which have radiating lines, concentric circles, parallel lines and ladder shapes. Predominantly painted in red, the remains of white pigment is still often visible. David Phillipson (1976) proposed that the naturalistic animals were earlier in date than geometric designs. Building on Phillipson’s work, <NAME> studied ethnographic records and demonstrated that geometric motifs were made by women or controlling the weather.\n\n*__Pastoralist paintings__*: \nPastoralist paintings are rare, with only a few known sites in Kenya and other possible sites in Malawi. Usually painted in black, white and grey, but also in other colours, they include small outlines, often infilled, of cattle and are occasional accompanied by geometric motifs. Made during the period from 3,200 to 1,800 years ago the practice ceased after Bantu language speaking people had settled in eastern Africa. Similar paintings are found in Ethiopia but not in southern Africa, and it has been assumed that these were made by Cushitic or Nilotic speaking groups, but their precise attribution remains unclear (Smith, 2013:154).\n" - sys: id: 5jReHrdk4okicG0kyCsS6w created_at: !ruby/object:DateTime 2015-11-25 19:00:41.789000000 Z updated_at: !ruby/object:DateTime 2017-12-15 17:10:04.890000000 Z content_type_id: image revision: 3 image: sys: id: 1hoZEK3d2Oi8iiWqoWACo created_at: !ruby/object:DateTime 2015-11-25 18:56:43.848000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:56:43.848000000 Z title: '2013,2034.13653' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1hoZEK3d2Oi8iiWqoWACo/1a1adcfad5d5a1cf0a341316725d61c4/2013_2034.13653.jpg" caption: Two red bulls face right. Mt Elgon, Kenya. 2013,2034.13653. © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3700058 - sys: id: 7rFAK9YoBqYs0u0EmCiY64 created_at: !ruby/object:DateTime 2015-11-25 19:00:58.494000000 Z updated_at: !ruby/object:DateTime 2017-12-15 17:11:37.760000000 Z content_type_id: image revision: 3 image: sys: id: 3bqDVyvXlS0S6AeY2yEmS8 created_at: !ruby/object:DateTime 2015-11-25 18:56:43.880000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:56:43.880000000 Z title: '2013,2034.13635' description: url: "//images.ctfassets.net/xt8ne4gbbocd/3bqDVyvXlS0S6AeY2yEmS8/c9921f3d8080bcef03c96c6b8f1b0323/2013_2034.13635.jpg" caption: Two cattle with horns in twisted perspective. Mt Elgon, Kenya. 2013,2034.13635. © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3698905 - sys: id: 1tX4nhIUgAGmyQ4yoG6WEY created_at: !ruby/object:DateTime 2015-11-25 19:14:33.823000000 Z updated_at: !ruby/object:DateTime 2015-11-25 19:14:33.823000000 Z content_type_id: chapter revision: 1 title_internal: 'East Africa: regional, chapter 5' body: |- *__Late White Paintings__*: Commonly painted in white, or off-white with the fingers, so-called ‘Late White’ depictions include quite large crudely rendered representations of wild animals, mythical animals, human figures and numerous geometric motifs. These paintings are attributed to Bantu language speaking, iron-working farmers who entered eastern Africa about 2,000 years ago from the west on the border of Nigeria and Cameroon. Moving through areas occupied by the Batwa it is thought they learned the use of symbols painted on rock, skin, bark cloth and in sand. Chewa peoples, Bantu language speakers who live in modern day Zambia and Malawi claim their ancestors made many of the more recent paintings which they used in rites of passage ceremonies. - sys: id: 35dNvNmIxaKoUwCMeSEO2Y created_at: !ruby/object:DateTime 2015-11-25 19:01:26.458000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:52:15.838000000 Z content_type_id: image revision: 4 image: sys: id: 6RGZZQ13qMQwmGI86Ey8ei created_at: !ruby/object:DateTime 2015-11-25 18:57:11.188000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:57:11.188000000 Z title: '2013,2034.16786' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6RGZZQ13qMQwmGI86Ey8ei/6d37a5bed439caf7a1223aca27dc27f8/2013_2034.16786.jpg" caption: Under a long narrow granite overhang, Late White designs including rectangular grids, concentric circles and various ‘square’ shapes. 2013,2034.16786 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3709608 - sys: id: 2XW0X9BzFCa8u2qiKu6ckK created_at: !ruby/object:DateTime 2015-11-25 19:01:57.959000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:53:21.559000000 Z content_type_id: image revision: 4 image: sys: id: 1UT4r6kWRiyiUIYSkGoACm created_at: !ruby/object:DateTime 2015-11-25 18:57:11.138000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:57:11.138000000 Z title: '2013,2034.16797' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1UT4r6kWRiyiUIYSkGoACm/fe915c6869b6c195d55b5ef805df7671/2013_2034.16797.jpg" caption: A monuments guard stands next to Late White paintings attributed to Bantu speaking farmers in Tanzania, probably made during the last 700 years. 2013,2034.16797 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3709628 - sys: id: 3z28O8A58AkgMUocSYEuWw created_at: !ruby/object:DateTime 2015-11-25 19:15:04.047000000 Z updated_at: !ruby/object:DateTime 2015-11-25 19:15:04.047000000 Z content_type_id: chapter revision: 1 title_internal: 'East Africa: regional, chapter 6' body: |- *__Meat-feasting paintings__*: Meat-feasting shelters exist from northern Tanzania through Kenya to Lake Turkana, and are places where Maa-speaking initiated men, who are not permitted to eat meat in their homes, gather to kill and feast on animals, predominantly cattle. The term Maa relates to a group of closely related Eastern Nilotic languages, which historically dominated the east African hinterland; and today is spoken by around a million people. During or after feasting, symbols of the animals that had been eaten were painted on the shelter ceiling in white or less often red. Maa speakers brand their cattle and camels with symbols that signify the lineage of their owners, but may also indicate if an animal has been treated for a particular disease. Different symbols may be used for male and female animals. Over the centuries, because the depictions are on the ceiling of meat feasting rock shelters, and because sites are used even today, a build-up of soot has obscured or obliterated the paintings. Unfortunately, few have been recorded or mapped. - sys: id: 1yjQJMFd3awKmGSakUqWGo created_at: !ruby/object:DateTime 2015-11-25 19:02:23.595000000 Z updated_at: !ruby/object:DateTime 2017-12-15 17:19:11.619000000 Z content_type_id: image revision: 3 image: sys: id: p4E0BRJzossaus6uUUkuG created_at: !ruby/object:DateTime 2015-11-25 18:56:49.743000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:56:49.743000000 Z title: '2013,2034.13004' description: url: "//images.ctfassets.net/xt8ne4gbbocd/p4E0BRJzossaus6uUUkuG/13562eee76ac2a9efe8c0d12e62fa23a/2013_2034.13004.jpg" caption: Huge granite boulder with Ndorobo man standing before a rock overhang used for meat-feasting. Laikipia, Kenya. 2013,2034. 13004. © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3700175 - sys: id: 6lgjLZVYrY606OwmwgcmG2 created_at: !ruby/object:DateTime 2015-11-25 19:02:45.427000000 Z updated_at: !ruby/object:DateTime 2017-12-15 17:20:14.877000000 Z content_type_id: image revision: 3 image: sys: id: 1RLyVKKV8MA4KEk4M28wqw created_at: !ruby/object:DateTime 2015-11-25 18:57:11.150000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:57:11.150000000 Z title: '2013,2034.13018' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1RLyVKKV8MA4KEk4M28wqw/044529be14a590fd1d0da7456630bb0b/2013_2034.13018.jpg" caption: This symbol is probably a ‘brand’ used on cattle that were killed and eaten at a Maa meat feast. Laikipia, Kenya. 2013,2034.13018 © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3700193 - sys: id: 5UQc80DUBiqqm64akmCUYE created_at: !ruby/object:DateTime 2015-11-25 19:15:34.582000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:53:53.936000000 Z content_type_id: chapter revision: 4 title: Central African Rock Art title_internal: 'East Africa: regional, chapter 7' body: The rock art of central Africa is attributed to hunter-gatherers known as Batwa. This term is used widely in eastern central and southern Africa to denote any autochthonous hunter-gatherer people. The rock art of the Batwa can be divided into two categories which are quite distinctive stylistically from the Tanzanian depictions of the Sandawe and Hadza. Nearly 3,000 sites are currently known from within this area. The vast majority, around 90%, consist of finger-painted geometric designs; the remaining 10% include highly stylised animal forms (with a few human figures) and rows of finger dots. Both types are thought to date back many thousands of years. The two traditions co-occur over a vast area of eastern and central Africa and while often found in close proximity to each other are only found together at a few sites. However, it is the dominance of geometric motifs that make this rock art tradition very distinctive from other regions in Africa. - sys: id: 4m51rMBDX22msGmAcw8ESw created_at: !ruby/object:DateTime 2015-11-25 19:03:40.666000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:54:25.415000000 Z content_type_id: image revision: 4 image: sys: id: 2MOrR79hMcO2i8G2oAm2ik created_at: !ruby/object:DateTime 2015-11-25 18:56:49.737000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:56:49.737000000 Z title: '2013,2034.15306' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2MOrR79hMcO2i8G2oAm2ik/86179e84233956e34103566035c14b76/2013_2034.15306.jpg" caption: Paintings in red and originally in-filled in white cover the underside of a rock shelter roof. The art is attributed to central African Batwa; the age of the paintings is uncertain. Lake Victoria, Uganda. 2013,2034.15306 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3691242 - sys: id: 5rNOG3568geMmIEkIwOIac created_at: !ruby/object:DateTime 2015-11-25 19:16:07.130000000 Z updated_at: !ruby/object:DateTime 2015-11-25 19:16:19.722000000 Z content_type_id: chapter revision: 2 title_internal: 'East Africa: regional, chapter 8' body: "*__Engravings__*:\nThere are a few engravings occurring on inland plateaus but these have elicited little scientific interest and are not well documented. \ Those at the southern end of Lake Turkana have been categorised into two types: firstly, animals, human figures and geometric forms and also geometric forms thought to involve lineage symbols.\nIn southern Ethiopia, near the town of Dillo about 300 stelae, some of which stand up to two metres in height, are fixed into stones and mark grave sites. People living at the site ask its spirits for good harvests. \n" - sys: id: LrZuJZEH8OC2s402WQ0a6 created_at: !ruby/object:DateTime 2015-11-25 19:03:59.496000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:54:51.576000000 Z content_type_id: image revision: 5 image: sys: id: 1uc9hASXXeCIoeMgoOuO4e created_at: !ruby/object:DateTime 2015-11-25 18:57:11.176000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:57:11.176000000 Z title: '2013,2034.16206' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1uc9hASXXeCIoeMgoOuO4e/09a7504449897509778f3b9455a42f8d/2013_2034.16206.jpg" caption: Group of anthropomorphic stelae with carved faces. <NAME>, Southern Ethiopia. 2013,2034.16206 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3703754 - sys: id: 7EBTx1IjKw6y2AUgYUkAcm created_at: !ruby/object:DateTime 2015-11-25 19:16:37.210000000 Z updated_at: !ruby/object:DateTime 2015-12-11 11:22:04.007000000 Z content_type_id: chapter revision: 2 title_internal: 'East Africa: regional, chapter 9' body: In the Sidamo region of Ethiopia, around 50 images of cattle are engraved in bas-relief on the wall of a gorge. All the engravings face right and the cows’ udders are prominently displayed. Similar engravings of cattle, all close to flowing water, occur at five other sites in the area, although not in such large numbers. - sys: id: 6MUkxUNFW8oEK2aqIEcee created_at: !ruby/object:DateTime 2015-11-25 19:04:34.186000000 Z updated_at: !ruby/object:DateTime 2017-12-19 12:22:24.891000000 Z content_type_id: image revision: 3 image: sys: id: PlhtduNGSaOIOKU4iYu8A created_at: !ruby/object:DateTime 2015-11-25 18:56:43.849000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:56:43.849000000 Z title: '2013,2034.16235' description: url: "//images.ctfassets.net/xt8ne4gbbocd/PlhtduNGSaOIOKU4iYu8A/7625c8a21caf60046ea73f184e8b5c76/2013_2034.16235.jpg" caption: Around 50 images of cattle are engraved in bas-relief into the sandstone wall of a gorge in the Sidamo region of Ethiopia. 2013,2034.16235 © TARA/<NAME> col_link: http://bit.ly/2hMU0vm - sys: id: 6vT5DOy7JK2oqgGK8EOmCg created_at: !ruby/object:DateTime 2015-11-25 19:17:53.336000000 Z updated_at: !ruby/object:DateTime 2015-12-11 11:25:38.678000000 Z content_type_id: chapter revision: 3 title: Rock art in the Horn of Africa title_internal: 'East Africa: regional, chapter 10' body: "The Horn of Africa has historically been a crossroads area between the Eastern Sahara, the Subtropical regions to the South and the Arabic Peninsula. These mixed influences can be seen in many archaeological and historical features throughout the region, the rock art being no exception. Since the early stages of research in the 1930s, a strong relationship between the rock art in Ethiopia and the Arabian Peninsula was detected, leading to the establishment of the term *Ethiopian-Arabian* rock art by <NAME> in 1971. This research thread proposes a progressive evolution from naturalism to schematism, ranging from the 4th-3rd millennium BC to the near past. Although the *Ethiopian-Arabian* proposal is still widely accepted and stylistic similarities between the rock art of Somalia, Ethiopia, Yemen or Saudi Arabia are undeniable, recent voices have been raised against the term because of its excessive generalisation and lack of operability. In addition, recent research to the south of Ethiopia have started to discover new rock art sites related to those found in Uganda and Kenya.\n\nRegarding the main themes of the Horn of Africa rock art, cattle depictions seem to have been paramount, with cows and bulls depicted either isolated or in herds, frequently associated with ritual scenes which show their importance in these communities. Other animals – zebus, camels, felines, dogs, etc. – are also represented, as well as rows of human figures, and fighting scenes between warriors or against lions. Geometric symbols are also common, usually associated with other depictions; and in some places they have been interpreted as tribal or clan marks. Both engraving and painting is common in most regions, with many regional variations. \n" - sys: id: 4XIIE3lDZYeqCG6CUOYsIG created_at: !ruby/object:DateTime 2015-11-25 19:04:53.913000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:55:12.472000000 Z content_type_id: image revision: 4 image: sys: id: 3ylztNmm2cYU0GgQuW0yiM created_at: !ruby/object:DateTime 2015-11-25 18:57:11.155000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:57:11.155000000 Z title: '2013,2034.15749' description: url: "//images.ctfassets.net/xt8ne4gbbocd/3ylztNmm2cYU0GgQuW0yiM/3be240bf82adfb5affc0d653e353350b/2013_2034.15749.jpg" caption: Painted roof of rock shelter showing decorated cows and human figures. <NAME>. 2013,2034.15749 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3691391 - sys: id: 2IKYx0YIVOyMSwkU8mQQM created_at: !ruby/object:DateTime 2015-11-25 19:18:28.056000000 Z updated_at: !ruby/object:DateTime 2015-12-11 11:26:13.401000000 Z content_type_id: chapter revision: 2 title_internal: 'East Africa: regional, chapter 11' body: |- Rock art in the Horn of Africa faces several challenges. One of them is the lack of consolidated chronologies and absolute dating for the paintings and engravings. Another is the uneven knowledge of rock art throughout the region, with research often affected by political unrest. Therefore, distributions of rock art in the region are steadily growing as research is undertaken in one of the most interactive areas in East Africa. The rock art of Central and East Africa is one of the least documented and well understood of the corpus of African rock art. However, in recent years scholars have undertaken some comprehensive reviews of existing sites and surveys of new sites to open up the debates and more fully understand the complexities of this region. citations: - sys: id: 7d9bmwn5kccgO2gKC6W2Ys created_at: !ruby/object:DateTime 2015-11-25 19:08:04.014000000 Z updated_at: !ruby/object:DateTime 2017-12-19 12:24:18.659000000 Z content_type_id: citation revision: 2 citation_line: "<NAME>. 1996. ‘Cultural Patterns in the Rock Art of Central Tanzania.’ in *The Prehistory of Africa*. XIII International Congress of Prehistoric and Protohistoric Sciences Forli-Italia-8/14 September.\n\nČerviček, P. 1971. ‘Rock paintings of Laga Oda (Ethiopia)’ in *Paideuma*, 17, pp.121-136.\n\nClark, <NAME>. 1954. *The Prehistoric Cultures of the Horn of Africa*. New York: Octagon Press.\n\nClark, J.C.D. 1959. ‘Rock Paintings of Northern Rhodesia and Nyasaland’, in Summers, R. (ed.) *Prehistoric Rock Art of the Federation of Rhodesia & Nyasaland*: Glasgow: National Publication Trust, pp.163- 220.\n\nJoussaume, R. (ed.) 1995. Tiya, *l’Ethiopie des mégalithes : du biface à l’art rupestre dans la Corne de l’Afrique*. Association des publications chauvinoises (A.P.C.), Chauvigny.\n\n<NAME>. 1983. *Africa’s Vanishing Art – The Rock Paintings of Tanzania*. London: Hamish Hamilton Ltd.\n\nMasao, F.T. 1979. *The Later Stone Age and the Rock Paintings of Central Tanzania*. Wiesbaden: Franz Steiner Verlag. \n\nNamono, Catherine. 2010. *A contextual interpretive approach to the rock art of Uganda*. Unpublished PhD Thesis. Johannesburg: University of Witwatersrand\n\nPhillipson, D.W. 1976. ‘The Rock Paintings of Eastern Zambia’, in *The Prehistory of Eastern Zambia: Memoir 6 of the british Institute in Eastern Africa*. Nairobi.\n\n<NAME>. (1995), Rock art in south-Central Africa: A study based on the pictographs of Dedza District, Malawi and Kasama District Zambia. dissertation. Cambridge: University of Cambridge, Unpublished Ph.D. dissertation.\n\n<NAME>. (1997), Zambia’s ancient rock art: The paintings of Kasama. Zambia: The National Heritage Conservation Commission of Zambia.\n\nSmith B.W. (2001), Forbidden images: Rock paintings and the Nyau secret society of Central Malaŵi and Eastern Zambia. *African Archaeological Review*18(4): 187–211.\n\nSmith, Benjamin. 2013, ‘Rock art research in Africa; in In: Lane, P. & Mitchell, P. (eds) *Handbook of African Archaeology*. Oxford: Oxford University Press, pp.145-162.\n\nTen Raa, E. 1974. ‘A record of some prehistoric and some recent Sandawe rock paintings’ in *Tanzania Notes and Records* 75, pp.9-27." background_images: - sys: id: 4aeKk2gBTiE6Es8qMC4eYq created_at: !ruby/object:DateTime 2015-12-07 19:42:27.348000000 Z updated_at: !ruby/object:DateTime 2017-12-19 12:25:55.914000000 Z title: '2013,2034.1298' description: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3592557 url: "//images.ctfassets.net/xt8ne4gbbocd/4aeKk2gBTiE6Es8qMC4eYq/31cde536c4abf1c0795761f8e35b255c/2013_2034.1298.jpg" - sys: id: 6DbMO4lEBOU06CeAsEE8aA created_at: !ruby/object:DateTime 2015-12-07 19:41:53.440000000 Z updated_at: !ruby/object:DateTime 2017-12-19 12:26:40.898000000 Z title: '2013,2034.15749' description: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3691391 url: "//images.ctfassets.net/xt8ne4gbbocd/6DbMO4lEBOU06CeAsEE8aA/9fc2e1d88f73a01852e1871f631bf4ff/2013_2034.15749.jpg" - sys: id: 2KyCxSpMowae0oksYsmawq created_at: !ruby/object:DateTime 2015-11-25 18:32:33.269000000 Z updated_at: !ruby/object:DateTime 2019-02-21 14:57:42.412000000 Z content_type_id: thematic revision: 5 title: 'The Country of the Standing Stones: Stela in Southern Ethiopia' slug: country-of-standing-stones lead_image: sys: id: 5N30tsfHVuW0AmIgeQo8Kk created_at: !ruby/object:DateTime 2015-11-25 18:01:40.103000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:01:40.103000000 Z title: ETHTBU0050002 description: url: "//images.ctfassets.net/xt8ne4gbbocd/5N30tsfHVuW0AmIgeQo8Kk/ad2ce21e5a6a89a0d4ea07bee897b525/ETHTBU0050002.jpg" chapters: - sys: id: 7lbvgOvsBO0sgeSkwU68K8 created_at: !ruby/object:DateTime 2015-11-25 18:28:36.149000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:48:54.764000000 Z content_type_id: chapter revision: 2 title_internal: 'Stela: thematic, chapter 1' body: Ethiopia is home to some of the most impressive archaeological remains in Africa, such as the rock-hewn churches of Lalibela, the Axumite kingdom monoliths or the Gondar palaces. Most of these sites are located in northern Ethiopia, but to the south of the country there are also some remarkable archaeological remains, less well-known but which deserve attention. One of them is the dozens of graveyards located along the Rift Valley and marked by hundreds of stone stelae of different types, usually decorated. Ethiopia holds the biggest concentration of steale in all Africa, a testimony of the complexity of the societies which inhabited the Horn of Africa at the beginning of the second millennium AD. - sys: id: 3q8L69s3O8YOWsS4MAI0gk created_at: !ruby/object:DateTime 2015-11-25 18:03:36.680000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:51:45.367000000 Z content_type_id: image revision: 2 image: sys: id: 3lhKPWDnSwEIKmoGaySEIy created_at: !ruby/object:DateTime 2015-11-25 18:02:34.448000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:02:34.448000000 Z title: ETHTBU0090003 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3lhKPWDnSwEIKmoGaySEIy/a330ae393d066149e80155b81694f6d3/ETHTBU0090003.jpg" caption: Engraved stela from Silté (now in the Addis Ababa National Museum), probably of a historic period, completely covered by symbols and human figures. 2013,2034.16388 ©TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3704087&partId=1&searchText=2013,2034.16388&view=list&page=1 - sys: id: wMW6zfth1mIgEiSqIy04S created_at: !ruby/object:DateTime 2015-11-25 18:28:55.931000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:52:16.164000000 Z content_type_id: chapter revision: 2 title_internal: 'Stela: thematic, chapter 2' body: Although some of the most impressive stelae are located to the north-east of Ethiopia, in the region where the Axumite Kingdom flourished between the 1st and the 10th centuries AD, the area with the highest concentration of stelae is to the south-west of the country, from the Manz region to the north of Addis Ababa to the border with Kenya. It is an extensive area which approximately follows the Rift Valley and the series of lakes that occupy its floor, and which roughly covers the Soddo, Wolayta and Sidamo regions. The region has a tropical climate and is fertile, with warm conditions being predominant and rainfall being quite abundant, with annual rates of 1200-1500 mm in the lower areas while in the highlands the rainfall reaches 2.000 mm per year. - sys: id: 5BGRogcCPeYgq2SY62eyUk created_at: !ruby/object:DateTime 2015-11-25 18:24:59.375000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:53:36.787000000 Z content_type_id: image revision: 2 image: sys: id: 3HHuQorm12WGUu0kC0Uce created_at: !ruby/object:DateTime 2015-11-25 18:02:09.630000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:02:09.630000000 Z title: ETHTBU0080002 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3HHuQorm12WGUu0kC0Uce/cf9d160fced55a45a8cb0cc9db8cbd54/ETHTBU0080002.jpg" caption: Two stelae on which are carved human figures. The faces have carved stripes, sometimes interpreted as masks. <NAME>. 2013,2034.16385 ©TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3704090&partId=1&searchText=2013,2034.16385&view=list&page=1 - sys: id: 3CBiLCh7ziUkMC264I4oSw created_at: !ruby/object:DateTime 2015-11-25 18:29:16.601000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:58:41.825000000 Z content_type_id: chapter revision: 2 title_internal: 'Stela: thematic, chapter 3' body: 'Ethiopian stelae have been known to western scholars since the end of the 19th century, with the first examples documented in 1885 to the north of Addis Ababa and the news about the main group to the south arriving in 1905. The first archaeological works in the southern area took place in the 1920’s carried out by French and German researchers. The work of <NAME> was especially remarkable, with four expeditions undertaken between 1922 and 1926 which were partially published in 1931. Along with Azaïs, a German team from the Frobénius Institute started to study the site of Tuto Fela, a huge cemetery with hundreds of phallic and anthropomorphic stelae located in the Sidamo region. Since these early studies the archaeological remains were left unattended until the 1970’s, when <NAME> excavated the site of Gattira-Demma and organized a far more systematic survey in the area which documented dozens of stelae of different sizes and types. In the 1980’s, another French team started to study first Tiya and then Tuto Fela and another important site, Chelba-Tutitti, in a long-term project which has been going on for thirty years and has been paramount to understand the types, chronologies and distribution of these archaeological remains. The historical importance of these stelae was universally recognized in 1980, when Tiya was listed as a UNESCO World Heritage Site. ' - sys: id: 3OqDncSoogykaUgAyW0Mei created_at: !ruby/object:DateTime 2015-11-25 18:25:18.604000000 Z updated_at: !ruby/object:DateTime 2018-05-15 16:00:14.418000000 Z content_type_id: image revision: 2 image: sys: id: 5Zt1z4iJ44c2MWmWcGy4Ey created_at: !ruby/object:DateTime 2015-11-25 18:01:40.088000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:01:40.088000000 Z title: ETHSID0010002 description: url: "//images.ctfassets.net/xt8ne4gbbocd/5Zt1z4iJ44c2MWmWcGy4Ey/7a08db34b4eba7530b9efb69f42fec36/ETHSID0010002.jpg" caption: View of the Tuto Fela site, showing some of the stelae standing over the burials. The stelae are anthropomorphic, corresponding to the second phase of the cemetery. 2013,2034.16196 ©TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3703783&partId=1&searchText=2013,2034.16196&view=list&page=1 - sys: id: 5NnJiqSSNGkOuooYIEYIWO created_at: !ruby/object:DateTime 2015-11-25 18:25:38.253000000 Z updated_at: !ruby/object:DateTime 2018-05-15 16:01:28.688000000 Z content_type_id: image revision: 2 image: sys: id: 5N30tsfHVuW0AmIgeQo8Kk created_at: !ruby/object:DateTime 2015-11-25 18:01:40.103000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:01:40.103000000 Z title: ETHTBU0050002 description: url: "//images.ctfassets.net/xt8ne4gbbocd/5N30tsfHVuW0AmIgeQo8Kk/ad2ce21e5a6a89a0d4ea07bee897b525/ETHTBU0050002.jpg" caption: Back of the Tiya stelae, showing the graves attached to them. 2013,2034.16345 ©TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3704130&partId=1&searchText=2013,2034.16345&view=list&page=1 - sys: id: 66kOG829XiiESyKSYUcOkI created_at: !ruby/object:DateTime 2015-11-25 18:29:40.626000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:29:40.626000000 Z content_type_id: chapter revision: 1 title_internal: 'Stela: thematic, chapter 4' body: 'The Ethiopian stelae show a great variability in shapes and decorations, but at least three main groups could be defined. The first corresponds to the so-called phallic stelae, long cylindrical stones with a hemispherical top delimited by a groove or ring (Jossaume 2012: 97). The body of the stela is sometimes decorated with simple geometric patterns. A second type is known as anthropomorphic, with the top of the piece carved to represent a face and the rest of the piece decorated with crossed patterns. These two types are common to the east of the Rift Valley lakes, while to the south of Addis Ababa and to the west of these lakes several other types are present, most of them representing anthropomorphs but sometimes plain instead of cylindrical. These figures are usually classified depending on the shape and especially the features engraved on them –masks, pendants, swords- with the most lavishly carved considered the most recent. Probably the best known group is that with swords represented, such as those of Tiya, characterized by plain stones in which groups of swords (up to nineteen) are depicted along with dots and other unidentified symbols. Not all the stelae have these weapons, although those that don’t are otherwise identical in shape and have other common signs engraved on them. Regarding their chronology the Ethiopian stela seem to be relatively new, dated from the 10th to the 13th centuries, sometimes with one type of stela superimposed on another and in other cases with old types being reused in later tombs.' - sys: id: 66jbDvBWhykGwIOOmaYesY created_at: !ruby/object:DateTime 2015-11-25 18:26:18.279000000 Z updated_at: !ruby/object:DateTime 2018-05-15 16:04:13.365000000 Z content_type_id: image revision: 4 image: sys: id: 5Bpxor1k1GMmUOoEWWqK2k created_at: !ruby/object:DateTime 2015-11-25 18:02:34.437000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:02:34.437000000 Z title: ETHSOD0050002 description: url: "//images.ctfassets.net/xt8ne4gbbocd/5Bpxor1k1GMmUOoEWWqK2k/a6ec0e80da1e2b1c7cecdf2ee7951b9e/ETHSOD0050002.jpg" caption: Example of a phallic cylindrical stela, Gido Wamba, Ethiopia. 2013,2034.16290 ©TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3703913&partId=1&searchText=2013,2034.16290&&page=1 - sys: id: 3gftSkoIHSsmeCU6M8EkcE created_at: !ruby/object:DateTime 2015-11-25 18:27:02.886000000 Z updated_at: !ruby/object:DateTime 2018-05-15 16:06:02.999000000 Z content_type_id: image revision: 2 image: sys: id: 6WDEsfzmqQGkyyGImgYmcU created_at: !ruby/object:DateTime 2015-11-25 18:02:24.547000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:02:24.547000000 Z title: ETHTBU0050025 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6WDEsfzmqQGkyyGImgYmcU/5055128d6e0e0b51216e0daeb59c6728/ETHTBU0050025.jpg" caption: Examples of a plain stela with swords at Tiya, Ethiopia. 2013,2034.16365 ©TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3704110&partId=1&searchText=2013,2034.16365&page=1 - sys: id: 41cBMB2SpOEqy0m66k64Gc created_at: !ruby/object:DateTime 2015-11-25 18:29:58.521000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:29:58.521000000 Z content_type_id: chapter revision: 1 title_internal: 'Stela: thematic, chapter 5' body: 'Regardless of their chronology and shape, most of the stela seem to have a funerary function, marking the tombs of deceased which were buried in cemeteries sometimes reaching hundreds of graves. The information collected from sites of such as Tuto Fela show that not all the burials had an attached stela, and considering the amount of work necessary to prepare them those which had could be interpreted as belonging to high status people. In some cases, such as in Tiya, it seems evident that the stela marked the graves of important personalities within their communities. It is difficult to determine who the groups that carved these stelae were, but given their chronology it seems that they could have been Cushitic or Nilotic-speaking pastoralist communities absorbed by the Oromo expansion that took place in the sixteenth century. A lot of research has still to be done about these graveyards and their associated living spaces, and undoubtedly many groups of stelae are yet to be discovered. Those studied show, however, the potential interest of ancient communities still poorly known but which were able to develop complex societies and these material expressions of authority and power. ' - sys: id: 5DJsnYIbRKiAiOqYMWICau created_at: !ruby/object:DateTime 2015-11-25 18:27:29.739000000 Z updated_at: !ruby/object:DateTime 2018-05-15 16:07:15.282000000 Z content_type_id: image revision: 2 image: sys: id: 5zepzVfNDiOQy8gOyAkGig created_at: !ruby/object:DateTime 2015-11-25 18:02:34.369000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:02:34.369000000 Z title: ETHTBU0010003 description: url: "//images.ctfassets.net/xt8ne4gbbocd/5zepzVfNDiOQy8gOyAkGig/3131691f0940b7f5c823ec406b1acd03/ETHTBU0010003.jpg" caption: Stela graveyard in Meskem. 2013,2034.16330 ©TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3704143&partId=1&searchText=2013,2034.16330&page=1 citations: - sys: id: 6LBJQl0eT62A06YmiSqc4W created_at: !ruby/object:DateTime 2015-11-25 18:28:00.511000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:28:00.511000000 Z content_type_id: citation revision: 1 citation_line: | <NAME> (dir.) (1995): *Tiya, l'Éthiopie des Mégalithes, du Biface a l'Art Rupestre dans la Corne d'Afrique*. Paris, UNESCO/CNS. <NAME>. (2007): Tuto Fela et les stèles du sud de l'Ethiopie. Paris, Éditions recherche sur les civilisations. <NAME>. (2012): The Superimposed Cemeteries of Tuto Fela in Gedeo Country (Ethiopia), and Thoughts on the Site of Chelba-Tutitti. *Palethnology*, 4, 87-110. background_images: - sys: id: 3HHuQorm12WGUu0kC0Uce created_at: !ruby/object:DateTime 2015-11-25 18:02:09.630000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:02:09.630000000 Z title: ETHTBU0080002 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3HHuQorm12WGUu0kC0Uce/cf9d160fced55a45a8cb0cc9db8cbd54/ETHTBU0080002.jpg" - sys: id: 5zepzVfNDiOQy8gOyAkGig created_at: !ruby/object:DateTime 2015-11-25 18:02:34.369000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:02:34.369000000 Z title: ETHTBU0010003 description: url: "//images.ctfassets.net/xt8ne4gbbocd/5zepzVfNDiOQy8gOyAkGig/3131691f0940b7f5c823ec406b1acd03/ETHTBU0010003.jpg" country_introduction: sys: id: 2DBcI8BWaU6mcgAKK6KCsE created_at: !ruby/object:DateTime 2015-11-26 18:31:41.871000000 Z updated_at: !ruby/object:DateTime 2015-12-07 13:43:18.317000000 Z content_type_id: country_information revision: 3 title: 'Somalia/ Somaliland: country introduction' chapters: - sys: id: 1KQNUoZNrCkAQ2SymEAMC created_at: !ruby/object:DateTime 2015-11-26 18:26:17.254000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:26:17.254000000 Z content_type_id: chapter revision: 1 title: Introduction title_internal: 'Somalia: country, chapter 1' body: Somalia is a country located at the corner of the Horn of Africa, bordered by Djibouti, Ethiopia and Kenya. Somaliland self-declared independence from Somalia in 1991 although the government of Somalia has not recognised this and views it as an autonomous region. A cultural and economic crossroads between Middle East, Africa and Asia, this area has historically been the centre of trade routes that linked these regions. It also has a very rich rock art heritage which has only recently been started to be studied in depth. Most of the known depictions correspond to painted or engraved cattle scenes, often accompanied by human figures, dogs and other domestic animals, although some warriors, camels and geometric symbols (sometimes interpreted as tribal marks) are common too. - sys: id: 3dA1xqkTa0mKwo2mQcASWm created_at: !ruby/object:DateTime 2015-11-26 18:23:03.983000000 Z updated_at: !ruby/object:DateTime 2018-05-17 16:37:53.141000000 Z content_type_id: image revision: 2 image: sys: id: 4n4aYQQ3ws86seSuSQC2Q0 created_at: !ruby/object:DateTime 2015-11-26 18:17:32.780000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:17:32.780000000 Z title: '2013,1023.15855' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4n4aYQQ3ws86seSuSQC2Q0/dbb3602a28b6144aa4c317fe75196363/SOMLAG0030004.jpg" caption: Figure of painted cattle and human figures, with a semi-desert plain in the background. <NAME>, Somaliland. 2013,1023.15855 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3691566&partId=1&people=197356&place=41067%7c27048%7c1665&view=list&page=2 - sys: id: 2OBCFk5x3OmouqCga48C8U created_at: !ruby/object:DateTime 2015-11-26 18:26:58.643000000 Z updated_at: !ruby/object:DateTime 2017-01-11 14:18:51.197000000 Z content_type_id: chapter revision: 2 title: Geography and rock art distribution title_internal: 'Somalia: country, chapter 2' body: 'The geography of Somaliland is characterized by a coastal semi-desert plain which runs parallel to the Gulf of Aden coast, crossed by seasonal rivers (wadis) which make possible some grazing during the rainy season. Farther to the south, this semi-desert plain gives rise to the Karkaar Mountains. These mountains, which run from Somaliland into the region of Puntland in Somalia, have an average height of 1800 meters above sea level and run west to east until Ras Caseyr (Cape Guardafui) where the north and east coasts of the Horn of Africa meet. Southward to the mountains there is a big, dry plateau known as the Ogo, whose western part (the Haud) is one of the few good grazing areas in the country. The Ogo plateau occupies much of central and eastern Somalia, which to the south is characterized by the two only permanent rivers in the country, the Jubba and the Shabeele, born in the Ethiopian highlands and running to the south. Regarding rock art, the distribution of the known rock art sites shows a high concentration in Somaliland, with only some sites located to the south in the Gobolka Hiiraan region. However, this distribution could be a result of lack of research in other areas. ' - sys: id: 2OM3VEqOV2esQye48QAu2s created_at: !ruby/object:DateTime 2015-11-26 18:23:30.937000000 Z updated_at: !ruby/object:DateTime 2017-01-11 14:21:01.481000000 Z content_type_id: image revision: 2 image: sys: id: 2mLUneHM24eEYEQ8W4EKsq created_at: !ruby/object:DateTime 2015-11-26 18:18:00.392000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:18:00.392000000 Z title: '2013,2034.15623' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2mLUneHM24eEYEQ8W4EKsq/53eef5b06e2341da0768225d38e7847c/SOMGABNAS010005.jpg" caption: Semi-desert landscape in Somaliland. Dhaga Koure. 2013,2034.15623 © TARA/<NAME> col_link: http://bit.ly/2jDoZeS - sys: id: 41tEkwH3cIckAgeM0MaO6o created_at: !ruby/object:DateTime 2015-11-26 18:27:28.491000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:27:28.491000000 Z content_type_id: chapter revision: 1 title: Research history title_internal: 'Somalia: country, chapter 3' body: A reconstruction of rock art research history is challenging due to its contemporary history. To begin with, during the colonial period the country was divided in three different territories (British, Italian and French) with very different trajectories, until 1960 when the British and Italian territories joined to create Somalia. In British Somaliland the first studies of rock art were carried out by <NAME> and <NAME> in the 1940s, and the first general overview was published in 1954 by <NAME>, as a part of a regional synthesis of the Horn of Africa prehistory, followed by limited research done by Italians in the north-east region in the late 1950s. Since then, research has been limited, with some general catalogues published in the 1980s and 1990s, although political instability has often prevented research, especially in the south-eastern region of Somalia. In fact, most rock art information comes from wider regional syntheses dedicated to the Horn of Africa. In the early 2000’s the discovery of the Laas Geel site led to a renewed interest in rock art in Somaliland, which has allowed a more systematic study of archaeological sites. Nowadays, about 70 of these sites have been located only in this area, something which shows the enormous potential of rock art studies in the Horn of Africa. - sys: id: 4w2Oo8iJG0A6a6suMusm8c created_at: !ruby/object:DateTime 2015-11-26 18:24:00.701000000 Z updated_at: !ruby/object:DateTime 2017-01-11 14:22:27.659000000 Z content_type_id: image revision: 2 image: sys: id: 3mWyGCLGFacW2aOUYmGQWs created_at: !ruby/object:DateTime 2015-11-26 18:19:01.529000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:19:01.529000000 Z title: '2013,2034.16100' description: url: "//images.ctfassets.net/xt8ne4gbbocd/3mWyGCLGFacW2aOUYmGQWs/066214022447d9fbe76ff624e2887a57/SOMLAG0100001.jpg" caption: View of engraved cattle with lyre-like horns and marked udders. Laas Geel. 2013,2034.16100© TARA/<NAME> col_link: http://bit.ly/2j68Ld2 - sys: id: 4gYGUVBkbKwWYqUwAsMs0U created_at: !ruby/object:DateTime 2015-11-26 18:27:53.242000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:27:53.242000000 Z content_type_id: chapter revision: 1 title: Themes title_internal: 'Somalia: country, chapter 4' body: The rock art has traditionally been ascribed to the so-called Ethiopian-Arabican style, a term coined by <NAME> in 1971 to remark the strong stylistic relationship between the rock art found in the Horn of Africa and the Arabian Peninsula. According to this proposal, there was a progressive evolution from naturalism to schematism, perceptible in the animal depictions throughout the region. Wild animals seem to be largely absent but for Djibouti, while cattle depictions seem to have been fundamental elsewhere, either isolated or in herds. Such is the case with rock art in this region, where cows and bulls are the most common depictions, in many cases associated to human figures in what seems to be reverential or ritual scenes. In some of the sites, such as Laas Geel, the necks of the cows have been decorated with complex geometric patterns interpreted as a kind of mat used in special occasions to adorn them. - sys: id: LmEAuSwhEG6iuQ6K8CioS created_at: !ruby/object:DateTime 2015-11-26 18:24:22.355000000 Z updated_at: !ruby/object:DateTime 2017-01-11 14:26:37.550000000 Z content_type_id: image revision: 2 image: sys: id: 10vxtVrFIcuoaww8gEKCSY created_at: !ruby/object:DateTime 2015-11-26 18:19:22.576000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:19:22.576000000 Z title: '2013,2034.15935' description: url: "//images.ctfassets.net/xt8ne4gbbocd/10vxtVrFIcuoaww8gEKCSY/c4d210b0ddd69dd44e5bcd59cdecc875/SOMLAG0070012.jpg" caption: View of painted cattle and human figures. Laas Geel, Somaliland. 2013,2034.15935 © TARA/<NAME> col_link: http://bit.ly/2jiF5XI - sys: id: 2twRKjr52EwkSI0UMUIws4 created_at: !ruby/object:DateTime 2015-11-26 18:28:12.916000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:28:12.916000000 Z content_type_id: chapter revision: 1 title_internal: 'Somalia: country, chapter 5' body: Along with cattle, other animals were represented (humped cows or zebus, dogs, sheep, dromedaries), although to a much lesser extent. Wild animals are very rare, but giraffes have been documented in Laas Geel and elephants and antelopes in Tug Gerbakele, and lions are relatively common in the schematic, more modern depictions. Human figures also appear, either distributed in rows or isolated, sometimes holding weapons. Geometric symbols are also common, usually associated with other depictions. In Somalia, these symbols have often been interpreted as tribal or clan marks. With respect to techniques, both engraving and painting are common, although paintings seem to be predominant. - sys: id: 2gSkte21PuqswWM2Q804gi created_at: !ruby/object:DateTime 2015-11-26 18:24:47.061000000 Z updated_at: !ruby/object:DateTime 2017-01-12 16:00:51.600000000 Z content_type_id: image revision: 2 image: sys: id: 20zCz4hAbmiSm0MuGIkGQk created_at: !ruby/object:DateTime 2015-11-26 18:19:38.412000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:19:38.412000000 Z title: '2013,2034.15386' description: url: "//images.ctfassets.net/xt8ne4gbbocd/20zCz4hAbmiSm0MuGIkGQk/d36ff89e5284f1536daa5c3c82e345be/SOMDHA0020008.jpg" caption: Panel or relatively modern chronology showing painted white camels, unidentified quadrupeds and signs. <NAME>, Somaliland. 2013,2034.15386© TARA/<NAME> col_link: http://bit.ly/2j4Q3Ar - sys: id: 5QuYRZm7SMewQCgO0g2sE2 created_at: !ruby/object:DateTime 2015-11-26 18:28:43.949000000 Z updated_at: !ruby/object:DateTime 2015-12-11 12:13:57.212000000 Z content_type_id: chapter revision: 2 title: Chronology title_internal: 'Somalia: country, chapter 6' body: As in many other places, the establishment of accurate chronologies for Somaliland rock art is challenging. In this case, the lack of long term research has made things more difficult, and most hypotheses have been based in stylistic approaches, analysis of depictions and a small set of radiocarbon data and archaeological excavations. According to this, the oldest depictions could be dated to between the mid-3rd and the 2rd millennium BC, although older dates have been proposed for Laas Geel. This phase would be characterized by humpless cows, sheep and goats as well as wild animals. These sites would indicate the beginning of domestication in this region, the cattle being as a fundamental pillar of these communities. From this starting point the relative antiquity of the depictions would be marked by a tendency to schematism, visible in the superimpositions of several rock art sites. The introduction of camels would mark a chronology of the end of the first millennium BC, while the date proposed for the introduction of zebus (humped cows) should be placed at between the 1st Centuries BC and AD. - sys: id: 5Qtce93TSEks2Ukmks8e4E created_at: !ruby/object:DateTime 2015-11-26 18:25:07.168000000 Z updated_at: !ruby/object:DateTime 2017-01-12 16:24:38.017000000 Z content_type_id: image revision: 2 image: sys: id: 22wpEosKyYwyycaMgSmQMU created_at: !ruby/object:DateTime 2015-11-26 18:21:17.860000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:21:17.860000000 Z title: '2013,2034.15564' description: url: "//images.ctfassets.net/xt8ne4gbbocd/22wpEosKyYwyycaMgSmQMU/526e6ce44e5bf94379b55b2551a44b18/SOMGAB0050003.jpg" caption: Humped white cow. <NAME>, Somaliland. 2013,2034.15564 © TARA/David Coulson col_link: http://bit.ly/2ikqWb2 - sys: id: uPwtnjPhmK6y4kUImq4g8 created_at: !ruby/object:DateTime 2015-11-26 18:29:03.262000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:29:03.262000000 Z content_type_id: chapter revision: 1 title_internal: 'Somalia: country, chapter 7' body: Since the 1st millennium BC human figures armed with lances, bows and shields start to appear alongside the cattle, in some cases distributed in rows and depicting fighting scenes against other warriors or lions. The moment when this last period of rock art ended is unknown, but in nearby Eritrea some of these figures were depicted with firearms, thus implying that they could have reached a relatively modern date. - sys: id: PLXVZ70YMuKQuMOOecEIi created_at: !ruby/object:DateTime 2015-11-26 18:25:31.222000000 Z updated_at: !ruby/object:DateTime 2018-09-19 15:23:32.358000000 Z content_type_id: image revision: 3 image: sys: id: 4njSKDcdtuaCGiSKGKmGEa created_at: !ruby/object:DateTime 2015-11-26 18:21:32.901000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:21:32.901000000 Z title: '2013,2034.15617' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4njSKDcdtuaCGiSKGKmGEa/04b2b2ab0529ebec8831b47816d7f5f2/SOMGAB0090007.jpg" caption: 'Detail of painted rock art depicting two human figures and a humped cow, infilled in red and yellow. <NAME>houre, Somaliland. 2013,2034.15616 © TARA/<NAME> ' col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3711116&partId=1&searchText=2013,2034.15616+&page=1 citations: - sys: id: 62GO9AUWhq0GgwQC6keQAU created_at: !ruby/object:DateTime 2015-11-26 18:32:25.937000000 Z updated_at: !ruby/object:DateTime 2015-12-11 12:13:02.046000000 Z content_type_id: citation revision: 2 citation_line: | <NAME>. (1998): Contributo alla conoscenza dell’arte rupestre somala. *Rivista di Scienze Prehistoriche*, 49 (225-246). <NAME>. (1954): *The Prehistoric Cultures of the Horn of Africa*. Octagon Press, New York. <NAME>. (2015), Mapping the Archaeology of Somaliland: Religion, Art, Script, Time, Urbanism, Trade and Empire, *African Archaeological Review* 32(1): 111-136. background_images: - sys: id: 2RyEtF6eyI6q64Okqw2gOu created_at: !ruby/object:DateTime 2015-11-30 14:10:44.866000000 Z updated_at: !ruby/object:DateTime 2015-11-30 14:10:44.866000000 Z title: SOMGABNAS010038 description: url: "//images.ctfassets.net/xt8ne4gbbocd/2RyEtF6eyI6q64Okqw2gOu/7baa1a334726754b1f75ae5e2808eea0/SOMGABNAS010038.jpg" - sys: id: 1iKLJilSqIewGKAe0CuISa created_at: !ruby/object:DateTime 2015-11-30 14:10:53.312000000 Z updated_at: !ruby/object:DateTime 2015-11-30 14:10:53.312000000 Z title: SOMGAB0060011 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1iKLJilSqIewGKAe0CuISa/82fe8243484eca99a44beae93abc7ec0/SOMGAB0060011.jpg" - sys: id: 2kSvSjWnmQ46yGyeOCkioQ created_at: !ruby/object:DateTime 2015-11-30 14:11:00.915000000 Z updated_at: !ruby/object:DateTime 2015-11-30 14:11:00.915000000 Z title: SOMLAG0090043 description: url: "//images.ctfassets.net/xt8ne4gbbocd/2kSvSjWnmQ46yGyeOCkioQ/9ca0920f42ca2603f508a669e93a3b99/SOMLAG0090043.jpg" region: Eastern and central Africa ---<file_sep>/_coll_country_information/nigeria-country-introduction.md --- contentful: sys: id: 1yZL5vCVKkSw0ue6EqCgm0 created_at: !ruby/object:DateTime 2017-12-12 00:55:17.028000000 Z updated_at: !ruby/object:DateTime 2017-12-12 00:55:17.028000000 Z content_type_id: country_information revision: 1 title: 'Nigeria: country introduction' chapters: - sys: id: 3fiSQDTIRakyMIookukQGA created_at: !ruby/object:DateTime 2017-11-16 17:47:22.283000000 Z updated_at: !ruby/object:DateTime 2017-11-17 17:49:16.694000000 Z content_type_id: chapter revision: 2 title: Introduction title_internal: 'Nigeria: country, chapter 1' body: In general, West Africa is not well known for its painted or engraved rock art and does not have a long history of rock art research. The scarcity of paintings may be predicated on the topography and more humid conditions of the climate, but the shortage of discovered sites to date may indicate that the paucity of evidence is genuine. Painted rock art occurs in the north of the country and comprises humpless cattle, monkeys, antelope and human figures, mainly painted in red. More unique sculptural forms include standing stones engraved with stylised faces and codified motifs, found to the south, and are reminiscent of the burial stelae at [Tuto Fela in Ethiopia](http://africanrockart.britishmuseum.org/#/article/country-of-standing-stones "Standing Stones of Ethiopia"). - sys: id: 2TEEwkKGBWa648eEAeik8O created_at: !ruby/object:DateTime 2017-11-17 17:51:57.172000000 Z updated_at: !ruby/object:DateTime 2017-11-17 17:51:57.172000000 Z content_type_id: chapter revision: 1 title: Geography and rock art distribution title_internal: 'Nigeria: country, chapter 2' body: Located in West Africa, the Federal Republic of Nigeria shares land borders with Benin in the west, Chad and Cameroon in the east, and Niger in the north. Its coastline lies in the south on the Gulf of Guinea in the Atlantic Ocean. The Niger and Benue River valleys make up Nigeria's most extensive region, merging into each other to form a distinctive 'Y' shape confluence. - sys: id: 5j33Z322RiqSIkgEa6W0MC created_at: !ruby/object:DateTime 2017-11-22 15:44:24.402000000 Z updated_at: !ruby/object:DateTime 2017-11-22 15:44:24.402000000 Z content_type_id: image revision: 1 image: sys: id: 1wpXiaFLE8kImw6a4O0yO8 created_at: !ruby/object:DateTime 2017-11-22 15:43:09.652000000 Z updated_at: !ruby/object:DateTime 2017-11-22 15:43:09.652000000 Z title: NIGCRMNAS0010006 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1wpXiaFLE8kImw6a4O0yO8/a299524cd0c60d521815d02eb3347c2f/NIGCRMNAS0010006.jpg" caption: View looking east from the Ikom area towards Cross River and the Cameroon border. 2013,2034.24321 © TARA/<NAME> - sys: id: 4JWHrIYC4UgkUe2yqco4Om created_at: !ruby/object:DateTime 2017-11-22 15:56:27.091000000 Z updated_at: !ruby/object:DateTime 2017-11-22 16:05:16.491000000 Z content_type_id: chapter revision: 2 title_internal: 'Nigeria: country, chapter 3' body: 'Nigeria boasts a variety of landscapes - mangrove forests and swamps border the southern coastline; plains rise to the north of the valleys; rugged highlands are located in the southwest and to the southeast of the Benue River; hills and mountains extend to the border with Cameroon. Between the far south and far north is a vast savannah made up of three zones: the Guinean forest-savanna mosaic, the Sudanian savannah, and the Sahel savannah. Painted rock art is located in the northwest of the country, in the savannah zone, while engraved standing stones can be found in the more forested southeast.' - sys: id: 3kIQbhZ4xOgKeKqEwuoeOg created_at: !ruby/object:DateTime 2017-11-22 16:23:30.974000000 Z updated_at: !ruby/object:DateTime 2017-11-22 16:23:30.974000000 Z content_type_id: image revision: 1 image: sys: id: 6EygE2u9DUWkOAmoMayOQQ created_at: !ruby/object:DateTime 2017-11-22 16:21:19.288000000 Z updated_at: !ruby/object:DateTime 2017-11-22 16:21:19.288000000 Z title: NIGCRMNAS0010004 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6EygE2u9DUWkOAmoMayOQQ/b02ac0c0e9384d4c9e144434e63e8369/NIGCRMNAS0010004.jpg" caption: Boatman at Ofun-Nta, a seaport during the early years of trade on the Cross River. 2013,2034.24319 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/search.aspx?people=197356&place=37854 - sys: id: 8Gp0HoIrfiQUQGaMKmwO2 created_at: !ruby/object:DateTime 2017-11-22 16:56:06.115000000 Z updated_at: !ruby/object:DateTime 2017-11-22 16:56:06.115000000 Z content_type_id: chapter revision: 1 title: History of the research title_internal: 'Nigeria: country, chapter 4' body: | The existence of carved standing stones in Cross River State was first reported by an Officer of the British Administration in 1905 (Allison, 1967). In the 1960s, <NAME> undertook extensive surveying in the area, resulting in a major publication by the Nigerian Department of Antiquities in 1968. Research was undertaken in the run up to the Nigerian Civil War (also known as the Biafran War 1967-1970), during the course of which many of the monoliths were stolen and made their way on the international antiquities market. Today a number of these monoliths can be found in American and European museums, including [an example](http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=611818&partId=1&searchText=ikom&images=on&page=1) from the British Museum. The painted rock art found in the northeastern region of the country was first systematically studied and documented in the late 1950s. In 1964, the site of <NAME>, in present-day Jigawa State was declared a National Historical Monument, as a means to promote tourism in the country. Unfortunately, criticism that the site has not been well-maintained or managed has impeded tourism development (Mangut and Mangut, 2012:37). - sys: id: Bhiu5cJqUgQCmwWuIMsKG created_at: !ruby/object:DateTime 2017-12-12 00:29:36.099000000 Z updated_at: !ruby/object:DateTime 2017-12-12 00:29:36.099000000 Z content_type_id: chapter revision: 1 title: Themes title_internal: 'Nigeria: country, chapter 5' body: "Painted rock art sites in northern Nigeria are often located adjacent to lithophones, also known as rock gongs - these are rocks and boulders that were used as percussion instruments. Painted rock art and lithophones occur systematically at Birnin Kudu, “where the lithophones produce eleven different notes“ and are associated with female rituals that precede marriage (Le Quellec, 2004:74). Depictions consist of humpless cattle and sheep as well as geometric signs. Although the original artists and meaning of the rock art are not known, local communities recognise them today as sacred sites and the images are thought to be associated with [shamanic activities](http://www.bradshawfoundation.com/africa/nigeria/birnin_kudu/index.php \"Documenting Rock Art in Nigeria Bradshaw Foundation\"). \n\nIn northern Nigeria, the painted rock art at Shira in Bauchi State consists of two traditions: naturalistic, consisting of humans and cattle with suckling calves, and anthropomorphic images. Paintings are usually executed in dark red on steep rock faces or overhangs (Mangut and Mangut, 2012:36). Anthropomorphic images have been found nearby at Geji and Birnin Kudu, and are associated with marriage and initiation (Vaughan, 1962). Also at Geji, subject matter is quite varied including humpless long-horned cattle, monkeys, horse, human figures and antelope. These are painted in three different styles, as solid figures, in outline, and outline and stripe (Mangut and Mangut, 2012:37).\n" - sys: id: F5aTJf3MqWMgUeuIsUMIY created_at: !ruby/object:DateTime 2017-12-12 00:47:57.513000000 Z updated_at: !ruby/object:DateTime 2017-12-12 00:47:57.513000000 Z content_type_id: chapter revision: 1 title: Meaning title_internal: 'Nigeria: country, chapter 6' body: | In the Marghi region, paintings are made with reddish clay that is found at the bottom of the river during the dry season. Cooked to enhance the brightness of the pigment it is mixed with karite butter. The clay is however rare and as such expensive, so poorer families replace the clay with charcoal ashes, resulting in black pigments. Thus, the differences seen in the colours used for rock paintings are “not related to chronology or symbolism but only to social status” (Le Quellec, 2004:77). Near Geji, there is a rock shelter known as <NAME>, that is visited by Fulani herders during the rainy season who peck the existing rock paintings to retrieve the pigment. The pigment is mixed with food for both humans and cattle and is consumed to protect “the fertility of the herd and the prosperity of the herders” (Le Quellec, 2004:77). The villagers of Geji did not presume these paintings had been made by humans but had appeared naturally from the rock, and if damaged or destroyed by pecking would reappear the next day (Le Quellec, 2004:79). Unfortunately, such practices have resulted in permanent damage or destruction of rock art. - sys: id: 5zxzzlmp2wSkAA82ukiEme created_at: !ruby/object:DateTime 2017-12-12 00:49:31.706000000 Z updated_at: !ruby/object:DateTime 2017-12-12 00:49:31.706000000 Z content_type_id: chapter revision: 1 title: Chronology title_internal: 'Nigeria: country, chapter 7' body: Based on the depictions of both long and short-horned humpless cattle at Birnin Kudu, it has been suggested that paintings predate the introduction of humped cattle into northern Nigeria, and may be at least a thousand years old (Shaw 1978). However, depictions of horse at Geji have been used to suggest that painted rock art in Nigeria are no earlier than the 15th century BC (Mangut and Mangut, 2012:38). The engraved standing stones at Cross River are thought to be up to 1500 years old. citations: - sys: id: 5XzFExCZYA4mKGY0ua6Iwc created_at: !ruby/object:DateTime 2017-12-12 00:54:17.136000000 Z updated_at: !ruby/object:DateTime 2017-12-12 00:54:17.136000000 Z content_type_id: citation revision: 1 citation_line: "<NAME>. 2014. ‘Beyond Anthropological and Associational discourse- interrogating the minimalism of Ikom Monoliths as concept and found object art’, in \n*Global Journal of Arts Humanities and Social Sciences*, Vol.2, Issue 1, pp.67-84.\n\nAllison P. 1967. *Cross River State Monoliths*. Lagos: Department of Antiquities, Federal Republic of Nigeria.\n\nEsu, <NAME>. and Ukata, S. 2012. ‘Enhancing the tourism value of Cross River state monoliths and stone circles through geo-mapping and ethnographic study (part 1)’, in *Journal of Hospitality Management and Tourism*, Vol. 3(6), pp. 106-116.\n\nLe Quellec, J-L. 2004. *Rock Art in Africa: Mythology and Legend*. Paris: Flammarion.\n\nMangut, J. and <NAME>. 2012. ‘Harnessing the Potentials of Rock Art Sites in Birnin Kudu, Jigawa State, Nigeria for Tourism Development’, in *Journal of Tourism and Heritage*, Vol.1 No. 1 pp: 36-42.\n\nShaw, T. 1978. *Nigeria its Archaeology and Early History*. London: Thames and\nHudson.\n\nUNESCO. 2007. ‘Alok Ikom Monoliths’ UNESCO [Online], Available at: http://whc.unesco.org/en/tentativelists/5173/\n\nVaughan J. H. 1962. ‘Rock paintings and Rock gong among the Marghi of\nNigeria’ in *Man*, 62, pp:49-52.\n\n\n" ---<file_sep>/_coll_country_information/niger-country-introduction.md --- contentful: sys: id: 3dMpIo4d4cQa2OI4me2ACQ created_at: !ruby/object:DateTime 2015-11-26 11:15:52.509000000 Z updated_at: !ruby/object:DateTime 2015-12-08 14:55:14.724000000 Z content_type_id: country_information revision: 4 title: 'Niger: country introduction' chapters: - sys: id: 1edWsVTqzcciiIAUaqYoG created_at: !ruby/object:DateTime 2015-11-26 11:03:04.104000000 Z updated_at: !ruby/object:DateTime 2017-01-09 16:49:15.950000000 Z content_type_id: chapter revision: 2 title: Introduction title_internal: 'Niger: country, chapter 1' body: Niger is geographically diverse, having both the Sahel (savannah) and the Sahara (desert). The majority of the country’s rock art – made up predominantly of engravings – is located in the northern desert area, in and around the Aïr Mountains, where some of the art is thought to be several thousand years old. The Djado Plateau in the north-east is also rich in art that includes both paintings and engravings. One of the most celebrated sites of rock engraving is at a place called Dabous, to the west of the mountains. Here, two life-size giraffe were carved on the top of an outcrop, and may be up to 6,000 years old. Other notable areas for engravings are Iwellene in the northern Aïr Mountains, where some of the art is thought to be several thousand years old, as well the sites of Tanakom and Tagueit in the south-eastern Aïr Mountains, where engravings are located on the sides of two wadis (dry riverbeds). - sys: id: 1E25PiKMde8CE8MgQIukKK created_at: !ruby/object:DateTime 2015-11-26 10:55:02.416000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:55:02.416000000 Z content_type_id: image revision: 1 image: sys: id: 2FAYj7hG88aQ0Quq6Wc6gE created_at: !ruby/object:DateTime 2015-11-26 10:54:16.151000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:54:16.151000000 Z title: '2013,2034.9967' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2FAYj7hG88aQ0Quq6Wc6gE/49ae0722057f453db4bb15da9c1ee6c0/2013_2034.9967.jpg" caption: Block-pecked engraving of running hare. 2013,2034.9967 © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3637684&partId=1&page=1 - sys: id: 1WQHiGltOAqm4oAc46YAme created_at: !ruby/object:DateTime 2015-11-26 11:03:35.303000000 Z updated_at: !ruby/object:DateTime 2015-11-26 11:03:35.303000000 Z content_type_id: chapter revision: 1 title_internal: 'Niger: country, chapter 2' body: Links have been made between the rock art of Niger and that of several other countries – in particular, between the so-called Libyan Warrior art found in the Aïr Mountains and the rock engravings of the Adrar des Iforas in Mali. Stylistic similarities also exist with some of the art of the Tadrart (Acacus) and in south-east Algeria. Further associations have been made between the Early Hunter art of the Djado Plateau and art in south-west Libya and south-east Algeria. Equally, similarities have been observed with the Tazina-style engravings in south-western Algeria and south-eastern Morocco. - sys: id: 5bPNREZcAMsO8SuecSaoQy created_at: !ruby/object:DateTime 2015-11-26 10:55:34.135000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:55:34.135000000 Z content_type_id: image revision: 1 image: sys: id: 4h5Sa7Ex2M2aEa8YSGW6iU created_at: !ruby/object:DateTime 2015-11-26 10:53:55.744000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:53:55.744000000 Z title: '2013,2034.8958' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4h5Sa7Ex2M2aEa8YSGW6iU/b394694db95c753013248a8e398017d4/2013_2034.8958.jpg" caption: Looking out of a shallow cave, Djado Plateau, Niger. 2013,2034.8958 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3637696&partId=1&page=1 - sys: id: 3OeKLV88XSow8C0iOKcqIg created_at: !ruby/object:DateTime 2015-11-26 11:04:29.851000000 Z updated_at: !ruby/object:DateTime 2015-12-07 17:12:48.554000000 Z content_type_id: chapter revision: 6 title: Geography and rock art distribution title_internal: 'Niger: country, chapter 3' body: "Covering an area of 1.267 million km², this landlocked country borders seven others. Its south-western borders flank the Niger River, with Burkina Faso, Benin and Nigeria to the south; its north-eastern borders touch the borders of Algeria, Libya and Chad in the central Sahara, and Mali to the west. The climate is mainly hot and dry with much of the country covered by the Sahara desert. In the extreme south, on the edges of the Sahel, the terrain is mainly shrub savannah.\n\nUnlike other regions in northern Africa, in the absence of a generally agreed chronology, scholars have categorised the rock art of Niger regionally and stylistically, making connections where possible with rock art of other regions. The rock art of Niger can be broadly divided into the following regions: \n" - sys: id: 516un196R2QI8MKOSMA6mW created_at: !ruby/object:DateTime 2015-12-07 17:13:15.478000000 Z updated_at: !ruby/object:DateTime 2015-12-07 17:13:15.478000000 Z content_type_id: chapter revision: 1 title_internal: Sub heading 1 body: '__Aïr Mountains (northern Niger)__ ' - sys: id: 57o3riQZdC2CE4IOSgoOke created_at: !ruby/object:DateTime 2015-11-26 10:56:09.992000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:56:09.992000000 Z content_type_id: image revision: 1 image: sys: id: 6wKZcUGktaAG0IYOagAIQ4 created_at: !ruby/object:DateTime 2015-11-26 10:54:26.849000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:54:26.849000000 Z title: '2013,2034.11147' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6wKZcUGktaAG0IYOagAIQ4/9ddabc2eb10161fcb2c69cff6817741a/2013_2034.11147.jpg" caption: Libyan Warrior figure, Western Aïr Mountains, Niger. 2013,2034.11147 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3637713&partId=1&museumno=2013,2034.11147&page=1 - sys: id: 5p9XKG2DjakmUkWuq6AuIK created_at: !ruby/object:DateTime 2015-11-26 11:05:00.923000000 Z updated_at: !ruby/object:DateTime 2015-12-08 14:54:12.049000000 Z content_type_id: chapter revision: 2 title_internal: 'Niger: country, chapter 4' body: Consisting predominantly of engravings, the majority of depictions in this region fall within the so-called Libyan Warrior period or style of art, dating from 1,500–3,000 years ago, characterised by forward-facing figures with metal weapons and horses. Approximately 1,000 engravings of warriors have been recorded from the Aïr Mountains in Niger, as well as the Adrar des Iforas in bordering Mali. Based on investigations into the garments worn, accessories, headdresses and weaponry, and by studying the placement and superimposition of images, it has been proposed that there are two main stages of this Libyan Warrior rock art. The oldest is linked to a pastoral economy based on cattle-rearing, when metal had been introduced to the region and the use of the spear took over from the traditional bow. This region also hosts images of wild animals such as Barbary sheep and ostrich, as well as cattle. - sys: id: 61yqtntiEMEgWW8iAAa4Ao created_at: !ruby/object:DateTime 2015-12-08 14:54:32.334000000 Z updated_at: !ruby/object:DateTime 2015-12-08 14:54:48.031000000 Z content_type_id: chapter revision: 2 title_internal: Sub heading 2 body: __Djado Plateau__ - sys: id: Kjmi6uh5U2aGEuI0ggoEw created_at: !ruby/object:DateTime 2015-11-26 10:56:33.929000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:56:33.929000000 Z content_type_id: image revision: 1 image: sys: id: 6yxgQFojbUcOUSwyaWwEMC created_at: !ruby/object:DateTime 2015-11-26 10:54:27.057000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:54:03.540000000 Z title: '2013,2034.8891' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3637764&partId=1&searchText=2013,2034.8891&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/6yxgQFojbUcOUSwyaWwEMC/5547eadfdf388937a8c708c145c2dba6/2013_2034.8891.jpg" caption: Two outline engravings of white rhinoceros. 2013,2034.8891 © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3637764&partId=1&museumno=2013,2034.8891&page=1 - sys: id: olpDz3t6DeY0qgiiCeIq created_at: !ruby/object:DateTime 2015-11-26 11:05:22.441000000 Z updated_at: !ruby/object:DateTime 2015-11-26 11:05:22.441000000 Z content_type_id: chapter revision: 1 title_internal: 'Niger: country, chapter 5' body: Here, both paintings and engravings occur. The earliest engravings include images of wild animals such as elephants, rhinoceros, giraffe and other game, and dated to the Early Hunter or Bubalus Period; human figures are very rare. Tazina-style engravings – similar to those found in south-eastern Morocco – also occur, as well as polychrome fine-line and finger paintings that are unique to this area. - sys: id: 5F6G6OVWSI4UOWmaq0ocqS created_at: !ruby/object:DateTime 2015-11-26 10:57:18.063000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:57:18.063000000 Z content_type_id: image revision: 1 image: sys: id: 2ANvzNqFfiKkMWAAsWCWKQ created_at: !ruby/object:DateTime 2015-11-26 10:54:26.916000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:54:26.916000000 Z title: '2013,2034.8960' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2ANvzNqFfiKkMWAAsWCWKQ/724f5a5d07a365fdf3b9040aa30d916c/2013_2034.8960.jpg" caption: White cows with calves and three figures. Djado Plateau, Niger. 2013,2034.8960 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3637694&partId=1&museumno=2013,2034.8960&page=1 - sys: id: 3qTgmBHVQc48E4WUuQgkGM created_at: !ruby/object:DateTime 2015-11-26 11:05:56.545000000 Z updated_at: !ruby/object:DateTime 2015-11-26 11:05:56.545000000 Z content_type_id: chapter revision: 1 title_internal: 'Niger: country, chapter 6' body: The number of cattle depictions is small, but particular images of calves attached to a lead can be compared stylistically with images of cattle in Tassili n’Ajjer, Algeria. Moreover, <NAME> noted the resemblance between these rock art depictions and the husbandry practices of the present day Wodaabe people of Niger, who use a similar calf rope. The calf rope (a long rope comprising loops within which the heads of the calves are secured) is both practical and symbolic, ensuring the cows always return to their home camp, while also physically dividing the camp into male and female halves. It is interesting to note the close relationship between the rock art of regions that today are politically discrete. - sys: id: dGrDTSq3Xqm06eis6sUkU created_at: !ruby/object:DateTime 2015-11-26 11:06:48.293000000 Z updated_at: !ruby/object:DateTime 2015-11-26 11:06:48.293000000 Z content_type_id: chapter revision: 1 title: History of rock art discovery in Niger title_internal: 'Niger: country, chapter 7' body: Until relatively recently rock art research has been sporadic in Niger. In the 1920s Major Gen. <NAME>, a British explorer and army officer, made two great expeditions into the Sahara. He was the first person to make a serious study of the Tuareg and documented some of the rock art in the Aïr Mountains. Subsequently, French colonial officers noted some sites around 1960. However, it was French archaeologist <NAME> who undertook major recording programmes throughout the 1960s and 1970s to document, trace and publish several thousand engravings. Very little information is known relating the rock art to known cultural groups, either past or present. Most of the sites were not habitation sites, and were probably only occasionally visited by nomadic societies in the past, so very little (if any) archaeological evidence remains. Most of the art predates the residence of the Tuareg, who now inhabit this area and who appear to have no direct connections with the art. The Tuareg recognise old script which sometimes accompanies images as it closely resembles their own writing, *Tifinagh*; however, it is incomprehensible to them if it is more than 100 years old. - sys: id: 2dnMaAI1RyUiEgWiY8SEsS created_at: !ruby/object:DateTime 2015-11-26 10:57:51.550000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:57:51.550000000 Z content_type_id: image revision: 1 image: sys: id: 5OBSH7pvt6I6eOAc4OaqEG created_at: !ruby/object:DateTime 2015-11-26 10:54:26.945000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:54:26.945000000 Z title: '2013,2034.10009' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5OBSH7pvt6I6eOAc4OaqEG/f667bce1cf4cf3c6dbce0bb5a83383bc/2013_2034.10009.jpg" caption: Large reground and painted figure surrounded by ancient Tifinagh script. Northern Air Mountains, Niger. 2013,2034.10009 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3637714&partId=1&museumno=2013,2034.10009&page=1 - sys: id: 37Cl8z71uMqYsoeyqyOegs created_at: !ruby/object:DateTime 2015-11-26 11:07:24.753000000 Z updated_at: !ruby/object:DateTime 2015-11-26 11:07:24.753000000 Z content_type_id: chapter revision: 1 title: Chronology title_internal: 'Niger: country, chapter 8' body: 'The relative chronology for rock art in Niger can be based, as in other Saharan regions, on stylistic classifications:' - sys: id: uNjAW1yrkW6iyE0iqcsQy created_at: !ruby/object:DateTime 2015-11-26 10:58:19.111000000 Z updated_at: !ruby/object:DateTime 2017-01-09 16:51:42.139000000 Z content_type_id: image revision: 2 image: sys: id: 1vncvc4BCIG8ymWeS8c28q created_at: !ruby/object:DateTime 2015-11-26 10:54:27.168000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:54:27.168000000 Z title: '2013,2034.9910' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1vncvc4BCIG8ymWeS8c28q/ee518eb244c2193ea827c7875b30c049/2013_2034.9910.jpg" caption: Block-pecked elephant. Northern Aïr Mountains, Niger. 2013,2034.9910 © TARA/<NAME> col_link: http://bit.ly/2iVcmsb - sys: id: 31SOSm8z04CU4MouUSUSQe created_at: !ruby/object:DateTime 2015-11-26 11:07:44.432000000 Z updated_at: !ruby/object:DateTime 2017-01-09 16:53:27.619000000 Z content_type_id: chapter revision: 2 title_internal: 'Niger: country, chapter 9' body: Early Hunter or Bubalus Period rock engravings are executed with deeply incised and smoothened lines, mainly depicting big game such as elephants, rhinoceros, giraffe and other game (with rhinoceros occurring most often), and are found on the Djado Plateau, as well as the Mangueni and Tchigai plateaux in north-east Niger. In the eastern Aïr Mountains, archaeological traces of human occupation during this early wet phase are evident, dating back 9,500 years. - sys: id: 2HafBWCAcMOYykSgSywEK6 created_at: !ruby/object:DateTime 2015-11-26 10:58:42.964000000 Z updated_at: !ruby/object:DateTime 2017-01-09 16:54:59.579000000 Z content_type_id: image revision: 2 image: sys: id: 2lW3L3iwz60ekeWsYKgOYC created_at: !ruby/object:DateTime 2015-11-26 10:54:26.852000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:53:07.945000000 Z title: '2013,2034.9786' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3637692 url: "//images.ctfassets.net/xt8ne4gbbocd/2lW3L3iwz60ekeWsYKgOYC/c303352ed0b0976a3f1508ea30b8a41d/2013_2034.9786.jpg" caption: Outline and decorated cattle, some with elaborate deliberately turned-back horns. 2013,2034.9786 © TARA/<NAME> col_link: http://bit.ly/2jlwIKc - sys: id: 2lLu5BCrhuiWA0eOUSkQYo created_at: !ruby/object:DateTime 2015-11-26 11:08:13.631000000 Z updated_at: !ruby/object:DateTime 2015-11-26 11:08:13.631000000 Z content_type_id: chapter revision: 1 title_internal: 'Niger: country, chapter 10' body: Although the Bovidian Period is sparsely represented in comparison to other rock art regions, both on the Djado Plateau and the Aïr Mountains, this period can probably be dated to between 7,000 and 4,000 years ago. A few cattle are depicted in a similar fashion to the big game of the Early Hunter Period, which raises the question of whether the nomadic cattle-herding culture emerged from a hunting lifestyle, or at least rapidly succeeded it. - sys: id: 6JJPeizRe0WiQIc2yOEaIY created_at: !ruby/object:DateTime 2015-11-26 10:59:13.005000000 Z updated_at: !ruby/object:DateTime 2017-01-09 17:03:18.580000000 Z content_type_id: image revision: 2 image: sys: id: 3nBXTYYPN6ucuaImm24iuG created_at: !ruby/object:DateTime 2015-11-26 10:54:30.823000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:54:30.823000000 Z title: '2013,2034.8834' description: url: "//images.ctfassets.net/xt8ne4gbbocd/3nBXTYYPN6ucuaImm24iuG/a188d0ae5e00e8934acbf0397ce50194/2013_2034.8834.jpg" caption: Outline Tazina-style engraving of a giraffe. 2013,2034.8834 © TARA/David Coulson col_link: http://bit.ly/2i9uPQ2 - sys: id: 6lPfzlhbskGkAcU6eiEuIQ created_at: !ruby/object:DateTime 2015-11-26 11:08:30.254000000 Z updated_at: !ruby/object:DateTime 2015-11-26 11:08:30.254000000 Z content_type_id: chapter revision: 1 title_internal: 'Niger: country, chapter 11' body: Engravings in the Tazina style are found on the Djado Plateau and have been likened to those in south-eastern Morocco. While dates in Niger are not generally agreed, the Tazina period in Morocco is dated from c.5,000–2,000 BC. - sys: id: 5cO6JFSdgQgQMIK8egwYwA created_at: !ruby/object:DateTime 2015-11-26 10:59:45.306000000 Z updated_at: !ruby/object:DateTime 2017-01-09 17:04:32.984000000 Z content_type_id: image revision: 2 image: sys: id: 2wvcOF7LOQa6iEsWyQOUQi created_at: !ruby/object:DateTime 2015-11-26 10:54:26.797000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:54:26.797000000 Z title: '2013,2034.9875' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2wvcOF7LOQa6iEsWyQOUQi/ba1af764bd58d195ef002f58cca5eb51/2013_2034.9875.jpg" caption: Libyan Warrior-style figures. Northern Aïr Mountains, Niger. 2013,2034.9875 © TARA/<NAME> col_link: http://bit.ly/2i6usdB - sys: id: 5s0XmNAWWIwwQ2m8q88AWe created_at: !ruby/object:DateTime 2015-11-26 11:00:12.745000000 Z updated_at: !ruby/object:DateTime 2017-01-09 17:05:53.718000000 Z content_type_id: image revision: 2 image: sys: id: 4fSRLSsTP2MCiquKAEsmkQ created_at: !ruby/object:DateTime 2015-11-26 10:54:26.833000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:54:26.833000000 Z title: '2013,2034.9430' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4fSRLSsTP2MCiquKAEsmkQ/ad620450f16447bcbb6e734d2a4c1c0e/2013_2034.9430.jpg" caption: Two horses attached to two-wheeled chariot with charioteer. Eastern Aïr Mountains, Niger. 2013,2034.9430 © TARA/<NAME> col_link: http://bit.ly/2i6uJ07 - sys: id: 5lN8CVda2AG6QAaeyI20O8 created_at: !ruby/object:DateTime 2015-11-26 11:08:51.981000000 Z updated_at: !ruby/object:DateTime 2015-12-08 14:57:22.081000000 Z content_type_id: chapter revision: 2 title_internal: 'Niger: country, chapter 12' body: Consisting predominantly of rock engravings and found in the Aïr Mountains, the Horse Period and Libyan Warrior Period date from around 3,000–1,500 years ago. Depictions are of horses with so-called Libyan Warriors, with metal weapons or with chariots and charioteers. Human figures, which often appear with horses, were sometimes depicted with elaborate apparel; others were drawn with stylized bodies consisting of two triangles joined at the apex. Wild animals such as Barbary sheep and ostrich, as well as cattle, appear in this art. Art of the Horse Period is not widely represented in the Djado Plateau, suggesting that Berber groups did not reach the region in any great numbers – but it has been proposed that certain peculiarities of style may suggest an influence from Aïr. - sys: id: IVnNUsnIeAcAiM42imyI4 created_at: !ruby/object:DateTime 2015-11-26 11:00:38.006000000 Z updated_at: !ruby/object:DateTime 2017-01-09 17:06:56.071000000 Z content_type_id: image revision: 2 image: sys: id: 2bO7Zt5qJ6UI088i422mMe created_at: !ruby/object:DateTime 2015-11-26 10:53:55.796000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:53:55.796000000 Z title: '2013,2034.9578' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2bO7Zt5qJ6UI088i422mMe/337784cf715978325ffb7bda8179c3ce/2013_2034.9578.jpg" caption: Crudely pecked camels. Eastern Aïr Mountains, Niger. 2013,2034.9578 © TARA/<NAME> col_link: http://bit.ly/2i9tto4 - sys: id: ZjY1WlFDm8uM2oycKygUa created_at: !ruby/object:DateTime 2015-11-26 11:09:10.217000000 Z updated_at: !ruby/object:DateTime 2015-11-26 11:09:10.217000000 Z content_type_id: chapter revision: 1 title_internal: 'Niger: country, chapter 13' body: A small number of engravings from the Camel Period occur on the Djado Plateau, but as camels were introduced to the Sahara up to 2,000 years ago, the relative lack of depictions suggests that the plateau was scarcely frequented during this hyper-arid period. citations: - sys: id: 23N5waXqbei8UswAuiGa8g created_at: !ruby/object:DateTime 2015-11-26 11:02:17.186000000 Z updated_at: !ruby/object:DateTime 2015-11-26 11:02:17.186000000 Z content_type_id: citation revision: 1 citation_line: |- <NAME>. ‘Sub-zone 3: Niger’, in *Rock art of Sahara and North Africa: Thematic study*. [ICOMOS](http://www.icomos.org/en/116-english-categories/resources/publications/222-rock-art-of-sahara-and-north-africa-thematic-study). <NAME>. 2003. ‘One Hundred Years of Archaeology in Niger’, *Journal of World Prehistory*, Vol. 17, No. 2, pp. 181-234 Muzzolini, Alfred.2001. ‘Saharan Africa’, in D.S. Whitley (ed.) *Handbook of Rock Art Research*. Walnut Creek, California: AltaMira Press, pp.605-636. Striedter, <NAME>.1993. ‘Rock Art research on the Djado Plateau (Niger): a Preliminary Report n Arkana’, in *Rock Art in the Old World*. Walnut Creek, (ed. Michel Lorblanchet). New Delhi: Indira Ghandi National Centre for the Arts, pp.113-128 ---<file_sep>/assets/vendor/tooltipster-follower/dist/js/tooltipster-follower.js /** * tooltipster-follower v0.1.5 * https://github.com/louisameline/tooltipster-follower/ * Developed by <NAME> * MIT license */ (function (root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module unless amdModuleId is set define(["tooltipster"], function (a0) { return (factory(a0)); }); } else if (typeof exports === 'object') { // Node. Does not work with strict CommonJS, but // only CommonJS-like environments that support module.exports, // like Node. module.exports = factory(require("tooltipster")); } else { factory(jQuery); } }(this, function ($) { var pluginName = 'laa.follower'; $.tooltipster._plugin({ name: pluginName, instance: { /** * @return {object} An object with the defaults options * @private */ __defaults: function() { return { anchor: 'top-left', maxWidth: null, minWidth: 0, offset: [15, -15] }; }, /** * Run once at instantiation of the plugin * * @param {object} instance The tooltipster object that instantiated this plugin * @return {self} * @private */ __init: function(instance) { var self = this; // list of instance variables self.__displayed; self.__helper; // the inition repositionOnScroll option value self.__initialROS = instance.option('repositionOnScroll'); self.__instance = instance; self.__latestMouseEvent; self.__namespace = 'tooltipster-follower-'+ Math.round(Math.random()*1000000); self.__openingTouchEnded; self.__pointerPosition; self.__previousState = 'closed'; self.__size; self.__options; // enable ROS (scrolling forces us to re-evaluate the window geometry) if (!self.__initialROS) { self.__instance.option('repositionOnScroll', true); } // initial formatting self.__optionsFormat(); // reformat every time the options are changed self.__instance._on('destroy.'+ self.__namespace, function() { self.__destroy(); }); // reformat every time the options are changed self.__instance._on('options.'+ self.__namespace, function() { self.__optionsFormat(); }); self.__instance._on('reposition.'+ self.__namespace, function(event) { self.__reposition(event.event, event.helper); }); // we need to register the mousemove events before the tooltip is actually // opened, because the event that will be passed to __reposition at opening // will be the mouseenter event, which is too old and does not reflect the // current position of the mouse self.__instance._on('start.'+ self.__namespace, function(event) { self.__instance._$origin.on('mousemove.'+ self.__namespace, function(e) { self.__latestMouseEvent = e; }); }); // undo the previous binding self.__instance._one('startend.'+ self.__namespace +' startcancel.'+ self.__namespace, function(event){ self.__instance._$origin.off('mousemove.'+ self.__namespace); // forget the event if (event.type == 'startcancel') { self.__latestMouseEvent = null; } }); self.__instance._on('state.'+ self.__namespace, function(event) { if (event.state == 'closed') { self.__close(); } else if (event.state == 'appearing' && self.__previousState == 'closed') { self.__create(); } self.__previousState = event.state; }); return self; }, /** * Called when the tooltip has closed * * @return {self} * @private */ __close: function() { // detach our content object first, so the next jQuery's remove() // call does not unbind its event handlers if (typeof this.__instance.content() == 'object' && this.__instance.content() !== null) { this.__instance.content().detach(); } // remove the tooltip from the DOM this.__instance._$tooltip.remove(); this.__instance._$tooltip = null; // stop listening to mouse moves $($.tooltipster._env.window.document).off('.'+ this.__namespace); // reset the event this.__latestMouseEvent = null; return this; }, /** * Contains the HTML markup of the tooltip and the bindings the should * exist as long as the tooltip is open * * @return {self} * @private */ __create: function() { var self = this, // note: we wrap with a .tooltipster-box div to be able to set a margin on it // (.tooltipster-base must not have one) $html = $( '<div class="tooltipster-base tooltipster-follower">' + '<div class="tooltipster-box">' + '<div class="tooltipster-content"></div>' + '</div>' + '</div>' ), $document = $($.tooltipster._env.window.document); // apply min/max width if asked if (self.__options.minWidth) { $html.css('min-width', self.__options.minWidth + 'px'); } if (self.__options.maxWidth) { $html.css('max-width', self.__options.maxWidth + 'px'); } self.__instance._$tooltip = $html; // not displayed until we have a mousemove event self.__displayed = false; self.__openingTouchEnded = false; $document.on('mousemove.'+ self.__namespace, function(event) { // don't follow the finger after the opening gesture has ended, if the tap // close trigger is used. However we cannot ignore the event if we are right // after the opening tap, since we must use to open it the first time if (!self.__openingTouchEnded || !self.__displayed) { self.__follow(event); } }); // This addresses the following situation: the user taps the tooltip open, then // taps somewhere else on the screen to close it. We'd expect the tooltip not to // move when the closing gesture is executed but it might be the case if the tap // is actually a touchstart+touchmove+touchend (which happens if the finger // slightly moves during the tap). Although it's only logical, we'll prevent it // as it would likely be unexpected by everyone. To do that, we'll unbind our // "move" listener when the opening gesture ends (if it even was a gesture that // opened the tooltip). var triggerClose = self.__instance.option('triggerClose'); if (triggerClose.tap) { // this will catch an opening tap event since we have (supposedly) been called // upon the event on the origin and it has not bubbled to the document yet $document.on('touchend.'+ self.__namespace + ' touchcancel.'+ self.__namespace, function(event) { // we're not using a timeout to remove the mousemove listener since it // break things for an unknown reason in Chrome mobile self.__openingTouchEnded = true; }); } // tell the instance that the tooltip element has been created self.__instance._trigger('created'); return self; }, /** * Called upon the destruction of the tooltip or the destruction of the plugin * * @return {self} * @private */ __destroy: function() { this.__instance._off('.'+ this.__namespace); if (!this.__initialROS) { this.__instance.option('repositionOnScroll', false); } return this; }, /** * Called when the mouse has moved. * * Note: this is less "smart" than sideTip, which tests scenarios before choosing one. * Here we have to be fast so the moving animation can stay fluid. So there will be no * constrained widths for example. * * @return {self} * @private */ __follow: function(event) { // store the event in case it's a method call that triggers this method next time, // or use the latest mousemove event if we have one. if (event) { this.__latestMouseEvent = event; } else if (this.__latestMouseEvent) { event = this.__latestMouseEvent; } if (event) { this.__displayed = true; var coord = {}, anchor = this.__options.anchor, offset = $.merge([], this.__options.offset); // the scroll data of the helper must be updated manually on mousemove when the // origin is fixed, because Tooltipster will not call __reposition on scroll, so // it's out of date. Even though the tooltip will be fixed too, we need to know // the scroll distance to determine the position of the pointer relatively to the // viewport this.__helper.geo.window.scroll = { left: $.tooltipster._env.window.scrollX || $.tooltipster._env.window.document.documentElement.scrollLeft, top: $.tooltipster._env.window.scrollY || $.tooltipster._env.window.document.documentElement.scrollTop }; // coord left switch (anchor) { case 'top-left': case 'left-center': case 'bottom-left': coord.left = event.pageX + offset[0]; break; case 'top-center': case 'bottom-center': coord.left = event.pageX + offset[0] - this.__size.width / 2; break; case 'top-right': case 'right-center': case 'bottom-right': coord.left = event.pageX + offset[0] - this.__size.width; break; default: console.log('Wrong anchor value'); break; } // coord top switch (anchor) { case 'top-left': case 'top-center': case 'top-right': // minus because the Y axis is reversed (pos above the X axis, neg below) coord.top = event.pageY - offset[1]; break; case 'left-center': case 'right-center': coord.top = event.pageY - offset[1] - this.__size.height / 2; break; case 'bottom-left': case 'bottom-center': case 'bottom-right': coord.top = event.pageY - offset[1] - this.__size.height; break; } // if the tooltip does not fit on the given side, see if it could fit on the // opposite one, otherwise put at the bottom (which may be moved again to the // top by the rest of the script below) if ( anchor == 'left-center' || anchor == 'right-center' ){ // if the tooltip is on the left of the cursor if (anchor == 'right-center') { // if it overflows the viewport on the left side if (coord.left < this.__helper.geo.window.scroll.left) { // if it wouldn't overflow on the right if (event.pageX - offset[0] + this.__size.width <= this.__helper.geo.window.scroll.left + this.__helper.geo.window.size.width) { // move to the right anchor = 'left-center'; // reverse the offset as well offset[0] = -offset[0]; coord.left = event.pageX + offset[0]; } else { // move to the bottom left anchor = 'top-right'; // we'll use the X offset to move the tooltip on the Y axis. Maybe // we'll make this configurable at some point offset[1] = offset[0]; coord = { left: 0, top: event.pageY - offset[1] }; } } } else { // if it overflows the viewport on the right side if (coord.left + this.__size.width > this.__helper.geo.window.scroll.left + this.__helper.geo.window.size.width) { var coordLeft = event.pageX - offset[0] - this.__size.width; // if it wouldn't overflow on the left if (coordLeft >= 0) { // move to the left anchor = 'right-center'; // reverse the offset as well offset[0] = -offset[0]; coord.left = coordLeft; } else { // move to the bottom right anchor = 'top-left'; offset[1] = -offset[0]; coord = { left: event.pageX + offset[0], top: event.pageY - offset[1] }; } } } // if it overflows the viewport at the bottom if (coord.top + this.__size.height > this.__helper.geo.window.scroll.top + this.__helper.geo.window.size.height) { // move up coord.top = this.__helper.geo.window.scroll.top + this.__helper.geo.window.size.height - this.__size.height; } // if it overflows the viewport at the top if (coord.top < this.__helper.geo.window.scroll.top) { // move down coord.top = this.__helper.geo.window.scroll.top; } // if it overflows the document at the bottom if (coord.top + this.__size.height > this.__helper.geo.document.size.height) { // move up coord.top = this.__helper.geo.document.size.height - this.__size.height; } // if it overflows the document at the top if (coord.top < 0) { // no top document overflow coord.top = 0; } } // when the tooltip is not on a side, it may freely move horizontally because // it won't go under the pointer if ( anchor != 'left-center' && anchor != 'right-center' ){ // left and right overflow if (coord.left + this.__size.width > this.__helper.geo.window.scroll.left + this.__helper.geo.window.size.width) { coord.left = this.__helper.geo.window.scroll.left + this.__helper.geo.window.size.width - this.__size.width; } // don't ever let document overflow on the left, only on the right, so the user // can scroll. Note: right overflow should not happen often because when // measuring the natural width, text is already broken to fit into the viewport. if (coord.left < 0) { coord.left = 0; } // top and bottom overflow var pointerViewportY = event.pageY - this.__helper.geo.window.scroll.top; // if the tooltip is above the pointer if (anchor.indexOf('bottom') == 0) { // if it overflows the viewport on top if (coord.top < this.__helper.geo.window.scroll.top) { // if the tooltip overflows the document at the top if ( coord.top < 0 // if there is more space in the viewport below the pointer and that it won't // overflow the document, switch to the bottom. In the latter case, it might // seem odd not to switch to the bottom while there is more space, but the // idea is that the user couldn't close the tooltip, scroll down and try to // open it again, whereas he can do that at the top || ( pointerViewportY < this.__helper.geo.window.size.height - pointerViewportY && event.pageY + offset[1] + this.__size.height <= this.__helper.geo.document.size.height ) ) { coord.top = event.pageY + offset[1]; } } } // similar logic else { var coordBottom = coord.top + this.__size.height; // if it overflows at the bottom if (coordBottom > this.__helper.geo.window.scroll.top + this.__helper.geo.window.size.height) { // if there is more space above the pointer or if it overflows the document if ( pointerViewportY > this.__helper.geo.window.size.height - pointerViewportY || pointerViewportY - offset[1] + this.__size.height <= this.__helper.geo.document.size.height ) { // move it unless it would overflow the document at the top too var coordTop = event.pageY + offset[1] - this.__size.height; if (coordTop >= 0) { coord.top = coordTop; } } } } } // ignore the scroll distance if the origin is fixed if (this.__helper.geo.origin.fixedLineage) { coord.left -= this.__helper.geo.window.scroll.left; coord.top -= this.__helper.geo.window.scroll.top; } var position = { coord: coord }; this.__instance._trigger({ edit: function(p) { position = p; }, event: event, helper: this.__helper, position: $.extend(true, {}, position), type: 'follow' }); this.__instance._$tooltip .css({ left: position.coord.left, top: position.coord.top }) .show(); } else { // hide until a mouse event happens this.__instance._$tooltip .hide(); } return this; }, /** * (Re)compute this.__options from the options declared to the instance * * @return {self} * @private */ __optionsFormat: function() { this.__options = this.__instance._optionsExtract(pluginName, this.__defaults()); return this; }, /** * Called when Tooltipster thinks the tooltip should be repositioned/resized * (there can be many reasons for that). Tooltipster does not take mouse moves * into account, for that we have our own listeners that will adjust the * position (see __follow()) * * @return {self} * @private */ __reposition: function(event, helper) { var self = this, $clone = self.__instance._$tooltip.clone(), // start position tests session ruler = $.tooltipster._getRuler($clone), animation = self.__instance.option('animation'); // an animation class could contain properties that distort the size if (animation) { $clone.removeClass('tooltipster-'+ animation); } var rulerResults = ruler.free().measure(), position = { size: rulerResults.size }; // set position values on the original tooltip element if (helper.geo.origin.fixedLineage) { self.__instance._$tooltip .css('position', 'fixed'); } else { // CSS default self.__instance._$tooltip .css('position', ''); } self.__instance._trigger({ edit: function(p) { position = p; }, event: event, helper: helper, position: $.extend(true, {}, position), tooltipClone: $clone[0], type: 'position' }); // the clone won't be needed anymore ruler.destroy(); // pass to __follow() self.__helper = helper; self.__size = position.size; // set the size here, the position in __follow() self.__instance._$tooltip .css({ height: position.size.height, width: position.size.width }); // reposition. We don't pass the event if it's a mouseenter/touchstart event as // it may be stale if it's the event that initially started an opening delay // (there may have been move events after that), so we rely on the events we // recorded ourselves instead. If it's a click event we'll use it but only in // IE because Chrome and Firefox trigger an additional mousemove event when the // mouse is clicked and that's enough for us. var e = ($.tooltipster._env.IE && event.type === 'click') ? event : null; self.__follow(e); // append the tooltip HTML element to its parent self.__instance._$tooltip.appendTo(self.__instance.option('parent')); // Currently, this event is meant to give the size of the tooltip to // Tooltipster. In the future, if it were also about its coordinates, we may // have to fire it at each mousemove self.__instance._trigger({ type: 'repositioned', event: event, position: { // won't be used anyway since we enabled repositionOnScroll coord: { left: 0, top: 0 }, // may be used by the tooltip tracker size: position.size } }); return this; } } }); /* a build task will add "return $;" here for UMD */ return $; })); <file_sep>/_coll_country/south-africa.md --- contentful: sys: id: 6kCSAOUxGwi44GMaGwiqOC created_at: !ruby/object:DateTime 2015-12-08 11:20:21.669000000 Z updated_at: !ruby/object:DateTime 2018-05-17 16:50:40.972000000 Z content_type_id: country revision: 12 name: South Africa slug: south-africa col_url: http://www.britishmuseum.org/research/collection_online/search.aspx?people=197356&place=40953 map_progress: true intro_progress: true image_carousel: - sys: id: 5Q0aWg25UWIIiKA8ukoEyS created_at: !ruby/object:DateTime 2016-09-12 15:10:44.445000000 Z updated_at: !ruby/object:DateTime 2018-09-19 15:27:42.518000000 Z title: SOADRB0060022 description: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3738802&partId=1&searchText=Drakensberg+Mountains,+South+Africa.+&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/5Q0aWg25UWIIiKA8ukoEyS/5f0bca2c21b38c3e8e377e261f8e9e06/SOADRB0060022.jpg" - sys: id: 1VzKgiG0y8EIUcGmkueqMk created_at: !ruby/object:DateTime 2016-09-12 15:10:51.615000000 Z updated_at: !ruby/object:DateTime 2018-09-19 15:40:37.406000000 Z title: SOANTC0010007 description: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3730586&partId=1&searchText=Thaba+Sione,+South+Africa&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/1VzKgiG0y8EIUcGmkueqMk/7b7ae67f3a677dc9e877d3865e39209d/SOANTC0010007.jpg" - sys: id: 5e7KMSlhwksGWkKggGcO6e created_at: !ruby/object:DateTime 2016-09-12 15:11:05.796000000 Z updated_at: !ruby/object:DateTime 2018-09-19 16:24:51.271000000 Z title: SOANTC0020007 description: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3730618&partId=1&searchText=Driekops+Eiland%2c+South+Africa&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/5e7KMSlhwksGWkKggGcO6e/29ff3bcaa6a860961bb02131d4361e2e/SOANTC0020007.jpg" - sys: id: 6KNIv5SuCQMMYoE4qE4S8A created_at: !ruby/object:DateTime 2016-09-12 15:11:13.130000000 Z updated_at: !ruby/object:DateTime 2018-09-19 16:28:35.718000000 Z title: SOANTC0040005 description: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3731061&partId=1&searchText=+Kimberley%2c+South+Africa&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/6KNIv5SuCQMMYoE4qE4S8A/059e102e1b8e3d44c707351e7ec9c8ed/SOANTC0040005.jpg" - sys: id: 5bGzl4ABJecgssmAccaog2 created_at: !ruby/object:DateTime 2016-09-12 15:11:23.273000000 Z updated_at: !ruby/object:DateTime 2018-09-19 16:30:30.968000000 Z title: SOASWC0050009 description: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3741695&partId=1&searchText=West+Coast+District+Municipality%2c+South+Africa&page=2 url: "//images.ctfassets.net/xt8ne4gbbocd/5bGzl4ABJecgssmAccaog2/de2c686122e5fa00afd2f5bc12b52a7f/SOASWC0050009.jpg" - sys: id: 6GqC6D7ckgwSoCCKEQqiEm created_at: !ruby/object:DateTime 2016-09-12 15:11:37.019000000 Z updated_at: !ruby/object:DateTime 2018-09-19 16:32:02.304000000 Z title: SOASWC0110006 description: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3734234&partId=1&searchText=+West+Coast+District+Municipality%2c+South+Africa&page=2 url: "//images.ctfassets.net/xt8ne4gbbocd/6GqC6D7ckgwSoCCKEQqiEm/0ff3dcb37da4a9a4c5ef6275563cdfdd/SOASWC0110006.jpg" featured_site: sys: id: 2XOggE9Gxaew6iMMKS4E4U created_at: !ruby/object:DateTime 2016-09-12 15:15:32.469000000 Z updated_at: !ruby/object:DateTime 2016-09-13 13:35:15.580000000 Z content_type_id: featured_site revision: 2 title: Game Pass Shelter, South Africa slug: gamepass chapters: - sys: id: 5WhcFBd6owA0UwoG6iOg4Y created_at: !ruby/object:DateTime 2016-09-12 15:12:00.222000000 Z updated_at: !ruby/object:DateTime 2016-09-13 13:34:42.735000000 Z content_type_id: chapter revision: 6 title: Game Pass Shelter, South Africa title_internal: 'South Africa: featured site, chapter 1' body: "Game Pass shelter is one of the most well-known rock art sites in South Africa. Situated in the foothills of the Drakensberg mountains, a sandstone recess atop a steep slope contains rock paintings made by people from the San&#124;Bushman¹ communities who historically lived as hunter-gatherers throughout southern Africa. The Drakensberg mountains in particular are known for their wealth of rock paintings, often showing detailed and brightly coloured images of people, animals and part-human, part-animal figures known as ‘therianthropes’, with this site a prime example. One of the panels of paintings here is particularly important in the history of rock art research, as in the 1970s it helped to inspire a new kind of approach to the understanding of the meanings and symbolism of San&#124;Bushman paintings and engravings.\n\n" - sys: id: 6mZ8n44JbyOIMKaQYKgm4k created_at: !ruby/object:DateTime 2016-09-12 15:12:11.338000000 Z updated_at: !ruby/object:DateTime 2018-05-15 13:55:27.144000000 Z content_type_id: image revision: 2 image: sys: id: XICyV4qumymqa8eIqCOeS created_at: !ruby/object:DateTime 2016-09-12 15:12:27.902000000 Z updated_at: !ruby/object:DateTime 2016-09-12 15:12:27.902000000 Z title: SOADRB0080002 description: url: "//images.ctfassets.net/xt8ne4gbbocd/XICyV4qumymqa8eIqCOeS/5c82b58cf67f6c300485aea40eb5b05a/SOADRB0080002.jpg" caption: View of the Game Pass Shelter from below. 2013,2034.18363 ©TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3730908&partId=1&searchText=2013,2034.18363&page=1 - sys: id: 3xOl8hqio0E2wYYKIKomag created_at: !ruby/object:DateTime 2016-09-12 15:12:45.525000000 Z updated_at: !ruby/object:DateTime 2018-05-15 13:57:48.547000000 Z content_type_id: image revision: 2 image: sys: id: 3cyElw8MaIS24gq8ioCcka created_at: !ruby/object:DateTime 2016-09-12 15:12:39.975000000 Z updated_at: !ruby/object:DateTime 2016-09-12 15:12:39.975000000 Z title: SOADRB0080007 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3cyElw8MaIS24gq8ioCcka/fcea216b7327f325bf27e3cebe49378e/SOADRB0080007.jpg" caption: Painted panel showing multiple eland antelope and other figures. 2013,2034.18368 ©TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3730846&partId=1&searchText=2013,2034.18368&page=1 - sys: id: 3ilqDwqo80Uq6Q42SosqQK created_at: !ruby/object:DateTime 2016-09-12 15:12:59.726000000 Z updated_at: !ruby/object:DateTime 2018-05-15 13:59:22.144000000 Z content_type_id: chapter revision: 5 title_internal: 'South Africa: featured site, chapter 2' body: The most prominent painting panel at Game Pass shows a series of carefully depicted eland antelope in delicately shaded red, brown and white pigment, largely super imposing a group of ambiguous anthropomorphic figures wrapped in what appear to be bell-shaped karosses (traditional skin cloaks). Several small human figures appear to be running above them. These are some of the best-preserved rock paintings in the Drakensberg, with the largest animals around 30 cm long. To the left of this panel are two smaller sets of images, one with two further eland, some further human-like figures and a human figure with a bow; the other a small panel, for which the site is most renowned. An image around 50 cm long shows an eland with its face turned towards the viewer, depicted as if stumbling forwards, with its hind legs crossed. Grasping the eland's tail is a therianthrope figure with hooves for feet. Like the eland, this figure has its legs crossed and is depicted with small lines like raised hairs bristling from its body. To the right are three further therianthrope figures. - sys: id: 3oYyhNlOdWu4oaoG0qUEGC created_at: !ruby/object:DateTime 2016-09-12 15:13:08.484000000 Z updated_at: !ruby/object:DateTime 2018-05-15 14:02:39.599000000 Z content_type_id: image revision: 3 image: sys: id: 777S5VQyBO0cMwKC0ayqKe created_at: !ruby/object:DateTime 2016-09-12 15:13:12.516000000 Z updated_at: !ruby/object:DateTime 2016-09-12 15:13:12.516000000 Z title: SOADRB0080015 description: url: "//images.ctfassets.net/xt8ne4gbbocd/777S5VQyBO0cMwKC0ayqKe/67d88e9197416be62cc8ccc0b576adf9/SOADRB0080015.jpg" caption: Panel showing an eland antelope with crossed legs and a therianthrope figure grasping its tail. 2013,2034.18376 ©TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3730898&partId=1&searchText=2013,2034.18376&page=1 - sys: id: 3t21DyQhhu6KYE24yOuW6E created_at: !ruby/object:DateTime 2016-09-12 15:13:26.839000000 Z updated_at: !ruby/object:DateTime 2018-05-15 14:02:03.671000000 Z content_type_id: chapter revision: 2 title_internal: 'South Africa: featured site, chapter 3' body: The rock paintings from this site were first brought to public attention in a 1915 issue of Scientific American, and it has been frequently published on and discussed through the 20th century. While studying a reproduction of the image with the stumbling eland in the early 1970s, researcher David Lewis-Williams began to consider that the figure holding the eland's tail might not be a simple illustration of a man wearing a skin suit, or performing an act of bravura, as had been suggested by previous researchers, but might be “idiomatic and metaphorical, rather than illustrative” (Lewis-Williams 1981:91). - sys: id: 8JKh5DFTLqMsaCQWAAA4c created_at: !ruby/object:DateTime 2016-09-12 15:13:41.069000000 Z updated_at: !ruby/object:DateTime 2018-05-15 14:03:14.804000000 Z content_type_id: image revision: 2 image: sys: id: 2QyopQgIx2AAMU46gEM2Wg created_at: !ruby/object:DateTime 2016-09-12 15:13:36.176000000 Z updated_at: !ruby/object:DateTime 2016-09-12 15:13:36.176000000 Z title: SOADRB0080017 description: url: "//images.ctfassets.net/xt8ne4gbbocd/2QyopQgIx2AAMU46gEM2Wg/614f0c5c375d7d8e8e9be93ce2179a18/SOADRB0080017.jpg" caption: The figure holding the eland’s tail has similar qualities to the eland itself. 2013,2034.1838 ©TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3730897&partId=1&place=107937&plaA=107937-2-2&page=1 - sys: id: 1l6QCXODlWoa6kmgWAgco2 created_at: !ruby/object:DateTime 2016-09-12 15:13:55.229000000 Z updated_at: !ruby/object:DateTime 2016-09-30 16:42:50.171000000 Z content_type_id: chapter revision: 3 title_internal: 'South Africa: featured site, chapter 4' body: "This idea was partly inspired by the testimony of Qing, a San&#124;Bushman man who, in 1873, had guided the Colonial Administrator <NAME> Orpen to rock art sites in the mountains of Lesotho, with which the Drakensberg forms a natural eastern border with South Africa and which also contains many rock paintings. Qing's explanations of the paintings, some of which Orpen copied, included a reference to antelope-headed human figures having “died and gone to live in rivers, who were spoilt at the same time as the elands and… by the dances of which you have seen paintings”. This, along with testimony and practices recorded from other South African San&#124;Bushman people at the time, as well as those living elsewhere in south-western Africa in the 20th century, suggested to Lewis-Williams that these and other images in San&#124;Bushman rock art may be a reference to the activities of spiritual leaders or 'shamans', people who, in San&#124;Bushman communities, are believed to have the power to interact with spirits and the spirit world in ways which may affect the physical world. \n\nLewis-Williams and other proponents of this 'shamanistic' approach to interpreting San&#124;Bushman rock art have proposed that much of its imagery is in fact related to the shaman's experience during the 'trance dance' ritual found in all San&#124;Bushman socie-ties. During this activity the shaman enters a hallucinatory state in which spiritual ‘tasks’ such as healing the sick may be undertaken on behalf of the community. On entering the trance state the shaman experiences trembling, sweating, stumbling and other symptoms similar to those of a dying antelope hit by a poisoned arrow. Lewis Williams noted that among some San&#124;Bushman people this process is referred to as ‘dying’ or being ‘spoilt’ and considered that the similarities between the eland and the therianthrope figure in this image represent this conceived equivalence.\n\n" - sys: id: 4cmGHIbGFqOEqYWwyi0S2e created_at: !ruby/object:DateTime 2016-09-12 15:14:08.008000000 Z updated_at: !ruby/object:DateTime 2018-05-15 14:05:13.185000000 Z content_type_id: image revision: 2 image: sys: id: 5qjFwYmXkca88mMcWSiGgc created_at: !ruby/object:DateTime 2016-09-12 15:14:04.272000000 Z updated_at: !ruby/object:DateTime 2016-09-12 15:14:04.272000000 Z title: SOADRB0010012 description: url: "//images.ctfassets.net/xt8ne4gbbocd/5qjFwYmXkca88mMcWSiGgc/761a55733ca2935fd7056e1a0de33dd6/SOADRB0010012.jpg" caption: Two eland antelope running in the Drakensberg. 2013,2034.18180 ©TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3729855&partId=1&searchText=2013,2034.18180&page=1 - sys: id: 1VRoS6FN4ga60gcYImm6c2 created_at: !ruby/object:DateTime 2016-09-12 15:14:20.350000000 Z updated_at: !ruby/object:DateTime 2016-09-30 16:47:30.231000000 Z content_type_id: chapter revision: 4 title_internal: 'South Africa: featured site, chapter 5' body: | Despite the historical presence of other large game animals in the Drakensberg, the eland is the most commonly depicted animal in rock art of the region. Patricia Vinnicombe, noting this and the focus on other particular subjects in the imagery at the expense of others, proposed in her pioneering 1976 study of the rock art of the Southern Drakensberg *People of the Eland* that the paintings are “not a realistic reflection of the daily pursuits or environment of the Bushmen” (Vinnicombe 1976:347). Vinnicombe recalled that when, in the 1930s, an old Sotho man named Mapote, who had San&#124;Bushman half-siblings and had used to paint with them, was requested to demonstrate, he had said that since the San&#124;Bushmen had been “of the eland”, he should first depict an eland. Based on this and recountings of a myth about the creation and death of the first eland from Qing and other contemporary Southern San&#124;Bushman people, Vinnicombe concluded that the eland, although regularly hunted by the Drakensberg San&#124;Bushmen, had been a particularly sacred or powerful animal to them and that “Through the act of painting and re-painting the eland… the mental conflict involved in destroying a creature that was prized and loved by their deity…was…ritually symbolised and resolved” (Vinnicombe, 1976:350). Building on the idea of the spiritual significance of the eland, the approach proposed by Lewis-Williams offered an alternative interpretation by inferring from ethnography that eland were believed to have spiritual ‘potency’. As part of a complex system of beliefs involving conceptions of power and potency in relation to animals and rites, this potency could be released upon death, with trancing shamans believed to be able to harness it, feeling themselves taking on the attributes of the animal. Thus therianthrope figures like those depicted here may be interpreted as representing hallucinatory experiences of shamans in trance, where they may feel that they are assuming the forms of other animals. It has been argued that other motifs such as geometric forms known as 'entoptics' represent the abstract patterns created by neural networks and ‘seen’ during the early stages of entering an altered state of consciousness and that the paintings themselves may have been created as reservoirs of spiritual potency. - sys: id: n044NT3TZAYwKSakkogoU created_at: !ruby/object:DateTime 2016-09-12 15:14:38.475000000 Z updated_at: !ruby/object:DateTime 2018-05-15 14:05:31.169000000 Z content_type_id: image revision: 2 image: sys: id: 60II5zuUne2A80682sYYs2 created_at: !ruby/object:DateTime 2016-09-12 15:14:34.660000000 Z updated_at: !ruby/object:DateTime 2016-09-12 15:14:34.660000000 Z title: SOADRB0080019 description: url: "//images.ctfassets.net/xt8ne4gbbocd/60II5zuUne2A80682sYYs2/bbee114e572cf8a7a403d6802749707c/SOADRB0080019.jpg" caption: Eland and faded figures. 2013,2034.18391 ©TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3730884&partId=1&place=107937&plaA=107937-2-2&page=1 - sys: id: 5Lheod1OGAYUW4Goi6GAUo created_at: !ruby/object:DateTime 2016-09-12 15:14:46.323000000 Z updated_at: !ruby/object:DateTime 2016-09-30 16:49:04.072000000 Z content_type_id: chapter revision: 2 title_internal: 'South Africa: featured site, chapter 6' body: "The shamanistic approach to interpreting San&#124;Bushman rock art images, for which the Game Pass panel is sometimes referred to as the ‘Rosetta Stone’, gained popularity in the 1980s and has since become the dominant interpretative framework for researchers. Debate continues about the extent and nature of its applicability in all of San&#124;Bushman rock art, and the extent to which myth and ritual not associated with the trance dance may also inform the art. Work that connects San&#124;Bushman cosmology and practice with images from sites like Game Pass continue to provide interesting insights into these enigmatic images. \n\nGame Pass Shelter and many other rock art sites are situated within the Maloti-Drakensberg Park, which was inscribed as a UNESCO Transboundary World Heritage Site in 2000. The site is open to the public and accessible via a trail from the Kamberg Rock Art Centre.\n\n" - sys: id: 4XwNgMsBPaQ06My8Qs4gKU created_at: !ruby/object:DateTime 2016-09-13 13:35:11.603000000 Z updated_at: !ruby/object:DateTime 2016-09-13 13:35:11.603000000 Z content_type_id: chapter revision: 1 title_internal: 'South Africa Featured Site Chapter 7 ' body: "¹ San&#124;Bushmen is a collective term used to describe the many different hunter-gatherer-fisher groups living in southern Africa who have related languages and cultural traditions. Both 'San' and 'Bushmen' are considered offensive terms by some members of these groups, although others have positively adopted them." citations: - sys: id: 3brqyMy1K0IC0KyOc8AYmE created_at: !ruby/object:DateTime 2016-09-12 15:14:59.720000000 Z updated_at: !ruby/object:DateTime 2016-09-12 15:14:59.720000000 Z content_type_id: citation revision: 1 citation_line: | <NAME>. 2009. 'Contested Histories: A Critique of Rock Art in the Drakens-berg Mountains' in Visual Anthropology 22:4, pp. 327 — 343 <NAME>. 1981. Believing and Seeing: Symbolic Meanings in San&#124;Bushman Rock Paintings. Johannesburg, University of Witwatersrand Press Vinnicombe, P. 1976. People of The Eland: Rock paintings of the Drakensberg Bushmen as a reflection of their life and thought. Pietermaritzburg, University of Natal Press Solomon, A. 1997. ‘The Myth of Ritual Origins: Ethnography, Mythology and Interpre-tation of San&#124;Bushman Rock Art’. South African Archaeological Bulletin 53, pp.3-13 <NAME>., & <NAME>. Art on the Rocks of Southern Africa. London, Mac-donald background_images: - sys: id: 6qIbC41P8IM2O8K4w6g0Ec created_at: !ruby/object:DateTime 2016-09-12 15:15:14.404000000 Z updated_at: !ruby/object:DateTime 2016-09-12 15:15:14.404000000 Z title: SOADRB0080001 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6qIbC41P8IM2O8K4w6g0Ec/60009e28497973bd9682d19ba5a9d497/SOADRB0080001.jpg" - sys: id: ARPF2hJVwOYm0iaAgUmk0 created_at: !ruby/object:DateTime 2016-09-12 15:15:22.171000000 Z updated_at: !ruby/object:DateTime 2016-09-12 15:15:22.171000000 Z title: SOADRB0080039 description: url: "//images.ctfassets.net/xt8ne4gbbocd/ARPF2hJVwOYm0iaAgUmk0/40e2845d0ffe86c19d674886a3721b10/SOADRB0080039.jpg" key_facts: sys: id: 3bOoDYEftKw6emikskymiu created_at: !ruby/object:DateTime 2016-09-12 15:15:50.428000000 Z updated_at: !ruby/object:DateTime 2016-09-30 16:50:58.347000000 Z content_type_id: country_key_facts revision: 2 title_internal: 'South Africa: key facts' image_count: 1,506 images date_range: Mostly 8,000 BC to the 20th Century main_areas: Throughout, with particular concentrations in the Drakensberg and Cape Fold mountains and the Karoo techniques: Brush painting, finger painting, pecked engraving main_themes: 'human figures, large fauna, particularly eland antelope, geometric shapes, occasionally subjects dating to the recent past such as firearms and people riding horses ' thematic_articles: - sys: id: 2Rh3XLBCreIy6ms4cKYKIQ created_at: !ruby/object:DateTime 2017-08-13 13:52:18.110000000 Z updated_at: !ruby/object:DateTime 2017-08-13 13:55:09.227000000 Z content_type_id: thematic revision: 2 title: Contact Rock Art in South Africa slug: contact-rock-art-south-africa lead_image: sys: id: 6GqC6D7ckgwSoCCKEQqiEm created_at: !ruby/object:DateTime 2016-09-12 15:11:37.019000000 Z updated_at: !ruby/object:DateTime 2018-09-19 16:32:02.304000000 Z title: SOASWC0110006 description: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3734234&partId=1&searchText=+West+Coast+District+Municipality%2c+South+Africa&page=2 url: "//images.ctfassets.net/xt8ne4gbbocd/6GqC6D7ckgwSoCCKEQqiEm/0ff3dcb37da4a9a4c5ef6275563cdfdd/SOASWC0110006.jpg" chapters: - sys: id: 4cLakkCQWQUUYiceIaW6AG - sys: id: 3rcFEUcVbqgqQ0mYUmgYYu - sys: id: 32Q6z3T9aU6WAUkuaI4Ikm - sys: id: 3C150sXEbCMQ8QMcYKui4C - sys: id: 1ob9WoGxQIKok6gWwiAkEO - sys: id: 6TiCFpLBHGUYCuOaOWoeYC - sys: id: 4nHgrO0wmQkaUGguQKeC2I - sys: id: 1O1Wk9Grbie4EiikoiyySE - sys: id: 3tat1UEvxSwg6swC0OmWs2 - sys: id: qkyiaZ7KjmACgou0suywM - sys: id: 5jp2LySdcAseIEcsy08Ssw - sys: id: 3ZSiZ5Zly8YeAcWKOs0M6k - sys: id: 6w7bPvqDzG4mmwKSkC2ua4 - sys: id: 1hLrFnRQlm6eEgeG2IMIcg - sys: id: 6Zo0yGAQ3mY8wqw8U60W2s - sys: id: 4v55jtTmQEoe2sCauwUisQ - sys: id: 4vGr1ql4RGaKSy0SMWieS2 - sys: id: 4HFYx1dTdm2GEQI4Q6WwqC - sys: id: 1IpPlvLRE42IYkcmayCUGq - sys: id: 7cu4xgoZhe48gOqI4iM2YS - sys: id: 6DhPevH8J222e6GEEkqU2A - sys: id: 6eZhwxCwyQoUQkuWyQsooi - sys: id: 227ir2Bipm8mmc2YKSMWkO citations: - sys: id: 7z28m7agdUckmmAUeEsoao background_images: - sys: id: 6QHTRqNGXmWic6K2cQU8EA created_at: !ruby/object:DateTime 2016-09-13 13:03:52.426000000 Z updated_at: !ruby/object:DateTime 2016-09-13 13:03:52.426000000 Z title: SOASWC0110006 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6QHTRqNGXmWic6K2cQU8EA/3d924964d904e34e6711c6224a7429e6/SOASWC0110006.jpg" - sys: id: 6OFVBr3mUgqcwCi4oC0u6m created_at: !ruby/object:DateTime 2017-08-13 13:27:10.583000000 Z updated_at: !ruby/object:DateTime 2017-08-13 13:27:10.583000000 Z title: '2013,2034.19509' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6OFVBr3mUgqcwCi4oC0u6m/5243bf9b8450bfab9fb3a454c2f78ca0/AN1613150762_l.jpg" - sys: id: 2fRpwDPsrmiQaUQMqSI8oA created_at: !ruby/object:DateTime 2017-03-13 02:40:28.121000000 Z updated_at: !ruby/object:DateTime 2017-03-13 02:40:28.121000000 Z content_type_id: thematic revision: 1 title: Rock Art VR - Game Pass Shelter Mobile App slug: rockartvr lead_image: sys: id: 2Sqy60hy3YSo4sQE2Ame6m created_at: !ruby/object:DateTime 2017-03-12 22:34:27.617000000 Z updated_at: !ruby/object:DateTime 2017-03-12 22:34:27.617000000 Z title: Screen Shot 2016-12-12 at 3.34.33 PM description: url: "//images.ctfassets.net/xt8ne4gbbocd/2Sqy60hy3YSo4sQE2Ame6m/b58f2bdd6c004b4111987aba5c2bd362/Screen_Shot_2016-12-12_at_3.34.33_PM.png" chapters: - sys: id: 6nHJUYFyucgyyMKs6iYwwo - sys: id: 2oGC8YIQnmIaewkKes6EqI - sys: id: 5rjsmkdjUcSEOWIYKuuCIi - sys: id: 4iG66vQ2MUu24GywiUEOYG - sys: id: 2XMhIpm5TW4mUySacSUggg - sys: id: 4f4xPt1kfeakUO4AE42yeg - sys: id: CV5a7U4DReuiC0e2yeUai - sys: id: 4Nw0ySbeZiIEuaimaYIowM - sys: id: 5i0X5VKYQEuYgCCUEUGsQm - sys: id: 6GhOyZzkrYAuG8agOSeA08 - sys: id: 3O7wEtT9WgIIy6AWGw4guE - sys: id: 1cN6S7SmRywQYmGwKGsaw2 - sys: id: 75vDJziuic2I02EQKym8Gm - sys: id: 7EhyKmW3NSKGeYksYOMGs - sys: id: 3KTPOINSlW6I0O6iEysQW - sys: id: 4whYOCUWdWiMY2MGiCWao0 - sys: id: AmuS3r3zIkMIgSmIEKqcK - sys: id: 75ifs3faSWy0qw2eUS4Yu4 - sys: id: 3dnPPXO03ecUwA2ymasCKo background_images: - sys: id: 2qLasAyYmAM4wUS2gOe4yg created_at: !ruby/object:DateTime 2017-03-12 22:40:18.738000000 Z updated_at: !ruby/object:DateTime 2017-03-12 22:40:18.738000000 Z title: Game Pass7 description: url: "//assets.ctfassets.net/xt8ne4gbbocd/2qLasAyYmAM4wUS2gOe4yg/50c79d5c2e310775bd444de205908a2e/Game_Pass7.tif" - sys: id: 4LZ2y95ptKWk2SwUQgwu4k created_at: !ruby/object:DateTime 2017-03-12 22:42:48.598000000 Z updated_at: !ruby/object:DateTime 2017-03-12 22:42:48.598000000 Z title: Game Pass3 description: url: "//assets.ctfassets.net/xt8ne4gbbocd/4LZ2y95ptKWk2SwUQgwu4k/a5150665772b9d769f26ccf3c6b39f03/Game_Pass3.tif" - sys: id: 570TteJLy8EmE4SYAGKcQw created_at: !ruby/object:DateTime 2017-06-14 17:36:35.946000000 Z updated_at: !ruby/object:DateTime 2017-06-21 13:55:43.874000000 Z content_type_id: thematic revision: 5 title: Rhinos in rock art slug: rhinos-in-rock-art lead_image: sys: id: 4uVUj08mRGOCkmK64q66MA created_at: !ruby/object:DateTime 2016-09-26 14:46:35.956000000 Z updated_at: !ruby/object:DateTime 2019-02-12 02:01:17.553000000 Z title: '2013,2034.20476' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3730556&partId=1&searchText=NAMDMT0010010&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/4uVUj08mRGOCkmK64q66MA/c1c895d4f72a2260ae166ab9c2148daa/NAMDMT0010010.jpg" chapters: - sys: id: 4kAwRERjIIQ4wSkS6y2i8c - sys: id: 2hohzbPqWMU2IGWEeSo2ma - sys: id: 5Ld8vmtLAAGcImkQaySck2 - sys: id: 6jA55SyPksGMQIYmYceMkQ - sys: id: 7gBWq5BdnOYUGm6O4KK4u0 - sys: id: 1LYEwVNEogggeMOcuQUOQW - sys: id: 4dbpdyyr2UAk4yKAomw42I - sys: id: 3VgqyhGcViwkwCoI88W4Ii - sys: id: 4TnBbYK1SEueSCAIemKOcA - sys: id: 4Z8zcElzjOCyO6iOasMuig - sys: id: 2Z9GGCpzCMk4sCKKYsmaU8 - sys: id: 2S3mX9yJfqoMka8QoWUqOE - sys: id: 4KLSIsvlmEMeOsCo8SGOQA - sys: id: 1IlptwbzFmIaSkIWWAqw8U - sys: id: 2Moq7jFKLCc60oamksKUgU - sys: id: 2OfGVIZFbOOm8w6gg6AucI - sys: id: 16oCD2X1nmEYmCOMOm6oWi - sys: id: 2jfI6k6zKAauIS62IC6weq - sys: id: 4k9Uy1dQzmkcIY0kIogeWK - sys: id: 2QFAA8hik82Y4EAIwGSiEs - sys: id: 3ApAq8tLfG6wWaswQEwuaU - sys: id: 4S5oC30EcwEUGEuEO6sa4m - sys: id: 4Y3xOdstSowoYOGOEmW6K6 - sys: id: 6ZjeUWwA5aCEMUiIgukK48 citations: - sys: id: TwHxmivy8uW8mIKAkkMeA background_images: - sys: id: 2ztUAznRiwc0qiE4iUIQGc created_at: !ruby/object:DateTime 2017-05-17 11:44:42.255000000 Z updated_at: !ruby/object:DateTime 2017-05-17 11:44:42.255000000 Z title: Rhinocéros grotte Chauvet description: url: "//images.ctfassets.net/xt8ne4gbbocd/2ztUAznRiwc0qiE4iUIQGc/5958ce98b795f63e5ee49806275209b7/Rhinoc__ros_grotte_Chauvet.jpg" - sys: id: 6m2Q1HCGT6Q2cey00sKGmu created_at: !ruby/object:DateTime 2017-05-17 12:26:24.400000000 Z updated_at: !ruby/object:DateTime 2017-05-17 12:26:24.400000000 Z title: Black Rhino description: url: "//images.ctfassets.net/xt8ne4gbbocd/6m2Q1HCGT6Q2cey00sKGmu/92caad1c13d4bbefe80a5a94aef9844e/Black_Rhino.jpg" country_introduction: sys: id: 3bwz5wde0EMm0iu06IOk0W created_at: !ruby/object:DateTime 2016-09-12 15:22:12.732000000 Z updated_at: !ruby/object:DateTime 2016-09-12 15:22:12.732000000 Z content_type_id: country_information revision: 1 title: 'South Africa: country introduction' chapters: - sys: id: 2LBn1DZ1m8gqQUMiKCSayA created_at: !ruby/object:DateTime 2016-09-12 15:16:12.647000000 Z updated_at: !ruby/object:DateTime 2016-09-12 22:01:59.313000000 Z content_type_id: chapter revision: 4 title: Introduction title_internal: 'South Africa: country, chapter 1' body: | The rock art of South Africa has probably been studied more extensively than that of any other African country. It is estimated that South Africa contains many thousands of rock art sites, with a great variety of styles and techniques. The most well-known rock art in South Africa is that created by the San&#124;Bushman¹ people (several culturally linked groups of indigenous people of southern Africa who were traditionally hunter-gatherers) and their ancestors, with the painted rock shelters of the Drakensberg mountains some of the most well-known rock art sites in the world. However, the range of South African rock art is wide, spanning great distances, many centuries, and different cultural traditions. ¹ San&#124;Bushmen is a collective term used to describe the many different hunter-gatherer-fisher groups living in southern Africa who have related languages and cultural traditions. Both 'San' and 'Bushmen' are considered offensive terms by some members of these groups, although others have positively adopted them. - sys: id: 6rGZi909xKeQSMcYmISMgA created_at: !ruby/object:DateTime 2016-09-12 15:16:31.433000000 Z updated_at: !ruby/object:DateTime 2018-05-15 13:46:10.737000000 Z content_type_id: image revision: 2 image: sys: id: 2bsw2WPaTKumMQ80maQ6iG created_at: !ruby/object:DateTime 2016-09-12 15:16:22.149000000 Z updated_at: !ruby/object:DateTime 2016-09-12 15:16:22.149000000 Z title: SOADRB0010004 description: url: "//images.ctfassets.net/xt8ne4gbbocd/2bsw2WPaTKumMQ80maQ6iG/1748f1d507b1e6e7b40b12621fcf06a4/SOADRB0010004.jpg" caption: Painted eland antelope, horses and riders. Drakensberg Mountains, South Africa. 2013,2034.18172 ©TARA/<NAME>oulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3738170&partId=1&searchText=2013,2034.18172&page=1 - sys: id: 3SiNGUuMNi4EQ6S6iEg6u created_at: !ruby/object:DateTime 2016-09-12 15:16:42.238000000 Z updated_at: !ruby/object:DateTime 2016-10-17 15:43:41.595000000 Z content_type_id: chapter revision: 4 title: Geography and rock art distribution title_internal: 'South Africa: country, chapter 2' body: South Africa covers around 1,213,090 km², encircling Lesotho and bordered in the north by Namibia, Botswana and Zimbabwe and in the west by Mozambique and Swaziland. Much of the interior of the country consists of a high central plateau bordered by the Great Escarpment, a rocky ridge which forms the bulk of the long Drakensberg mountain system in the east and several smaller ranges in the centre and west of the country, as well as the western border with Lesotho. Further to the south, the Cape Fold Mountains mirror the bend of the cape coast. Much of South Africa’s known engraved rock art is found on igneous or metamorphic formations in the semi-arid environments of the central plateau. In contrast, painted rock art sites are more commonly located in the sandstone and quartzite rock shelters of the mountain systems, which form the edges of the more temperate, low-lying coastal regions in the east and south of the country. - sys: id: DfGG3aLwUC26MWusakCaQ created_at: !ruby/object:DateTime 2016-09-12 15:16:52.597000000 Z updated_at: !ruby/object:DateTime 2016-10-24 12:32:11.801000000 Z content_type_id: chapter revision: 3 title: Hunter-gatherer rock art title_internal: 'South Africa: country, chapter 3' body: Much of both the painted and engraved rock art of South Africa is characterised by its naturalistic depictions of animals, as well as numerous images of people, ambiguous figures with mixtures of animal and human features, and certain ‘geometric’ or abstract shapes and patterns. These images are the work of San&#124;Bushman people and their ancestors. Although San&#124;Bushman communities now live mainly in Namibia, Botswana and north-western South Africa, historically San&#124;Bushman cultural groups lived more widely throughout southern Africa. Hunter-gatherer people are thought to have been the only inhabitants of what is now South Africa until the arrival of herding and farming people from the north from around 2,000 years ago. - sys: id: 71sZP8YT0A8Eg6SUEqQE0K created_at: !ruby/object:DateTime 2016-09-12 15:17:10.281000000 Z updated_at: !ruby/object:DateTime 2018-05-15 13:46:37.309000000 Z content_type_id: image revision: 2 image: sys: id: 2q8dJPCe2AKcAeogKWikue created_at: !ruby/object:DateTime 2016-09-12 15:17:06.782000000 Z updated_at: !ruby/object:DateTime 2016-09-12 15:17:06.782000000 Z title: SOASWC0130095 description: url: "//images.ctfassets.net/xt8ne4gbbocd/2q8dJPCe2AKcAeogKWikue/7edea03ab0a677b76edd11bda026ba2c/SOASWC0130095.jpg" caption: Human figures with bows and other items. Western Cape, South Africa. 2013,2034.19641 ©TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3740593&partId=1&searchText=2013,2034.19641&page=1 - sys: id: dbiRhTPqBamyEw8Wa8Am0 created_at: !ruby/object:DateTime 2016-09-12 15:17:21.602000000 Z updated_at: !ruby/object:DateTime 2016-09-12 19:41:29.750000000 Z content_type_id: chapter revision: 2 title: Farmer rock art title_internal: 'South Africa: country, chapter 4' body: "Some paintings and engravings in South Africa were made by Bantu language-speaking farming people. These include a distinct tradition of rock shelter paintings found in the north-west of the country, featuring mostly white finger-painted images of animals such as crocodiles and giraffes and other motifs. These paintings, located in remote areas, are known to have been created by Northern Sotho people. Further to the south and west, engraved designs showing conjoined circle motifs are found throughout KwaZulu Natal and some areas of Mpumalanga and Gauteng Provinces, and appear to have been made by the ancestors of Sotho-Tswana and Nguni language speakers, perhaps ancestors of modern Zulu people.\n\n" - sys: id: avwg4dFD5muMuGwi64OG8 created_at: !ruby/object:DateTime 2016-09-12 15:17:28.334000000 Z updated_at: !ruby/object:DateTime 2018-05-15 13:47:33.249000000 Z content_type_id: chapter revision: 4 title: Herder rock art and other traditions title_internal: 'South Africa: country, chapter 5' body: Some rock art styles and motifs elsewhere in South Africa seem to belong to other unique traditions. It has been proposed that engraved rock art patterns with particular features including circular, linear and oblong motifs found at sites across the country, particularly near watercourses, may be the work of the Khoekhoen people or their ancestors, herders culturally related to the San&#124;Bushmen. Some paintings also appear to reflect this tradition. Local rock art traditions specific to certain areas include, among others, conglomerations of handprints near the coast in the south-western part of the Western Cape and rows of engraved cupules in the north-east of the country. There are also several examples from different rock art traditions across South Africa, of depictions of European people, items or events (such as horses and firearms) which clearly date from the 17th century or later. In the Karoo region, rock gongs (natural rock formations with indentations indicating that they have been used as percussive instruments) are sometimes associated with engraving sites. - sys: id: 1mBBOrIKNWY4m20ywAQEG4 created_at: !ruby/object:DateTime 2016-09-12 15:17:42.557000000 Z updated_at: !ruby/object:DateTime 2018-05-15 13:48:06.147000000 Z content_type_id: image revision: 2 image: sys: id: afH4Qvv6OAAu6iW2sQumq created_at: !ruby/object:DateTime 2016-09-12 15:17:38.680000000 Z updated_at: !ruby/object:DateTime 2016-09-12 15:17:38.680000000 Z title: SOASWC0120007 description: url: "//images.ctfassets.net/xt8ne4gbbocd/afH4Qvv6OAAu6iW2sQumq/b1167a05a4746cff6df801f17a999b62/SOASWC0120007.jpg" caption: Paintings showing people in long skirts and hats, with wagons drawn by horses/mules. Swartruggens, Western Cape, South Africa. 2013,2034.19505 ©TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3734262&partId=1&searchText=2013,2034.19505&page=1 - sys: id: 2tA0V2wO16oKa8kgyOeACw created_at: !ruby/object:DateTime 2016-09-12 15:17:56.399000000 Z updated_at: !ruby/object:DateTime 2016-10-17 15:44:50.312000000 Z content_type_id: chapter revision: 2 title: Research history title_internal: 'South Africa: country, chapter 6' body: 'Rock art sites throughout what is now South Africa have likely always been known to local communities, even where the art''s creators were not from within them. The presence of rock art in the Cape region has been known to Europeans since at least the mid- 18th century AD, with one of the first known reports from the expedition of Ensign <NAME> in 1752, describing paintings near the Great Fish River in the Eastern Cape. Further written references to rock art from the area were made throughout the 18th and 19th centuries, with some of the earliest known reproductions of Southern African rock art made in the 1770s. During the 19th and early 20th centuries, painted copies were made of San&#124;Bushman rock art by amateur artists such as <NAME>, Mark and <NAME> and <NAME>. ' - sys: id: 19Up0IjuAa2c2WQuks6Qka created_at: !ruby/object:DateTime 2016-09-12 15:20:07.688000000 Z updated_at: !ruby/object:DateTime 2018-05-15 13:51:29.749000000 Z content_type_id: image revision: 2 image: sys: id: 5pQOdclMWsYUoiqUe6UWUk created_at: !ruby/object:DateTime 2015-11-30 10:16:55.281000000 Z updated_at: !ruby/object:DateTime 2015-11-30 10:16:55.281000000 Z title: SOANTC0050054 description: url: "//images.ctfassets.net/xt8ne4gbbocd/5pQOdclMWsYUoiqUe6UWUk/55b07efecee2210caec6f0fdbc227f60/SOANTC0050054.jpg" caption: "Engraved eland, Northern Cape, South Africa. 2013,2034.18803 ©TARA/David Coulson\t" col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3731055&partId=1&searchText=2013,2034.18803&page=1 - sys: id: 57UPgZOAQgOMC2YmuSUeUA created_at: !ruby/object:DateTime 2016-09-12 15:20:19.692000000 Z updated_at: !ruby/object:DateTime 2016-09-12 19:45:24.815000000 Z content_type_id: chapter revision: 2 title: title_internal: 'South Africa: country, chapter 7' body: "Scholarly interest in Southern African rock art increased in the early 20th century and pioneering efforts were made to record both painting and engraving assemblages. In 1928 renowned archaeologist and ethnologist Leo Frobenius mounted an expedition to record sites in South Africa as well as Zimbabwe and Namibia, while in the interior regions over the previous twenty years, <NAME> had instigated the first systematic rock engraving recording work. This endeavor was built upon from the late 1950s onwards with the extensive work of Gerhard and <NAME>. In the same decade <NAME> pioneered the practice of recording rock art through colour photography, and over the next twenty years, further recording and analysis projects were undertaken by researchers such as <NAME> in the Western Cape region and <NAME> and <NAME> in the Drakensberg mountain area. \n" - sys: id: 3ji8ZxGSA0qEugGSKc4AiM created_at: !ruby/object:DateTime 2016-09-12 15:20:34.228000000 Z updated_at: !ruby/object:DateTime 2018-05-15 13:52:17.397000000 Z content_type_id: image revision: 3 image: sys: id: 49XE8B9AUwcsyuwKS4qIoS created_at: !ruby/object:DateTime 2016-09-12 15:20:29.384000000 Z updated_at: !ruby/object:DateTime 2016-09-12 15:20:29.384000000 Z title: SOADRB0040015 description: url: "//images.ctfassets.net/xt8ne4gbbocd/49XE8B9AUwcsyuwKS4qIoS/0497ecca68dfaaf3b2656a890cff67dd/SOADRB0040015.jpg" caption: "Multiple painted eland and other antelope, Eland Cave, Drakensberg Mountains, South Africa. 2013,2034.18216 ©TARA/<NAME>\t" col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3738339&partId=1&searchText=2013,2034.18216&page=1 - sys: id: 2JAfr47aaAUicKcoeSqiGu created_at: !ruby/object:DateTime 2016-09-12 15:20:41.600000000 Z updated_at: !ruby/object:DateTime 2016-10-24 12:33:33.820000000 Z content_type_id: chapter revision: 3 title_internal: 'South Africa: country, chapter 8' body: In 1976, Vinnicombe published the seminal work *"People of the Eland"*, analysing paintings from 150 Drakensberg sites and attempting to gain insight into their execution and significance through a combination of quantitative study and reference to San&#124;Bushman ethnography (written records of insights from San&#124;Bushman culture compiled by anthropologists). Through the 1980s, interpretation of rock art was further developed, perhaps most significantly by <NAME>, a collaborator of Vinnicombe's. Lewis-Williams originated an approach to understanding San&#124;Bushman rock art which posits that the motivation and meaning for most, if not all, San&#124;Bushman rock art is based on the centrality of the spiritual leader or'shaman' and the shaman’s actions in San&#124;Bushman life and belief. Over the past 30 years, the idea that much of San&#124;Bushman rock art is essentially ‘shamanistic’ in nature has been dominant in academic discourse. - sys: id: 21vXKwU4akskQ6YAsYIo0i created_at: !ruby/object:DateTime 2016-09-12 15:20:48.780000000 Z updated_at: !ruby/object:DateTime 2016-10-24 12:36:25.686000000 Z content_type_id: chapter revision: 4 title: Themes and interpretations title_internal: 'South Africa: country, chapter 9' body: "Shamanistic interpretations of San&#124;Bushman paintings and engravings draw on both past records of ‘Southern’ or /Xam San&#124;Bushman people living historically in South Africa and more recent ethnography based mainly on San&#124;Bushman communities in Namibia and Botswana, suggesting that their imagery illustrated and reinforced the power of the actions of shamans. Much of the imagery is proposed to reflect the shaman’s hallucinatory visions from the 'trance dance’, a tradition common to San&#124;Bushman groups where shamans enter a trance state during which they visit a 'spirit world' in which they may go on spiritual journeys or perform tasks on behalf of their communities. It is thought that the rock art panels may have acted as reservoirs for the 'potency' that shamans are considered to possess, with the rock face considered a veil between both worlds. The images are thought to reflect trance experiences including those of 'therianthropes’, images of figures with both human and animal features, explained as shamans who in a trance state feel themselves transformed into animals. Certain other poses and features found in San&#124;Bushman rock art, such as so-called 'entoptic' motifs—geometric shapes such as zigzags and dots—have also been interpreted as reflecting visions that shamans experience while in a trance state. \n\nDiscussion continues around the extent of the applicability of 'shamanist' interpretations for all aspects of San&#124;Bushman art, with research ongoing and scholars also exploring the potential roles of other elements in rock art production, such as mythology or gender and initiation rites. Other avenues of study include more regional foci, on specific cultural and temporal contexts and how the imagery may reflect local power dynamics through time.\n" - sys: id: 6PJbU7cpFYUUMSYqEgS0Am created_at: !ruby/object:DateTime 2016-09-12 15:21:09.071000000 Z updated_at: !ruby/object:DateTime 2018-05-15 13:52:56.704000000 Z content_type_id: image revision: 3 image: sys: id: 2hL4pRsxIkw224k00EKeqQ created_at: !ruby/object:DateTime 2016-09-12 15:21:03.996000000 Z updated_at: !ruby/object:DateTime 2016-09-12 15:21:03.996000000 Z title: SOADRB0110028 description: url: "//images.ctfassets.net/xt8ne4gbbocd/2hL4pRsxIkw224k00EKeqQ/a0c3c33b1a178f24852aec444656fe55/SOADRB0110028.jpg" caption: Three painted ‘therianthrope’ figures with antelopes’ heads. Giant’s Castle Main Caves, Drakensberg Mountains, South Africa. 2013,2034.18474 ©TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3738986&partId=1&searchText=2013,2034.18474&page=1 - sys: id: 3AxyfldmRa4wWoGSgc2cei created_at: !ruby/object:DateTime 2016-09-12 15:21:17.413000000 Z updated_at: !ruby/object:DateTime 2016-09-12 15:21:17.413000000 Z content_type_id: chapter revision: 1 title_internal: 'South Africa: country, chapter 10' body: 'Although the focus in South African rock art research has been on San&#124;Bushman art, research has also been done on other rock art traditions, suggesting different cultural origins. For example, investigation of Northern Sotho rock art has shown much of it to have been created in relation to boys''and girls'' initiation ceremonies, while Bantu-language speakers''engravings of interlinked circle patterns have been interpreted as images of idealised conceptualised homesteads. Work on attribution for some rock art of uncertain authorship also has been undertaken. Certain geometric forms of rock engraving may be of Khoekhoen origin, possibly showing influence from central African geometric traditions and tracing historical migrations southwards. It has also been suggested that some finger-painted images in the centre of the country are the early 19th century work of the Korana people, a group of mixed ancestry living as raiders on the Cape frontier and incorporating motifs from San&#124;Bushman and other traditions. ' - sys: id: 4uS7XV338ke8iiQQ6asKC4 created_at: !ruby/object:DateTime 2016-09-12 15:21:30.588000000 Z updated_at: !ruby/object:DateTime 2016-09-12 15:21:30.588000000 Z content_type_id: chapter revision: 1 title: Chronology title_internal: 'South Africa: country, chapter 11' body: "The earliest scientifically dated examples of clearly visible painted parietal art in South Africa comes from Steenbokfontein Cave in the Western Cape, where collapsed painted portions from the wall buried in sediment have been radiocarbon dated to at least 3,600 years ago, while in the Drakensberg, AMS dating carried out on the oxalate crust superimposing a painting of a human figure has suggested it to be at least 1,800 years old. While it is thought that the beginnings of the painting tradition in the Drakensberg region are probably older than this, the relative lack of durability in paint means that many of the existing paintings were probably made sometime within the past few hundred years. Sometimes it is apparent when this is the case - several painting sites in this region show images of both San&#124;Bushman people and Europeans riding horses and bearing firearms, which dates them to within the past 350 years and particularly the 19th century. Images of sheep and cattle also place images within the last 2,000 years. \n\nThe oldest reliably dated evidence for deliberate engraving in the country is several ochre pieces incised with abstract patterns found in a buried layer in Blombos cave in the Western Cape and dated through a number of methods to between 70 and 100,000 years ago. The earliest known figurative engraving date from the country comes from a slab with an image of a portion of an animal on it, excavated from Wonderwerk Cave in the Northern Cape and dating from around 10,200 years ago. Engravings remaining in the open are more difficult to date scientifically, and various attempts have been made to date and sequence both engravings and paintings based on style and superimposition, while recent years, work has been undertaken to apply the Harris Matrix (an archaeological sequencing technique for relative dating) method to painting chronologies in the Free State, Drakensberg and Western Cape. This involves using techniques originally conceived for charting chronology in stratigraphic layering to compare and sequence different superimposed motifs.\n" - sys: id: 2Qms4PsSqQiUMGg4c4CIaS created_at: !ruby/object:DateTime 2016-09-12 15:21:46.299000000 Z updated_at: !ruby/object:DateTime 2018-05-15 13:53:23.983000000 Z content_type_id: image revision: 2 image: sys: id: 3BojqKseXY0IQkcKOwoC6K created_at: !ruby/object:DateTime 2016-09-12 15:21:40.866000000 Z updated_at: !ruby/object:DateTime 2016-09-12 15:21:40.866000000 Z title: SOANTC0030005 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3BojqKseXY0IQkcKOwoC6K/8e3971b5cccf481e5485cab60d361961/SOANTC0030005.jpg" caption: Engraved rhinoceros. Wildebeest Kuil, Northern Cape, South Africa. 2013,2034.18669 ©TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3730722&partId=1&searchText=2013,2034.18669&page=1 citations: - sys: id: 1i9uCQ3wrss8UGuMQgC0oW created_at: !ruby/object:DateTime 2016-09-12 15:21:54.192000000 Z updated_at: !ruby/object:DateTime 2016-09-12 15:21:54.192000000 Z content_type_id: citation revision: 1 citation_line: "Eastwood, E. & Eastwood, C. 2006. Capturing the Spoor: An exploration of Southern African Rock Art. Cape Town, <NAME>\n\nLewis-Williams, J.D. & Challis, S. 2011. Deciphering Ancient Minds: The Mystery of San&#124;BushmanBushman Rock Art. London, Thames & Hudson \n\nLewis-Williams, J.D. 1981. Believing and Seeing: Symbolic Meanings in San&#124;BushmanRock Paintings. Johannesburg, University of Witwatersrand Press\n\nMaggs, T. 1995. Neglected Rock Art: The Rock Engravings of Agriculturist Communities in South Africa. South African Archaeological Bulletin. Vol. 50 No. 162 pp. 132.142\n\nMazel, A.D. 2009. Images in time: advances in the dating of Drakensberg rock art since the 1970s. In: <NAME> & <NAME>, eds., The eland’s people: new perspectives on the rock art of the Maloti/Drakensberg Bushmen. Essays in memory of Pat Vinnicombe. Johannesburg: Wits University Press, pp. 81–96\n\nOuzman, S. 2005. The Magical Arts of a Raider Nation: Central South Africa’s Korana Rock Art. South African Archaeological Society Goodwin Series 9 pp. 101-113\n\nParkington, J. 2003. Cederberg Rock Paintings. Cape Town, Krakadouw Trust\n\nParkington, <NAME>, D. & Rusch, N. 2008. Karoo rock engravings: Marking places in the landscape. Cape Town, Krakadouw Trust\n\nRussell, T. 2000. The application of the Harris Matrix to San rock art at Main Caves North, KwaZulu-Natal. South African Archaeological Bulletin 55. Pp. 60–70\n\nSmith, B. & <NAME>. Taking Stock: Identifying Khoekhoen Herder Rock Art in Southern Africa. Current Anthropology Vol. 45, No. 4. pp 499-52\n\nSolomon, A. 1994. “Mythic Women: A Study in Variability in San Rock Art and Narra-tive”. In: <NAME> & <NAME> (eds.) Contested Images: Diversity in Southern African Rock Art Research. Johannesburg, Witwatersrand University press\n \nVinnicombe, P. 1976. People of The Eland: Rock paintings of the Drakensberg Bushmen as a reflection of their life and thought. Pietermaritzburg, University of Natal Press\n\nWillcox. A. R. 1963 The Rock Art of Southern Africa. Johannesburg, <NAME> and Sons (Africa) Pty. Ltd\n\n\n\n" background_images: - sys: id: 1aEgzQ3JQqqMMoMickSsOS created_at: !ruby/object:DateTime 2015-12-08 13:39:38.428000000 Z updated_at: !ruby/object:DateTime 2015-12-08 13:39:38.428000000 Z title: SOANTC0050031 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1aEgzQ3JQqqMMoMickSsOS/abebdeda1124a78accab915f2b8d399d/SOANTC0050031.jpg" - sys: id: 46XLBNJT96QyKCOCIig68S created_at: !ruby/object:DateTime 2016-09-12 15:10:15.232000000 Z updated_at: !ruby/object:DateTime 2016-09-12 15:10:15.232000000 Z title: SOADRB0040001 description: url: "//images.ctfassets.net/xt8ne4gbbocd/46XLBNJT96QyKCOCIig68S/a332d9f15548c8771bc095a75b7c82c1/SOADRB0040001.jpg" - sys: id: 6KNIv5SuCQMMYoE4qE4S8A created_at: !ruby/object:DateTime 2016-09-12 15:11:13.130000000 Z updated_at: !ruby/object:DateTime 2018-09-19 16:28:35.718000000 Z title: SOANTC0040005 description: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3731061&partId=1&searchText=+Kimberley%2c+South+Africa&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/6KNIv5SuCQMMYoE4qE4S8A/059e102e1b8e3d44c707351e7ec9c8ed/SOANTC0040005.jpg" region: Southern Africa ---<file_sep>/_coll_country/ethiopia.md --- contentful: sys: id: 5UJqbFEWrYQ4a2cC46g6Ee created_at: !ruby/object:DateTime 2015-11-25 18:50:28.576000000 Z updated_at: !ruby/object:DateTime 2018-05-17 16:58:01.095000000 Z content_type_id: country revision: 12 name: Ethiopia slug: ethiopia col_url: http://www.britishmuseum.org/research/collection_online/search.aspx?people=197356&place=39681 map_progress: true intro_progress: true short_introduction: image_carousel: - sys: id: JvGmxF8NMGMy8k8E8E0Mm created_at: !ruby/object:DateTime 2015-11-25 20:01:43.962000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:35:32.810000000 Z title: '2013,2034.16534' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3705795&partId=1&searchText=cows+ethiopia&page=3 url: "//images.ctfassets.net/xt8ne4gbbocd/JvGmxF8NMGMy8k8E8E0Mm/81c4461e097818737e9f27d006acd9cc/ETHKIM0010014.jpg" - sys: id: 3vzwt8quvSW0oKO6eeosOk created_at: !ruby/object:DateTime 2015-11-25 20:01:21.677000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:36:23.790000000 Z title: '2013,2034.16305' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3704178&partId=1&searchText=ETHSOD0060008&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/3vzwt8quvSW0oKO6eeosOk/60e2a4af7e00079913f9b2db085adf47/ETHSOD0060008.jpg" - sys: id: 1xCXP09bCE2a62KY4k6QwW created_at: !ruby/object:DateTime 2015-11-25 20:01:52.350000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:38:25.638000000 Z title: '2013,2034.16488' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3705709&partId=1&searchText=ethiopia+red+white+painted&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/1xCXP09bCE2a62KY4k6QwW/a9328e58a128d91f5541ffda0ee702e0/ETHGOD0010033.jpg" - sys: id: 2vzueS0uoQUgMyeC6AY6iY created_at: !ruby/object:DateTime 2015-11-25 20:01:31.556000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:39:35.289000000 Z title: '2013,2034.16316' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3704167&partId=1&searchText=ETHSOD0060019&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/2vzueS0uoQUgMyeC6AY6iY/a30526c8ece93d7abf4d4beaa6213485/ETHSOD0060019.jpg" - sys: id: 58MDK4bR1egMcgKW8AMe8E created_at: !ruby/object:DateTime 2015-11-25 20:02:00.661000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:41:27.946000000 Z title: '2013,2034.16473' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3705685&partId=1&searchText=ethiopia+white+painted&page=2 url: "//images.ctfassets.net/xt8ne4gbbocd/58MDK4bR1egMcgKW8AMe8E/0b2214edcffae9c129d108cd689c947e/ETHGOD0010018.jpg" - sys: id: 6Z9zHHijMAgGuScYAwaoGg created_at: !ruby/object:DateTime 2015-11-25 20:02:19.257000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:44:01.733000000 Z title: '2013,2034.16415' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3704256&partId=1&place=107473&plaA=107473-2-2&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/6Z9zHHijMAgGuScYAwaoGg/8d9bff24b057fa4f1cb4f6bf0fd13904/ETHDAG0010020.jpg" - sys: id: 6hGkN4Ns2cooU4EscicwkY created_at: !ruby/object:DateTime 2015-11-30 14:08:12.852000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:46:30.555000000 Z title: '2013,2034.16528' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3705773&partId=1&searchText=ethiopia+red+painted+animals&page=2 url: "//images.ctfassets.net/xt8ne4gbbocd/6hGkN4Ns2cooU4EscicwkY/e47678a6bec525057a227171c7237951/ETHKIM0010008.jpg" featured_site: sys: id: 5I6VFY4EX6GOW2mCag08aU created_at: !ruby/object:DateTime 2015-11-25 11:54:40.762000000 Z updated_at: !ruby/object:DateTime 2015-12-07 20:52:58.329000000 Z content_type_id: featured_site revision: 5 title: Shepe, Ethiopia slug: shepe chapters: - sys: id: 4ixjUTf8kEQuQk4GMOy4W6 created_at: !ruby/object:DateTime 2015-11-25 10:41:05.845000000 Z updated_at: !ruby/object:DateTime 2017-01-11 11:21:10.230000000 Z content_type_id: chapter revision: 5 title_internal: 'Ethiopia: featured site, chapter 1' body: The site of Shepe (also known as Chabbé, Šappe or Mancheti) is located in the Sidamo Zone of Oromia, about 250 km to the south of Addis Ababa. The region is a fertile, forest-mountainous area traditionally dedicated to the cultivation of coffee. The site is in a narrow gorge carved by the Shepe River at 1300 m above sea level, full of vegetation and therefore difficult to detect. Along this gorge there are several notable engravings depicted in four panels, forming one of the most impressive – if secluded — rock art sites in the Horn of Africa. The site was discovered in 1965 by Fitaorari Selechi Defabatchaw, governor of the Dilla district where the site is located, and was published by <NAME> two years later. Since that, the importance of Shepe has been widely recognized and some other sites with similar engravings have been documented in the surrounding area. This group (known generically as the Shepe-Galma group) constitutes one of the main areas of Ethiopian rock art, the other being the Laga Oda-Sourré group in the Harar region. images_and_captions: - sys: id: 5EG7K0Z26cUMISeKsAww4s created_at: !ruby/object:DateTime 2015-11-25 10:47:14.674000000 Z updated_at: !ruby/object:DateTime 2015-11-25 10:47:14.674000000 Z content_type_id: image revision: 1 image: sys: id: pU5IbmTygg4ka2kYisEyc created_at: !ruby/object:DateTime 2015-11-25 10:45:07.360000000 Z updated_at: !ruby/object:DateTime 2015-11-25 10:45:07.360000000 Z title: '2013,2034.16227' description: url: "//images.ctfassets.net/xt8ne4gbbocd/pU5IbmTygg4ka2kYisEyc/72c98385edd3833e70e9763f66945e98/ETHSID0050002.jpg" caption: View of the crease where the Shepe engravings are placed. Shepe, Ethiopia. 2013,2034.16227. col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3691737&partId=1&searchText=2013,2034.16227&page=1 - sys: id: 5EG7K0Z26cUMISeKsAww4s created_at: !ruby/object:DateTime 2015-11-25 10:47:14.674000000 Z updated_at: !ruby/object:DateTime 2015-11-25 10:47:14.674000000 Z content_type_id: image revision: 1 image: sys: id: pU5IbmTygg4ka2kYisEyc created_at: !ruby/object:DateTime 2015-11-25 10:45:07.360000000 Z updated_at: !ruby/object:DateTime 2015-11-25 10:45:07.360000000 Z title: '2013,2034.16227' description: url: "//images.ctfassets.net/xt8ne4gbbocd/pU5IbmTygg4ka2kYisEyc/72c98385edd3833e70e9763f66945e98/ETHSID0050002.jpg" caption: View of the crease where the Shepe engravings are placed. Shepe, Ethiopia. 2013,2034.16227. col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3691737&partId=1&searchText=2013,2034.16227&page=1 - sys: id: 1meXvF3KKYugMos2qqyyyA created_at: !ruby/object:DateTime 2015-11-25 10:50:09.415000000 Z updated_at: !ruby/object:DateTime 2017-01-11 11:21:36.739000000 Z content_type_id: chapter revision: 2 title_internal: 'Ethiopia: featured site, chapter 2' body: 'The rock art of Shepe consists almost exclusively of engravings of humpless cows which follow very strict conventions: profile bodies, small heads with long horns seen from above, U-like bellies and udders very clearly depicted. Some of the cows have an unidentified, triangular object hanging from their left horn. In total, around 50 relatively large cows (40 to 70 cm in length) are depicted throughout the gorge walls, distributed in rows and groups to represent herds. The most original feature of these engravings is, however, the technique used to depict them: rather than carving the outline of the cows, the area around them has been lowered to provide a bas-relief effect which has no known parallels in the region. The surface of the cows has been polished to obtain a smooth appearance.' images_and_captions: - sys: id: 3t1tUJZNRY4kkQAIeKmIea created_at: !ruby/object:DateTime 2015-11-25 10:50:00.721000000 Z updated_at: !ruby/object:DateTime 2015-11-25 10:50:00.721000000 Z content_type_id: image revision: 1 image: sys: id: 4wQ6Srd7EI0ckCYoA4IaWS created_at: !ruby/object:DateTime 2015-11-25 10:45:25.200000000 Z updated_at: !ruby/object:DateTime 2015-11-25 10:45:25.200000000 Z title: '2013,2034.16236' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4wQ6Srd7EI0ckCYoA4IaWS/3b87b98a6668f272110f5baf48e65a5b/ETHSID0060007.jpg" caption: View of the Shepe main panel. Shepe, Ethiopia. 2013,2034.16236. col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3691722&partId=1&searchText=2013,2034.16236&page=1 - sys: id: 3t1tUJZNRY4kkQAIeKmIea created_at: !ruby/object:DateTime 2015-11-25 10:50:00.721000000 Z updated_at: !ruby/object:DateTime 2015-11-25 10:50:00.721000000 Z content_type_id: image revision: 1 image: sys: id: 4wQ6Srd7EI0ckCYoA4IaWS created_at: !ruby/object:DateTime 2015-11-25 10:45:25.200000000 Z updated_at: !ruby/object:DateTime 2015-11-25 10:45:25.200000000 Z title: '2013,2034.16236' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4wQ6Srd7EI0ckCYoA4IaWS/3b87b98a6668f272110f5baf48e65a5b/ETHSID0060007.jpg" caption: View of the Shepe main panel. Shepe, Ethiopia. 2013,2034.16236. col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3691722&partId=1&searchText=2013,2034.16236&page=1 - sys: id: 2MCiQOzg1WWksmyW4kiCko created_at: !ruby/object:DateTime 2015-11-25 10:51:18.446000000 Z updated_at: !ruby/object:DateTime 2015-11-25 10:51:18.446000000 Z content_type_id: chapter revision: 1 title_internal: 'Ethiopia: featured site, chapter 3' body: The chronology of the Shepe cows is difficult to determine, but stylistically they have been related to the Laga Oda paintings in the area of Harar and to other sites in Eritrea and Djibouti. According to most researchers, the Shepe figures have been ascribed to the so-called Ethiopian-Arabian style, with a generic chronology from the 3rd to the 1st millennia BC. Shepe engravings can be considered relatively naturalistic, and therefore should be among the oldest depictions of this style. Other interpretations, however, consider Shepe and the nearby sites a completely differentiated school whose chronology is still unclear but could be more recent. images_and_captions: - sys: id: 23e0al3lEEaeCEawuaEuei created_at: !ruby/object:DateTime 2015-11-25 10:51:09.956000000 Z updated_at: !ruby/object:DateTime 2015-11-25 10:51:09.956000000 Z content_type_id: image revision: 1 image: sys: id: 2NxPqNw24UkMkmY0oAeMUW created_at: !ruby/object:DateTime 2015-11-25 10:45:40.809000000 Z updated_at: !ruby/object:DateTime 2015-11-25 10:45:40.809000000 Z title: '2013,2034.16235' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2NxPqNw24UkMkmY0oAeMUW/2722889dec86c49a3d5c1fa47f5c96ff/ETHSID0060006.jpg" caption: Frontal view of one the Shepe panels. Shepe, Ethiopia. 2013,2034.16235. col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3691723&partId=1&searchText=2013,2034.16235&page=1 - sys: id: 23e0al3lEEaeCEawuaEuei created_at: !ruby/object:DateTime 2015-11-25 10:51:09.956000000 Z updated_at: !ruby/object:DateTime 2015-11-25 10:51:09.956000000 Z content_type_id: image revision: 1 image: sys: id: 2NxPqNw24UkMkmY0oAeMUW created_at: !ruby/object:DateTime 2015-11-25 10:45:40.809000000 Z updated_at: !ruby/object:DateTime 2015-11-25 10:45:40.809000000 Z title: '2013,2034.16235' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2NxPqNw24UkMkmY0oAeMUW/2722889dec86c49a3d5c1fa47f5c96ff/ETHSID0060006.jpg" caption: Frontal view of one the Shepe panels. Shepe, Ethiopia. 2013,2034.16235. col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3691723&partId=1&searchText=2013,2034.16235&page=1 - sys: id: 5Ts9l53bJ6uU4OKaqYEAMO created_at: !ruby/object:DateTime 2015-11-25 10:51:54.888000000 Z updated_at: !ruby/object:DateTime 2015-12-11 12:20:03.439000000 Z content_type_id: chapter revision: 2 title_internal: 'Ethiopia: featured site, chapter 4' body: Regarding their meaning, only conjecture can be made at present, but it seems quite likely that they were made by pastoral communities to whom cattle were fundamental. The careful depiction of the udders, the repetition of this single motif and the effort paid to achieve the bas-relief effect imply a paramount importance of cattle in the economy and society of the group that engraved them. The fact that some of the cows have what seem to be adornments hanging from the horns (a feature documented in other rock art regions as the Libyan Messak) also points in that direction. Contemporary groups, such as the Nuer in nearby Sudan have similar traditions of horn adornments, and throughout the Omo river region different techniques of embellishment (ear cutting, horn shaping, modifications of the hump) have been documented, and in all of them cattle are a key cultural mark as well as an economic resource. Of course, direct links cannot be established between these contemporary examples and the communities that made the engravings of Shepe, but the cattle depictions in the ravine are nevertheless a document of the importance and consideration given to cattle, an animal which was undoubtedly part of these groups’ identity. citations: - sys: id: 435YtX7CQ08gcuU240ucwc created_at: !ruby/object:DateTime 2015-11-25 10:52:31.089000000 Z updated_at: !ruby/object:DateTime 2015-12-11 12:20:33.907000000 Z content_type_id: citation revision: 3 citation_line: |- <NAME>. (1967): Les sculptures rupestres de Chabbè dans le Sidamo. *Annales d'Ethiopie* 7: 19-32. <NAME>. (ed.) (1995): *Tiya, l’Ethiopie des mégalithes : du biface à l’art rupestre dans la Corne de l’Afrique*. Association des publications chauvinoises (A.P.C.), Chauvigny. <NAME>., & <NAME> (2001): New sites of South Ethiopian rock engravings: <NAME>, <NAME>, and remarks on the Sappe-Galma School. *Annales d’Ethiopie*, 17: 205-224. background_images: - sys: id: 6bqPx8NVF6CsoC6kS4KkQ4 created_at: !ruby/object:DateTime 2015-12-07 20:36:14.616000000 Z updated_at: !ruby/object:DateTime 2015-12-07 20:36:14.616000000 Z title: ETHSID0080008 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6bqPx8NVF6CsoC6kS4KkQ4/2b81668d390ad745fc484b83c33c3548/ETHSID0080008.jpg" - sys: id: 6johOxHojKY4EkOqEco6c6 created_at: !ruby/object:DateTime 2015-11-25 19:45:27.772000000 Z updated_at: !ruby/object:DateTime 2015-11-25 19:45:27.772000000 Z title: ETHSOD0030007 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6johOxHojKY4EkOqEco6c6/2640f76a5871320bf2ff03fefd8c37a7/ETHSOD0030007.jpg" key_facts: sys: id: 1jkynD2NtMOCIIQeUAMsQu created_at: !ruby/object:DateTime 2015-11-25 18:36:57.233000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:36:57.233000000 Z content_type_id: country_key_facts revision: 1 title_internal: 'Ethiopia: key facts' image_count: 552 images date_range: Mostly 3,000 BC onwards main_areas: Harar region, Sidamo province techniques: Engravings, brush paintings, bas-relief main_themes: Cattle, anthropomorphs, geometric symbols thematic_articles: - sys: id: 2KyCxSpMowae0oksYsmawq created_at: !ruby/object:DateTime 2015-11-25 18:32:33.269000000 Z updated_at: !ruby/object:DateTime 2019-02-21 14:57:42.412000000 Z content_type_id: thematic revision: 5 title: 'The Country of the Standing Stones: Stela in Southern Ethiopia' slug: country-of-standing-stones lead_image: sys: id: 5N30tsfHVuW0AmIgeQo8Kk created_at: !ruby/object:DateTime 2015-11-25 18:01:40.103000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:01:40.103000000 Z title: ETHTBU0050002 description: url: "//images.ctfassets.net/xt8ne4gbbocd/5N30tsfHVuW0AmIgeQo8Kk/ad2ce21e5a6a89a0d4ea07bee897b525/ETHTBU0050002.jpg" chapters: - sys: id: 7lbvgOvsBO0sgeSkwU68K8 created_at: !ruby/object:DateTime 2015-11-25 18:28:36.149000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:48:54.764000000 Z content_type_id: chapter revision: 2 title_internal: 'Stela: thematic, chapter 1' body: Ethiopia is home to some of the most impressive archaeological remains in Africa, such as the rock-hewn churches of Lalibela, the Axumite kingdom monoliths or the Gondar palaces. Most of these sites are located in northern Ethiopia, but to the south of the country there are also some remarkable archaeological remains, less well-known but which deserve attention. One of them is the dozens of graveyards located along the Rift Valley and marked by hundreds of stone stelae of different types, usually decorated. Ethiopia holds the biggest concentration of steale in all Africa, a testimony of the complexity of the societies which inhabited the Horn of Africa at the beginning of the second millennium AD. - sys: id: 3q8L69s3O8YOWsS4MAI0gk created_at: !ruby/object:DateTime 2015-11-25 18:03:36.680000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:51:45.367000000 Z content_type_id: image revision: 2 image: sys: id: 3lhKPWDnSwEIKmoGaySEIy created_at: !ruby/object:DateTime 2015-11-25 18:02:34.448000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:02:34.448000000 Z title: ETHTBU0090003 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3lhKPWDnSwEIKmoGaySEIy/a330ae393d066149e80155b81694f6d3/ETHTBU0090003.jpg" caption: Engraved stela from Silté (now in the Addis Ababa National Museum), probably of a historic period, completely covered by symbols and human figures. 2013,2034.16388 ©TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3704087&partId=1&searchText=2013,2034.16388&view=list&page=1 - sys: id: wMW6zfth1mIgEiSqIy04S created_at: !ruby/object:DateTime 2015-11-25 18:28:55.931000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:52:16.164000000 Z content_type_id: chapter revision: 2 title_internal: 'Stela: thematic, chapter 2' body: Although some of the most impressive stelae are located to the north-east of Ethiopia, in the region where the Axumite Kingdom flourished between the 1st and the 10th centuries AD, the area with the highest concentration of stelae is to the south-west of the country, from the Manz region to the north of Addis Ababa to the border with Kenya. It is an extensive area which approximately follows the Rift Valley and the series of lakes that occupy its floor, and which roughly covers the Soddo, Wolayta and Sidamo regions. The region has a tropical climate and is fertile, with warm conditions being predominant and rainfall being quite abundant, with annual rates of 1200-1500 mm in the lower areas while in the highlands the rainfall reaches 2.000 mm per year. - sys: id: 5BGRogcCPeYgq2SY62eyUk created_at: !ruby/object:DateTime 2015-11-25 18:24:59.375000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:53:36.787000000 Z content_type_id: image revision: 2 image: sys: id: 3HHuQorm12WGUu0kC0Uce created_at: !ruby/object:DateTime 2015-11-25 18:02:09.630000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:02:09.630000000 Z title: ETHTBU0080002 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3HHuQorm12WGUu0kC0Uce/cf9d160fced55a45a8cb0cc9db8cbd54/ETHTBU0080002.jpg" caption: Two stelae on which are carved human figures. The faces have carved stripes, sometimes interpreted as masks. <NAME>. 2013,2034.16385 ©TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3704090&partId=1&searchText=2013,2034.16385&view=list&page=1 - sys: id: 3CBiLCh7ziUkMC264I4oSw created_at: !ruby/object:DateTime 2015-11-25 18:29:16.601000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:58:41.825000000 Z content_type_id: chapter revision: 2 title_internal: 'Stela: thematic, chapter 3' body: 'Ethiopian stelae have been known to western scholars since the end of the 19th century, with the first examples documented in 1885 to the north of Addis Ababa and the news about the main group to the south arriving in 1905. The first archaeological works in the southern area took place in the 1920’s carried out by French and German researchers. The work of Père Azaïs was especially remarkable, with four expeditions undertaken between 1922 and 1926 which were partially published in 1931. Along with Azaïs, a German team from the Frobénius Institute started to study the site of Tuto Fela, a huge cemetery with hundreds of phallic and anthropomorphic stelae located in the Sidamo region. Since these early studies the archaeological remains were left unattended until the 1970’s, when <NAME> excavated the site of Gattira-Demma and organized a far more systematic survey in the area which documented dozens of stelae of different sizes and types. In the 1980’s, another French team started to study first Tiya and then <NAME> and another important site, Chelba-Tutitti, in a long-term project which has been going on for thirty years and has been paramount to understand the types, chronologies and distribution of these archaeological remains. The historical importance of these stelae was universally recognized in 1980, when Tiya was listed as a UNESCO World Heritage Site. ' - sys: id: 3OqDncSoogykaUgAyW0Mei created_at: !ruby/object:DateTime 2015-11-25 18:25:18.604000000 Z updated_at: !ruby/object:DateTime 2018-05-15 16:00:14.418000000 Z content_type_id: image revision: 2 image: sys: id: 5Zt1z4iJ44c2MWmWcGy4Ey created_at: !ruby/object:DateTime 2015-11-25 18:01:40.088000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:01:40.088000000 Z title: ETHSID0010002 description: url: "//images.ctfassets.net/xt8ne4gbbocd/5Zt1z4iJ44c2MWmWcGy4Ey/7a08db34b4eba7530b9efb69f42fec36/ETHSID0010002.jpg" caption: View of the Tuto Fela site, showing some of the stelae standing over the burials. The stelae are anthropomorphic, corresponding to the second phase of the cemetery. 2013,2034.16196 ©TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3703783&partId=1&searchText=2013,2034.16196&view=list&page=1 - sys: id: 5NnJiqSSNGkOuooYIEYIWO created_at: !ruby/object:DateTime 2015-11-25 18:25:38.253000000 Z updated_at: !ruby/object:DateTime 2018-05-15 16:01:28.688000000 Z content_type_id: image revision: 2 image: sys: id: 5N30tsfHVuW0AmIgeQo8Kk created_at: !ruby/object:DateTime 2015-11-25 18:01:40.103000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:01:40.103000000 Z title: ETHTBU0050002 description: url: "//images.ctfassets.net/xt8ne4gbbocd/5N30tsfHVuW0AmIgeQo8Kk/ad2ce21e5a6a89a0d4ea07bee897b525/ETHTBU0050002.jpg" caption: Back of the Tiya stelae, showing the graves attached to them. 2013,2034.16345 ©TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3704130&partId=1&searchText=2013,2034.16345&view=list&page=1 - sys: id: 66kOG829XiiESyKSYUcOkI created_at: !ruby/object:DateTime 2015-11-25 18:29:40.626000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:29:40.626000000 Z content_type_id: chapter revision: 1 title_internal: 'Stela: thematic, chapter 4' body: 'The Ethiopian stelae show a great variability in shapes and decorations, but at least three main groups could be defined. The first corresponds to the so-called phallic stelae, long cylindrical stones with a hemispherical top delimited by a groove or ring (Jossaume 2012: 97). The body of the stela is sometimes decorated with simple geometric patterns. A second type is known as anthropomorphic, with the top of the piece carved to represent a face and the rest of the piece decorated with crossed patterns. These two types are common to the east of the Rift Valley lakes, while to the south of Addis Ababa and to the west of these lakes several other types are present, most of them representing anthropomorphs but sometimes plain instead of cylindrical. These figures are usually classified depending on the shape and especially the features engraved on them –masks, pendants, swords- with the most lavishly carved considered the most recent. Probably the best known group is that with swords represented, such as those of Tiya, characterized by plain stones in which groups of swords (up to nineteen) are depicted along with dots and other unidentified symbols. Not all the stelae have these weapons, although those that don’t are otherwise identical in shape and have other common signs engraved on them. Regarding their chronology the Ethiopian stela seem to be relatively new, dated from the 10th to the 13th centuries, sometimes with one type of stela superimposed on another and in other cases with old types being reused in later tombs.' - sys: id: 66jbDvBWhykGwIOOmaYesY created_at: !ruby/object:DateTime 2015-11-25 18:26:18.279000000 Z updated_at: !ruby/object:DateTime 2018-05-15 16:04:13.365000000 Z content_type_id: image revision: 4 image: sys: id: 5Bpxor1k1GMmUOoEWWqK2k created_at: !ruby/object:DateTime 2015-11-25 18:02:34.437000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:02:34.437000000 Z title: ETHSOD0050002 description: url: "//images.ctfassets.net/xt8ne4gbbocd/5Bpxor1k1GMmUOoEWWqK2k/a6ec0e80da1e2b1c7cecdf2ee7951b9e/ETHSOD0050002.jpg" caption: Example of a phallic cylindrical stela, Gido Wamba, Ethiopia. 2013,2034.16290 ©TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3703913&partId=1&searchText=2013,2034.16290&&page=1 - sys: id: 3gftSkoIHSsmeCU6M8EkcE created_at: !ruby/object:DateTime 2015-11-25 18:27:02.886000000 Z updated_at: !ruby/object:DateTime 2018-05-15 16:06:02.999000000 Z content_type_id: image revision: 2 image: sys: id: 6WDEsfzmqQGkyyGImgYmcU created_at: !ruby/object:DateTime 2015-11-25 18:02:24.547000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:02:24.547000000 Z title: ETHTBU0050025 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6WDEsfzmqQGkyyGImgYmcU/5055128d6e0e0b51216e0daeb59c6728/ETHTBU0050025.jpg" caption: Examples of a plain stela with swords at Tiya, Ethiopia. 2013,2034.16365 ©TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3704110&partId=1&searchText=2013,2034.16365&page=1 - sys: id: 41cBMB2SpOEqy0m66k64Gc created_at: !ruby/object:DateTime 2015-11-25 18:29:58.521000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:29:58.521000000 Z content_type_id: chapter revision: 1 title_internal: 'Stela: thematic, chapter 5' body: 'Regardless of their chronology and shape, most of the stela seem to have a funerary function, marking the tombs of deceased which were buried in cemeteries sometimes reaching hundreds of graves. The information collected from sites of such as Tuto Fela show that not all the burials had an attached stela, and considering the amount of work necessary to prepare them those which had could be interpreted as belonging to high status people. In some cases, such as in Tiya, it seems evident that the stela marked the graves of important personalities within their communities. It is difficult to determine who the groups that carved these stelae were, but given their chronology it seems that they could have been Cushitic or Nilotic-speaking pastoralist communities absorbed by the Oromo expansion that took place in the sixteenth century. A lot of research has still to be done about these graveyards and their associated living spaces, and undoubtedly many groups of stelae are yet to be discovered. Those studied show, however, the potential interest of ancient communities still poorly known but which were able to develop complex societies and these material expressions of authority and power. ' - sys: id: 5DJsnYIbRKiAiOqYMWICau created_at: !ruby/object:DateTime 2015-11-25 18:27:29.739000000 Z updated_at: !ruby/object:DateTime 2018-05-15 16:07:15.282000000 Z content_type_id: image revision: 2 image: sys: id: 5zepzVfNDiOQy8gOyAkGig created_at: !ruby/object:DateTime 2015-11-25 18:02:34.369000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:02:34.369000000 Z title: ETHTBU0010003 description: url: "//images.ctfassets.net/xt8ne4gbbocd/5zepzVfNDiOQy8gOyAkGig/3131691f0940b7f5c823ec406b1acd03/ETHTBU0010003.jpg" caption: Stela graveyard in Meskem. 2013,2034.16330 ©TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3704143&partId=1&searchText=2013,2034.16330&page=1 citations: - sys: id: 6LBJQl0eT62A06YmiSqc4W created_at: !ruby/object:DateTime 2015-11-25 18:28:00.511000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:28:00.511000000 Z content_type_id: citation revision: 1 citation_line: | <NAME> (dir.) (1995): *Tiya, l'Éthiopie des Mégalithes, du Biface a l'Art Rupestre dans la Corne d'Afrique*. Paris, UNESCO/CNS. <NAME>. (2007): Tuto Fela et les stèles du sud de l'Ethiopie. Paris, Éditions recherche sur les civilisations. <NAME>. (2012): The Superimposed Cemeteries of Tuto Fela in Gedeo Country (Ethiopia), and Thoughts on the Site of Chelba-Tutitti. *Palethnology*, 4, 87-110. background_images: - sys: id: 3HHuQorm12WGUu0kC0Uce created_at: !ruby/object:DateTime 2015-11-25 18:02:09.630000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:02:09.630000000 Z title: ETHTBU0080002 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3HHuQorm12WGUu0kC0Uce/cf9d160fced55a45a8cb0cc9db8cbd54/ETHTBU0080002.jpg" - sys: id: 5zepzVfNDiOQy8gOyAkGig created_at: !ruby/object:DateTime 2015-11-25 18:02:34.369000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:02:34.369000000 Z title: ETHTBU0010003 description: url: "//images.ctfassets.net/xt8ne4gbbocd/5zepzVfNDiOQy8gOyAkGig/3131691f0940b7f5c823ec406b1acd03/ETHTBU0010003.jpg" - sys: id: 5HZTuIVN8AASS4ikIea6m6 created_at: !ruby/object:DateTime 2017-12-19 12:27:08.508000000 Z updated_at: !ruby/object:DateTime 2017-12-19 12:27:08.508000000 Z content_type_id: thematic revision: 1 title: Introduction to rock art in central and eastern Africa slug: rock-art-in-central-and-east-africa lead_image: sys: id: 3esXNapo5GOWIKSImcY4QW created_at: !ruby/object:DateTime 2015-11-25 18:56:43.836000000 Z updated_at: !ruby/object:DateTime 2017-12-15 17:01:05.082000000 Z title: '2013,2034.12982' description: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3776396 url: "//images.ctfassets.net/xt8ne4gbbocd/3esXNapo5GOWIKSImcY4QW/6436b2034659eccb953844b21a400070/2013_2034.12982.jpg" chapters: - sys: id: 4ln5fQLq2saMKsOA4WSAgc created_at: !ruby/object:DateTime 2015-11-25 19:09:33.580000000 Z updated_at: !ruby/object:DateTime 2015-12-11 11:17:25.155000000 Z content_type_id: chapter revision: 4 title: Central and East Africa title_internal: 'East Africa: regional, chapter 1' body: |- Central Africa is dominated by vast river systems and lakes, particularly the Congo River Basin. Characterised by hot and wet weather on both sides of the equator, central Africa has no regular dry season, but aridity increases in intensity both north and south of the equator. Covered with a forest of about 400,000 m² (1,035,920 km²), it is one of the greenest parts of the continent. The rock art of central Africa stretches from the Zambezi River to the Angolan Atlantic coast and reaches as far north as Cameroon and Uganda. Termed the ‘schematic rock art zone’ by <NAME> (1959), it is dominated by finger-painted geometric motifs and designs, thought to extend back many thousands of years. Eastern Africa, from the Zambezi River Valley to Lake Turkana, consists largely of a vast inland plateau with the highest elevations on the continent, such as Mount Kilimanjaro (5,895m above sea level) and Mount Kenya (5,199 m above sea level). Twin parallel rift valleys run through the region, which includes the world’s second largest freshwater lake, Lake Victoria. The climate is atypical of an equatorial region, being cool and dry due to the high altitude and monsoon winds created by the Ethiopian Highlands. The rock art of eastern Africa is concentrated on this plateau and consists mainly of paintings that include animal and human representations. Found mostly in central Tanzania, eastern Zambia and Malawi; in comparison to the widespread distribution of geometric rock art, this figurative tradition is much more localised, and found at just a few hundred sites in a region of less than 100km in diameter. - sys: id: 4nyZGLwHTO2CK8a2uc2q6U created_at: !ruby/object:DateTime 2015-11-25 18:57:48.121000000 Z updated_at: !ruby/object:DateTime 2017-12-15 17:05:00.916000000 Z content_type_id: image revision: 2 image: sys: id: 3esXNapo5GOWIKSImcY4QW created_at: !ruby/object:DateTime 2015-11-25 18:56:43.836000000 Z updated_at: !ruby/object:DateTime 2017-12-15 17:01:05.082000000 Z title: '2013,2034.12982' description: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3776396 url: "//images.ctfassets.net/xt8ne4gbbocd/3esXNapo5GOWIKSImcY4QW/6436b2034659eccb953844b21a400070/2013_2034.12982.jpg" caption: Laikipia, Kenya. 2013,2034.12982 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3776396 - sys: id: 1OvIWDPyXaCO2gCWw04s06 created_at: !ruby/object:DateTime 2015-11-25 19:10:23.723000000 Z updated_at: !ruby/object:DateTime 2015-12-11 11:18:19.325000000 Z content_type_id: chapter revision: 2 title_internal: 'East Africa: regional, chapter 2' body: This collection from Central and East Africa comprises rock art from Kenya, Uganda and Tanzania, as well as the Horn of Africa; although predominantly paintings, engravings can be found in most countries. - sys: id: 4JqI2c7CnYCe8Wy2SmesCi created_at: !ruby/object:DateTime 2015-11-25 19:10:59.991000000 Z updated_at: !ruby/object:DateTime 2016-10-17 13:34:14.653000000 Z content_type_id: chapter revision: 3 title: History of research title_internal: 'East Africa: regional, chapter 3' body: |- The rock art of East Africa, in particular the red paintings from Tanzania, was extensively studied by Mary and <NAME> in the 1930s and 1950s. <NAME> observed Sandawe people of Tanzania making rock paintings in the mid-20th century, and on the basis of oral traditions argued that the rock art was made for three main purposes: casual art; magic art (for hunting purposes or connected to health and fertility) and sacrificial art (to appease ancestral spirits). Subsequently, during the 1970s Fidelis Masao and <NAME> recorded numerous sites, classifying the art in broad chronological and stylistic categories, proposing tentative interpretations with regard to meaning. There has much debate and uncertainty about Central African rock art. The history of the region has seen much mobility and interaction of cultural groups and understanding how the rock art relates to particular groups has been problematic. Pioneering work in this region was undertaken by <NAME> in central Malawi in the early 1920s, <NAME> visited Zambia in 1936 and attempted to provide a chronological sequence and some insight into the meaning of the rock art. Since the 1950s (Clarke, 1959), archaeologists have attempted to situate rock art within broader archaeological frameworks in order to resolve chronologies, and to categorise the art with reference to style, colour, superimposition, subject matter, weathering, and positioning of depictions within the panel (Phillipson, 1976). Building on this work, our current understanding of rock in this region has been advanced by <NAME> (1995, 1997, 2001) with his work in Zambia and Malawi. - sys: id: 35HMFoiKViegWSY044QY8K created_at: !ruby/object:DateTime 2015-11-25 18:59:25.796000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:51:25.789000000 Z content_type_id: image revision: 5 image: sys: id: 6KOxC43Z9mYCuIuqcC8Qw0 created_at: !ruby/object:DateTime 2015-11-25 18:57:00.077000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:57:00.077000000 Z title: '2013,2034.17450' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6KOxC43Z9mYCuIuqcC8Qw0/e25141d07f483d0100c4cf5604e3e525/2013_2034.17450.jpg" caption: This painting of a large antelope is possibly one of the earliest extant paintings. <NAME> believes similar paintings could be more than 28,000 years old. 2013,2034.17450 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3711689 - sys: id: 1dSBI9UNs86G66UGSEOOkS created_at: !ruby/object:DateTime 2015-12-09 11:56:31.754000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:50:18.203000000 Z content_type_id: chapter revision: 5 title: East African Rock Art title_internal: Intro to east africa, chapter 3.5 body: "Rock art of East Africa consists mainly of paintings, most of which are found in central Tanzania, and are fewer in number in eastern Zambia and Malawi; scholars have categorised them as follows:\n\n*__Red Paintings__*: \nRed paintings can be sub-divided into those found in central Tanzania and those found stretching from Zambia to the Indian Ocean.\nTanzanian red paintings include large, naturalistic animals with occasional geometric motifs. The giraffe is the most frequently painted animal, but antelope, zebra, elephant, rhino, felines and ostrich are also depicted. Later images show figures with highly distinctive stylised human head forms or hairstyles and body decoration, sometimes in apparent hunting and domestic scenes. The Sandawe and Hadza, hunter-gatherer groups, indigenous to north-central and central Tanzania respectively, claim their ancestors were responsible for some of the later art.\n\nThe area in which Sandawe rock art is found is less than 100km in diameter and occurs at just a few hundred sites, but corresponds closely to the known distribution of this group. There have been some suggestions that Sandawe were making rock art early into the 20th century, linking the art to particular rituals, in particular simbo; a trance dance in which the Sandawe communicate with the spirit world by taking on the power of an animal. The art displays a range of motifs and postures, features that can be understood by reference to simbo and to trance experiences; such as groups of human figures bending at the waist (which occurs during the *simbo* dance), taking on animal features such as ears and tails, and floating or flying; reflecting the experiences of those possessed in the dance." - sys: id: 7dIhjtbR5Y6u0yceG6y8c0 created_at: !ruby/object:DateTime 2015-11-25 19:00:07.434000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:51:51.887000000 Z content_type_id: image revision: 5 image: sys: id: 1fy9DD4BWwugeqkakqWiUA created_at: !ruby/object:DateTime 2015-11-25 18:57:11.188000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:57:11.188000000 Z title: '2013,2034.16849' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1fy9DD4BWwugeqkakqWiUA/9f8f1330c6c0bc0ff46d744488daa152/2013_2034.16849.jpg" caption: Three schematic figures formed by the use of multiple thin parallel lines. The shape and composition of the heads suggests either headdresses or elaborate hairstyles. Kondoa, Tanzania. 2013,2034.16849 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3709812 - sys: id: 1W573pi2Paks0iA8uaiImy created_at: !ruby/object:DateTime 2015-11-25 19:12:00.544000000 Z updated_at: !ruby/object:DateTime 2015-12-11 11:21:09.647000000 Z content_type_id: chapter revision: 8 title_internal: 'East Africa: regional, chapter 4' body: "Zambian rock art does not share any similarities with Tanzanian rock art and can be divided into two categories; animals (with a few depictions of humans), and geometric motifs. Animals are often highly stylised and superimposed with rows of dots. Geometric designs include, circles, some of which have radiating lines, concentric circles, parallel lines and ladder shapes. Predominantly painted in red, the remains of white pigment is still often visible. David Phillipson (1976) proposed that the naturalistic animals were earlier in date than geometric designs. Building on Phillipson’s work, <NAME> studied ethnographic records and demonstrated that geometric motifs were made by women or controlling the weather.\n\n*__Pastoralist paintings__*: \nPastoralist paintings are rare, with only a few known sites in Kenya and other possible sites in Malawi. Usually painted in black, white and grey, but also in other colours, they include small outlines, often infilled, of cattle and are occasional accompanied by geometric motifs. Made during the period from 3,200 to 1,800 years ago the practice ceased after Bantu language speaking people had settled in eastern Africa. Similar paintings are found in Ethiopia but not in southern Africa, and it has been assumed that these were made by Cushitic or Nilotic speaking groups, but their precise attribution remains unclear (Smith, 2013:154).\n" - sys: id: 5jReHrdk4okicG0kyCsS6w created_at: !ruby/object:DateTime 2015-11-25 19:00:41.789000000 Z updated_at: !ruby/object:DateTime 2017-12-15 17:10:04.890000000 Z content_type_id: image revision: 3 image: sys: id: 1hoZEK3d2Oi8iiWqoWACo created_at: !ruby/object:DateTime 2015-11-25 18:56:43.848000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:56:43.848000000 Z title: '2013,2034.13653' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1hoZEK3d2Oi8iiWqoWACo/1a1adcfad5d5a1cf0a341316725d61c4/2013_2034.13653.jpg" caption: Two red bulls face right. Mt Elgon, Kenya. 2013,2034.13653. © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3700058 - sys: id: 7rFAK9YoBqYs0u0EmCiY64 created_at: !ruby/object:DateTime 2015-11-25 19:00:58.494000000 Z updated_at: !ruby/object:DateTime 2017-12-15 17:11:37.760000000 Z content_type_id: image revision: 3 image: sys: id: 3bqDVyvXlS0S6AeY2yEmS8 created_at: !ruby/object:DateTime 2015-11-25 18:56:43.880000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:56:43.880000000 Z title: '2013,2034.13635' description: url: "//images.ctfassets.net/xt8ne4gbbocd/3bqDVyvXlS0S6AeY2yEmS8/c9921f3d8080bcef03c96c6b8f1b0323/2013_2034.13635.jpg" caption: Two cattle with horns in twisted perspective. Mt Elgon, Kenya. 2013,2034.13635. © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3698905 - sys: id: 1tX4nhIUgAGmyQ4yoG6WEY created_at: !ruby/object:DateTime 2015-11-25 19:14:33.823000000 Z updated_at: !ruby/object:DateTime 2015-11-25 19:14:33.823000000 Z content_type_id: chapter revision: 1 title_internal: 'East Africa: regional, chapter 5' body: |- *__Late White Paintings__*: Commonly painted in white, or off-white with the fingers, so-called ‘Late White’ depictions include quite large crudely rendered representations of wild animals, mythical animals, human figures and numerous geometric motifs. These paintings are attributed to Bantu language speaking, iron-working farmers who entered eastern Africa about 2,000 years ago from the west on the border of Nigeria and Cameroon. Moving through areas occupied by the Batwa it is thought they learned the use of symbols painted on rock, skin, bark cloth and in sand. Chewa peoples, Bantu language speakers who live in modern day Zambia and Malawi claim their ancestors made many of the more recent paintings which they used in rites of passage ceremonies. - sys: id: 35dNvNmIxaKoUwCMeSEO2Y created_at: !ruby/object:DateTime 2015-11-25 19:01:26.458000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:52:15.838000000 Z content_type_id: image revision: 4 image: sys: id: 6RGZZQ13qMQwmGI86Ey8ei created_at: !ruby/object:DateTime 2015-11-25 18:57:11.188000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:57:11.188000000 Z title: '2013,2034.16786' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6RGZZQ13qMQwmGI86Ey8ei/6d37a5bed439caf7a1223aca27dc27f8/2013_2034.16786.jpg" caption: Under a long narrow granite overhang, Late White designs including rectangular grids, concentric circles and various ‘square’ shapes. 2013,2034.16786 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3709608 - sys: id: 2XW0X9BzFCa8u2qiKu6ckK created_at: !ruby/object:DateTime 2015-11-25 19:01:57.959000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:53:21.559000000 Z content_type_id: image revision: 4 image: sys: id: 1UT4r6kWRiyiUIYSkGoACm created_at: !ruby/object:DateTime 2015-11-25 18:57:11.138000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:57:11.138000000 Z title: '2013,2034.16797' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1UT4r6kWRiyiUIYSkGoACm/fe915c6869b6c195d55b5ef805df7671/2013_2034.16797.jpg" caption: A monuments guard stands next to Late White paintings attributed to Bantu speaking farmers in Tanzania, probably made during the last 700 years. 2013,2034.16797 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3709628 - sys: id: 3z28O8A58AkgMUocSYEuWw created_at: !ruby/object:DateTime 2015-11-25 19:15:04.047000000 Z updated_at: !ruby/object:DateTime 2015-11-25 19:15:04.047000000 Z content_type_id: chapter revision: 1 title_internal: 'East Africa: regional, chapter 6' body: |- *__Meat-feasting paintings__*: Meat-feasting shelters exist from northern Tanzania through Kenya to Lake Turkana, and are places where Maa-speaking initiated men, who are not permitted to eat meat in their homes, gather to kill and feast on animals, predominantly cattle. The term Maa relates to a group of closely related Eastern Nilotic languages, which historically dominated the east African hinterland; and today is spoken by around a million people. During or after feasting, symbols of the animals that had been eaten were painted on the shelter ceiling in white or less often red. Maa speakers brand their cattle and camels with symbols that signify the lineage of their owners, but may also indicate if an animal has been treated for a particular disease. Different symbols may be used for male and female animals. Over the centuries, because the depictions are on the ceiling of meat feasting rock shelters, and because sites are used even today, a build-up of soot has obscured or obliterated the paintings. Unfortunately, few have been recorded or mapped. - sys: id: 1yjQJMFd3awKmGSakUqWGo created_at: !ruby/object:DateTime 2015-11-25 19:02:23.595000000 Z updated_at: !ruby/object:DateTime 2017-12-15 17:19:11.619000000 Z content_type_id: image revision: 3 image: sys: id: p4E0BRJzossaus6uUUkuG created_at: !ruby/object:DateTime 2015-11-25 18:56:49.743000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:56:49.743000000 Z title: '2013,2034.13004' description: url: "//images.ctfassets.net/xt8ne4gbbocd/p4E0BRJzossaus6uUUkuG/13562eee76ac2a9efe8c0d12e62fa23a/2013_2034.13004.jpg" caption: Huge granite boulder with Ndorobo man standing before a rock overhang used for meat-feasting. Laikipia, Kenya. 2013,2034. 13004. © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3700175 - sys: id: 6lgjLZVYrY606OwmwgcmG2 created_at: !ruby/object:DateTime 2015-11-25 19:02:45.427000000 Z updated_at: !ruby/object:DateTime 2017-12-15 17:20:14.877000000 Z content_type_id: image revision: 3 image: sys: id: 1RLyVKKV8MA4KEk4M28wqw created_at: !ruby/object:DateTime 2015-11-25 18:57:11.150000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:57:11.150000000 Z title: '2013,2034.13018' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1RLyVKKV8MA4KEk4M28wqw/044529be14a590fd1d0da7456630bb0b/2013_2034.13018.jpg" caption: This symbol is probably a ‘brand’ used on cattle that were killed and eaten at a Maa meat feast. Laikipia, Kenya. 2013,2034.13018 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3700193 - sys: id: 5UQc80DUBiqqm64akmCUYE created_at: !ruby/object:DateTime 2015-11-25 19:15:34.582000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:53:53.936000000 Z content_type_id: chapter revision: 4 title: Central African Rock Art title_internal: 'East Africa: regional, chapter 7' body: The rock art of central Africa is attributed to hunter-gatherers known as Batwa. This term is used widely in eastern central and southern Africa to denote any autochthonous hunter-gatherer people. The rock art of the Batwa can be divided into two categories which are quite distinctive stylistically from the Tanzanian depictions of the Sandawe and Hadza. Nearly 3,000 sites are currently known from within this area. The vast majority, around 90%, consist of finger-painted geometric designs; the remaining 10% include highly stylised animal forms (with a few human figures) and rows of finger dots. Both types are thought to date back many thousands of years. The two traditions co-occur over a vast area of eastern and central Africa and while often found in close proximity to each other are only found together at a few sites. However, it is the dominance of geometric motifs that make this rock art tradition very distinctive from other regions in Africa. - sys: id: 4m51rMBDX22msGmAcw8ESw created_at: !ruby/object:DateTime 2015-11-25 19:03:40.666000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:54:25.415000000 Z content_type_id: image revision: 4 image: sys: id: 2MOrR79hMcO2i8G2oAm2ik created_at: !ruby/object:DateTime 2015-11-25 18:56:49.737000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:56:49.737000000 Z title: '2013,2034.15306' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2MOrR79hMcO2i8G2oAm2ik/86179e84233956e34103566035c14b76/2013_2034.15306.jpg" caption: Paintings in red and originally in-filled in white cover the underside of a rock shelter roof. The art is attributed to central African Batwa; the age of the paintings is uncertain. Lake Victoria, Uganda. 2013,2034.15306 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3691242 - sys: id: 5rNOG3568geMmIEkIwOIac created_at: !ruby/object:DateTime 2015-11-25 19:16:07.130000000 Z updated_at: !ruby/object:DateTime 2015-11-25 19:16:19.722000000 Z content_type_id: chapter revision: 2 title_internal: 'East Africa: regional, chapter 8' body: "*__Engravings__*:\nThere are a few engravings occurring on inland plateaus but these have elicited little scientific interest and are not well documented. \ Those at the southern end of Lake Turkana have been categorised into two types: firstly, animals, human figures and geometric forms and also geometric forms thought to involve lineage symbols.\nIn southern Ethiopia, near the town of Dillo about 300 stelae, some of which stand up to two metres in height, are fixed into stones and mark grave sites. People living at the site ask its spirits for good harvests. \n" - sys: id: LrZuJZEH8OC2s402WQ0a6 created_at: !ruby/object:DateTime 2015-11-25 19:03:59.496000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:54:51.576000000 Z content_type_id: image revision: 5 image: sys: id: 1uc9hASXXeCIoeMgoOuO4e created_at: !ruby/object:DateTime 2015-11-25 18:57:11.176000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:57:11.176000000 Z title: '2013,2034.16206' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1uc9hASXXeCIoeMgoOuO4e/09a7504449897509778f3b9455a42f8d/2013_2034.16206.jpg" caption: Group of anthropomorphic stelae with carved faces. <NAME>, Southern Ethiopia. 2013,2034.16206 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3703754 - sys: id: 7EBTx1IjKw6y2AUgYUkAcm created_at: !ruby/object:DateTime 2015-11-25 19:16:37.210000000 Z updated_at: !ruby/object:DateTime 2015-12-11 11:22:04.007000000 Z content_type_id: chapter revision: 2 title_internal: 'East Africa: regional, chapter 9' body: In the Sidamo region of Ethiopia, around 50 images of cattle are engraved in bas-relief on the wall of a gorge. All the engravings face right and the cows’ udders are prominently displayed. Similar engravings of cattle, all close to flowing water, occur at five other sites in the area, although not in such large numbers. - sys: id: 6MUkxUNFW8oEK2aqIEcee created_at: !ruby/object:DateTime 2015-11-25 19:04:34.186000000 Z updated_at: !ruby/object:DateTime 2017-12-19 12:22:24.891000000 Z content_type_id: image revision: 3 image: sys: id: PlhtduNGSaOIOKU4iYu8A created_at: !ruby/object:DateTime 2015-11-25 18:56:43.849000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:56:43.849000000 Z title: '2013,2034.16235' description: url: "//images.ctfassets.net/xt8ne4gbbocd/PlhtduNGSaOIOKU4iYu8A/7625c8a21caf60046ea73f184e8b5c76/2013_2034.16235.jpg" caption: Around 50 images of cattle are engraved in bas-relief into the sandstone wall of a gorge in the Sidamo region of Ethiopia. 2013,2034.16235 © TARA/David Coulson col_link: http://bit.ly/2hMU0vm - sys: id: 6vT5DOy7JK2oqgGK8EOmCg created_at: !ruby/object:DateTime 2015-11-25 19:17:53.336000000 Z updated_at: !ruby/object:DateTime 2015-12-11 11:25:38.678000000 Z content_type_id: chapter revision: 3 title: Rock art in the Horn of Africa title_internal: 'East Africa: regional, chapter 10' body: "The Horn of Africa has historically been a crossroads area between the Eastern Sahara, the Subtropical regions to the South and the Arabic Peninsula. These mixed influences can be seen in many archaeological and historical features throughout the region, the rock art being no exception. Since the early stages of research in the 1930s, a strong relationship between the rock art in Ethiopia and the Arabian Peninsula was detected, leading to the establishment of the term *Ethiopian-Arabian* rock art by Pavel Červiček in 1971. This research thread proposes a progressive evolution from naturalism to schematism, ranging from the 4th-3rd millennium BC to the near past. Although the *Ethiopian-Arabian* proposal is still widely accepted and stylistic similarities between the rock art of Somalia, Ethiopia, Yemen or Saudi Arabia are undeniable, recent voices have been raised against the term because of its excessive generalisation and lack of operability. In addition, recent research to the south of Ethiopia have started to discover new rock art sites related to those found in Uganda and Kenya.\n\nRegarding the main themes of the Horn of Africa rock art, cattle depictions seem to have been paramount, with cows and bulls depicted either isolated or in herds, frequently associated with ritual scenes which show their importance in these communities. Other animals – zebus, camels, felines, dogs, etc. – are also represented, as well as rows of human figures, and fighting scenes between warriors or against lions. Geometric symbols are also common, usually associated with other depictions; and in some places they have been interpreted as tribal or clan marks. Both engraving and painting is common in most regions, with many regional variations. \n" - sys: id: 4XIIE3lDZYeqCG6CUOYsIG created_at: !ruby/object:DateTime 2015-11-25 19:04:53.913000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:55:12.472000000 Z content_type_id: image revision: 4 image: sys: id: 3ylztNmm2cYU0GgQuW0yiM created_at: !ruby/object:DateTime 2015-11-25 18:57:11.155000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:57:11.155000000 Z title: '2013,2034.15749' description: url: "//images.ctfassets.net/xt8ne4gbbocd/3ylztNmm2cYU0GgQuW0yiM/3be240bf82adfb5affc0d653e353350b/2013_2034.15749.jpg" caption: Painted roof of rock shelter showing decorated cows and human figures. <NAME>, Somaliland. 2013,2034.15749 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3691391 - sys: id: 2IKYx0YIVOyMSwkU8mQQM created_at: !ruby/object:DateTime 2015-11-25 19:18:28.056000000 Z updated_at: !ruby/object:DateTime 2015-12-11 11:26:13.401000000 Z content_type_id: chapter revision: 2 title_internal: 'East Africa: regional, chapter 11' body: |- Rock art in the Horn of Africa faces several challenges. One of them is the lack of consolidated chronologies and absolute dating for the paintings and engravings. Another is the uneven knowledge of rock art throughout the region, with research often affected by political unrest. Therefore, distributions of rock art in the region are steadily growing as research is undertaken in one of the most interactive areas in East Africa. The rock art of Central and East Africa is one of the least documented and well understood of the corpus of African rock art. However, in recent years scholars have undertaken some comprehensive reviews of existing sites and surveys of new sites to open up the debates and more fully understand the complexities of this region. citations: - sys: id: 7d9bmwn5kccgO2gKC6W2Ys created_at: !ruby/object:DateTime 2015-11-25 19:08:04.014000000 Z updated_at: !ruby/object:DateTime 2017-12-19 12:24:18.659000000 Z content_type_id: citation revision: 2 citation_line: "<NAME>. 1996. ‘Cultural Patterns in the Rock Art of Central Tanzania.’ in *The Prehistory of Africa*. XIII International Congress of Prehistoric and Protohistoric Sciences Forli-Italia-8/14 September.\n\nČerviček, P. 1971. ‘Rock paintings of Laga Oda (Ethiopia)’ in *Paideuma*, 17, pp.121-136.\n\nClark, <NAME>. 1954. *The Prehistoric Cultures of the Horn of Africa*. New York: Octagon Press.\n\nClark, J.C.D. 1959. ‘Rock Paintings of Northern Rhodesia and Nyasaland’, in Summers, R. (ed.) *Prehistoric Rock Art of the Federation of Rhodesia & Nyasaland*: Glasgow: National Publication Trust, pp.163- 220.\n\nJoussaume, R. (ed.) 1995. Tiya, *l’Ethiopie des mégalithes : du biface à l’art rupestre dans la Corne de l’Afrique*. Association des publications chauvinoises (A.P.C.), Chauvigny.\n\n<NAME>. 1983. *Africa’s Vanishing Art – The Rock Paintings of Tanzania*. London: Hamish Hamilton Ltd.\n\nMasao, F.T. 1979. *The Later Stone Age and the Rock Paintings of Central Tanzania*. Wiesbaden: <NAME>iner Verlag. \n\nNamono, Catherine. 2010. *A contextual interpretive approach to the rock art of Uganda*. Unpublished PhD Thesis. Johannesburg: University of Witwatersrand\n\nPhillipson, D.W. 1976. ‘The Rock Paintings of Eastern Zambia’, in *The Prehistory of Eastern Zambia: Memoir 6 of the british Institute in Eastern Africa*. Nairobi.\n\n<NAME>. (1995), Rock art in south-Central Africa: A study based on the pictographs of Dedza District, Malawi and Kasama District Zambia. dissertation. Cambridge: University of Cambridge, Unpublished Ph.D. dissertation.\n\n<NAME>. (1997), Zambia’s ancient rock art: The paintings of Kasama. Zambia: The National Heritage Conservation Commission of Zambia.\n\nSmith B.W. (2001), Forbidden images: Rock paintings and the Nyau secret society of Central Malaŵi and Eastern Zambia. *African Archaeological Review*18(4): 187–211.\n\nSmith, Benjamin. 2013, ‘Rock art research in Africa; in In: Lane, P. & Mitchell, P. (eds) *Handbook of African Archaeology*. Oxford: Oxford University Press, pp.145-162.\n\nTen Raa, E. 1974. ‘A record of some prehistoric and some recent Sandawe rock paintings’ in *Tanzania Notes and Records* 75, pp.9-27." background_images: - sys: id: 4aeKk2gBTiE6Es8qMC4eYq created_at: !ruby/object:DateTime 2015-12-07 19:42:27.348000000 Z updated_at: !ruby/object:DateTime 2017-12-19 12:25:55.914000000 Z title: '2013,2034.1298' description: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3592557 url: "//images.ctfassets.net/xt8ne4gbbocd/4aeKk2gBTiE6Es8qMC4eYq/31cde536c4abf1c0795761f8e35b255c/2013_2034.1298.jpg" - sys: id: 6DbMO4lEBOU06CeAsEE8aA created_at: !ruby/object:DateTime 2015-12-07 19:41:53.440000000 Z updated_at: !ruby/object:DateTime 2017-12-19 12:26:40.898000000 Z title: '2013,2034.15749' description: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3691391 url: "//images.ctfassets.net/xt8ne4gbbocd/6DbMO4lEBOU06CeAsEE8aA/9fc2e1d88f73a01852e1871f631bf4ff/2013_2034.15749.jpg" country_introduction: sys: id: 1wLn16dmUsUkcm6UgwmaoE created_at: !ruby/object:DateTime 2015-11-25 18:43:00.803000000 Z updated_at: !ruby/object:DateTime 2015-12-07 13:42:55.895000000 Z content_type_id: country_information revision: 4 title: 'Ethiopia: country introduction' chapters: - sys: id: 31sjVVkxrOsYoCakaWWIsw created_at: !ruby/object:DateTime 2015-11-25 18:38:08.693000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:38:08.693000000 Z content_type_id: chapter revision: 1 title: Introduction title_internal: 'Ethiopia: country, chapter 1' body: Ethiopia is the biggest country of the Horn of Africa, a very diverse country which has traditionally been a melting pot of cultures, religions and ethnicities, acting as a crossroads between the Nile valley region, the Red Sea and East Africa. Most rock art is located in the southern part of the country, although smaller concentrations have been documented near the borders with Eritrea, Sudan and Kenya. Ethiopian rock art shows strong similarities with other countries in the Horn of Africa as well as Sudan and mostly consists of cow depictions dated from the 3rd millennium onwards, although other animals, anthropomorphic figures and geometric symbols are also fairly common. - sys: id: 6DDVz3LoAwAoOaE6sg0qew created_at: !ruby/object:DateTime 2015-11-25 18:38:32.241000000 Z updated_at: !ruby/object:DateTime 2017-01-10 14:34:31.428000000 Z content_type_id: chapter revision: 4 title: Geography and rock art distribution title_internal: 'Ethiopia: country, chapter 2' body: The geography of Ethiopia is varied and ranges from high plateaus to savannahs and deserts. The eastern part mostly consists of a range of plateaus and high mountains, which in some cases reach more than 4000m above sea level. To the north of these mountains is Lake Tana, the biggest lake in Ethiopia and the source of the Blue Nile, one of the two tributaries of the Nile. The mountains are divided in two by the Great Rift Valley, which runs north-east to south-west, - and is one of the most important areas for the study of human evolution. The highlands are surrounded by tropical savannah and grassland regions to the west and south-west, while to the east lays the Danakil desert, one of the most inhospitable regions on earth. The south-eastern corner of Ethiopia, which borders Somalia, is a semi-desert plateau ranging from 300-1500 m above sea level. - sys: id: W4Ffii79a8aAicMksA4G0 created_at: !ruby/object:DateTime 2015-11-25 19:40:22.095000000 Z updated_at: !ruby/object:DateTime 2017-01-10 14:42:57.195000000 Z content_type_id: image revision: 3 image: sys: id: IIbbaihhGSi02y0qamaIy created_at: !ruby/object:DateTime 2015-11-25 19:43:02.833000000 Z updated_at: !ruby/object:DateTime 2015-11-25 19:43:02.833000000 Z title: ETHNAS0005 description: url: "//images.ctfassets.net/xt8ne4gbbocd/IIbbaihhGSi02y0qamaIy/b9ff2db6b1f2d89f359fe4f4278c51af/ETHNAS0005.jpg" caption: View of landscape in southern Ethiopia. 2013,2034.16171 © <NAME>/TARA col_link: http://bit.ly/2jqquJj - sys: id: 5lRTzejpleGqe2MQ0O4k0o created_at: !ruby/object:DateTime 2015-11-25 18:38:53.256000000 Z updated_at: !ruby/object:DateTime 2017-01-10 14:48:57.742000000 Z content_type_id: chapter revision: 3 title_internal: 'Ethiopia: country, chapter 3' body: 'Ethiopian rock art is located around two main areas: around the city of Harar to the east and the Sidamo region to the south-west. The first group comprises mainly painted depictions, while the second one is characterized by a bas-relief technique specific only to this area. However, rock art has also been discovered in other areas, such as the border with Eritrea, the area near Kenya and the Benishangul-Gumuz region, a lowland area along the border with Sudan. As research increases, it is likely that more rock art sites will be discovered throughout the country. In addition to these engravings and paintings, Ethiopia is also known for its decorated stelae, tall stone obelisks that are usually engraved with culturally and religiously important symbols. One of these places is Tiya, a burial place declared a World Heritage Site which has 32 richly decorated stelae. Although not strictly rock art in the traditional sense, they nevertheless represent one of the most interesting group of archaeological remains in the south of Ethiopia and demonstrate similar techniques to some of the engraved depictions.' - sys: id: 6Aw2hC2mDSGKMsEWYOa80C created_at: !ruby/object:DateTime 2015-11-25 19:46:38.477000000 Z updated_at: !ruby/object:DateTime 2017-01-10 15:06:35.150000000 Z content_type_id: image revision: 2 image: sys: id: 4w2Qic7EkEe0omyUA2i6QU created_at: !ruby/object:DateTime 2015-11-25 19:46:16.750000000 Z updated_at: !ruby/object:DateTime 2015-11-25 19:46:16.750000000 Z title: '2013,2034.16248' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4w2Qic7EkEe0omyUA2i6QU/5b36c4b2ad5132161c8e8348f760df1c/2013_2034.16248.jpg" caption: View of engraved cow with curved horns and marked udders. Shepe, Ethiopia. 2013,2034.16248 © <NAME>/TARA col_link: http://bit.ly/2i9tddD - sys: id: 2FarnK5oM0Ese246YsW2WC created_at: !ruby/object:DateTime 2015-11-25 18:39:19.763000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:39:19.763000000 Z content_type_id: chapter revision: 1 title: Research history title_internal: 'Ethiopia: country, chapter 4' body: Ethiopian rock art has played a key role in the Horn of Africa research, and the studies undertaken in this country have structured the chronologies, styles and interpretations of the whole region. Research started as early as the mid-1930s when the Abbé Henri Breuil proposed a classification of Ethiopian rock art through the study of the Porc-Epic and Genda-Biftou sites. This proposal stated a progressive evolution in eight steps from naturalism to schematism, and set the interpretative framework for succeeding decades. Breuil’s ideas were generally followed by <NAME> in his synthesis of the rock art in the Horn of Africa in 1954, and they also appear in the work of Paolo Graziosi (1964). During the 1960s, research was carried out by <NAME> in the Sidamo area and by <NAME> near Harar, where a report made for the Ethiopian government informed about the existence of around ten rock art sites in the same area. - sys: id: 5FlXwLASzY64aWE8kyUQi0 created_at: !ruby/object:DateTime 2015-11-25 19:41:06.599000000 Z updated_at: !ruby/object:DateTime 2017-01-10 15:20:14.088000000 Z content_type_id: image revision: 2 image: sys: id: 5rOzA2mToQEA8eCoE2S6yc created_at: !ruby/object:DateTime 2015-11-25 19:44:49.577000000 Z updated_at: !ruby/object:DateTime 2015-11-25 19:44:49.577000000 Z title: ETHLAG0010030 description: url: "//images.ctfassets.net/xt8ne4gbbocd/5rOzA2mToQEA8eCoE2S6yc/8a7fad16c52c41bab12fb032ccfc026c/ETHLAG0010030.jpg" caption: View of painted cattle and human figures. Laga Oda, Ethiopia. 2013,2034.16575 © <NAME>/TARA col_link: http://bit.ly/2j3OmG6 - sys: id: 64V0g8Z7P2EYc4AyAIKuWs created_at: !ruby/object:DateTime 2015-11-25 18:39:35.423000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:39:35.423000000 Z content_type_id: chapter revision: 1 title_internal: 'Ethiopia: country, chapter 5' body: Rock art research in Ethiopia has traditionally included the term Ethiopian-Arabian style, coined in 1971 by Červiček to show the similarities between the depictions found in the Horn of Africa and the Arabian Peninsula. The existence of this style is currently the paradigm used in most rock art interpretations of the region, although some concerns have been raised due to its too generic characteristics, which can be found in many other parts of Africa. The 1990s and 2000s have seen a remarkable increase of rock art research in the country, with the renewal of studies in the main areas and the beginning of research in the regions of Tigray and Benishangul-Gumuz. - sys: id: 5NlCEmTba0OqysyQwwQcKk created_at: !ruby/object:DateTime 2015-11-25 19:41:26.088000000 Z updated_at: !ruby/object:DateTime 2017-01-10 15:21:39.681000000 Z content_type_id: image revision: 2 image: sys: id: 6jqDCZikwg60QmgaSYKsKA created_at: !ruby/object:DateTime 2015-11-25 19:44:57.045000000 Z updated_at: !ruby/object:DateTime 2015-11-25 19:44:57.045000000 Z title: ETHDAG0010003 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6jqDCZikwg60QmgaSYKsKA/43845a952bb5271b011eed5227486ec2/ETHDAG0010003.jpg" caption: View of rock shelter full of humped cattle, human figures and unidentified shapes. Saka Sharifa, Ethiopia. 2013,2034.16397 © <NAME>/TARA col_link: http://bit.ly/2iAVSEX - sys: id: 4iWjeBjtmoEKS42IImMCYI created_at: !ruby/object:DateTime 2015-11-25 18:39:53.855000000 Z updated_at: !ruby/object:DateTime 2017-01-10 15:34:19.840000000 Z content_type_id: chapter revision: 2 title: Themes title_internal: 'Ethiopia: country, chapter 6' body: Cattle and cattle-related depictions are the main subject of Ethiopian rock art, regardless of their relative chronology. The oldest depictions (based on Červiček’s works) are of humpless cows, while in the late stages of rock art humped cows and camels appear. Goats, sheep and dogs are very occasionally depicted, and unlike the Saharan rock art, wild animals such as giraffes and antelopes are scarce. Figures of cattle appear alone or in herds, and the depictions of cows with calves are a fairly common motif not only in Ethiopia but in the whole Horn of Africa. - sys: id: 4180pjSpqg2mQKuYMq66a4 created_at: !ruby/object:DateTime 2015-11-25 19:41:45.230000000 Z updated_at: !ruby/object:DateTime 2017-01-10 15:35:54.275000000 Z content_type_id: image revision: 2 image: sys: id: cyrbFGoA8wEaS8qM4Ys4c created_at: !ruby/object:DateTime 2015-11-25 19:45:06.217000000 Z updated_at: !ruby/object:DateTime 2015-11-25 19:45:06.217000000 Z title: ETHKIM0010014 description: url: "//images.ctfassets.net/xt8ne4gbbocd/cyrbFGoA8wEaS8qM4Ys4c/dae038fef2aa592df7f64faebacd63a9/ETHKIM0010014.jpg" caption: Group of humped cattle painted in white, with round heads. Kimet, Ethiopia. 2013,2034.16534 © <NAME>/TARA col_link: http://bit.ly/2iB07QT - sys: id: 3jCmlMhq00Wq8g8aSMgqc2 created_at: !ruby/object:DateTime 2015-11-25 18:40:11.167000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:40:11.167000000 Z content_type_id: chapter revision: 1 title_internal: 'Ethiopia: country, chapter 7' body: The other main group of depictions is of anthropomorphs, which are usually schematic and often distributed in rows. In some cases, the tendency to schematism is so pronounced that human figures are reduced to an H-like shape. Sometimes, human figures are represented as warriors, carrying weapons and on occasion fighting against other humans or big felines. Along with these figurative themes, geometric signs are very common in Ethiopian rock art, including groups of dots and other motifs that have been interpreted as symbols associated with groups that historically lived in the region. - sys: id: 1eqq7kEwJUWO0EgC6cqmEY created_at: !ruby/object:DateTime 2015-11-25 19:42:03.855000000 Z updated_at: !ruby/object:DateTime 2017-01-10 16:28:50.616000000 Z content_type_id: image revision: 2 image: sys: id: 1gmLTDIgQY8i4SgKUMYSc4 created_at: !ruby/object:DateTime 2015-11-25 19:45:20.229000000 Z updated_at: !ruby/object:DateTime 2015-11-25 19:45:20.229000000 Z title: ETHKIM0010016 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1gmLTDIgQY8i4SgKUMYSc4/fb8b409508be98645c1d84812937d4ab/ETHKIM0010016.jpg" caption: View of schematic, red human figure. Kimet, Ethiopia. 2013,2034.16536 © <NAME>/TARA col_link: http://bit.ly/2jqRjNt - sys: id: 6AAXBjdFN6mACg0K8kEGcQ created_at: !ruby/object:DateTime 2015-11-25 18:40:35.934000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:40:35.934000000 Z content_type_id: chapter revision: 1 title_internal: 'Ethiopia: country, chapter 8' body: 'Not all themes are distributed in every area. In Sidamo, almost all figures depict humpless cows, while subjects in the Harar region show a far bigger variability. Again, differences in techniques are also evident: while depictions in the Harar region are mainly paintings, in Sidamo many figures are engraved in a very singular way, lowering the area around the figures to achieve a bas-relief effect. The clear differences between the Sidamo engravings (known as the Chabbé-Galma group) and those of the Harar (the Laga Oda-Sourré group) have led to criticisms about the perceived uniformity of the *Ethiopian-Arabian* style.' - sys: id: 6cRf4VoFgsiuoQUaKoG6Eq created_at: !ruby/object:DateTime 2015-11-25 19:42:26.511000000 Z updated_at: !ruby/object:DateTime 2017-01-10 16:29:56.050000000 Z content_type_id: image revision: 2 image: sys: id: 6johOxHojKY4EkOqEco6c6 created_at: !ruby/object:DateTime 2015-11-25 19:45:27.772000000 Z updated_at: !ruby/object:DateTime 2015-11-25 19:45:27.772000000 Z title: ETHSOD0030007 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6johOxHojKY4EkOqEco6c6/2640f76a5871320bf2ff03fefd8c37a7/ETHSOD0030007.jpg" caption: Engraved grids and geometric signs. Ambe Akirsa, Ethiopia. 2013,2034.16270 © <NAME>/TARA col_link: http://bit.ly/2iYklVo - sys: id: 5oDcrjBLqwk44WoQge2ECA created_at: !ruby/object:DateTime 2015-11-25 18:41:00.681000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:41:00.681000000 Z content_type_id: chapter revision: 1 title: Chronology title_internal: 'Ethiopia: country, chapter 9' body: As is the case with most African rock art, absolute dates for depictions based on radiocarbon techniques are scarce, and therefore most of the chronological framework of Ethiopian rock art has to rely on the analysis of figures, superimpositions, parallels with depictions of better known areas and other indirect dating methods. In Ethiopian rock art it is generally assumed that the oldest depictions could be dated to the mid-third millennium BC, according to parallels with other Saharan rock art. As aforementioned, the so-called Ethiopian-Arabian style shows an evolution from naturalism to schematism, with an older group (Sourré-Hanakiya) showing strong similarities with rock art in Egypt, Sudan and Libya. A second, progressively schematic group (Dahtami) would last until the end of the first millennium BC. This date is supported by the appearance of camels and humped cows (zebus), which were introduced in the region at the end of the second half of the 1st millennium BC. The last stages of Ethiopian rock art relating to camel, warriors and geometric depictions can be considered to belong to the historical period, in some cases reaching very near to the present day. - sys: id: 5znoN0ALBYKoEswqOIoUQ4 created_at: !ruby/object:DateTime 2015-11-25 19:42:45.233000000 Z updated_at: !ruby/object:DateTime 2017-01-10 16:31:49.133000000 Z content_type_id: image revision: 2 image: sys: id: 5Q738mIexa8sWUwqsai8Ai created_at: !ruby/object:DateTime 2015-11-25 19:45:35.501000000 Z updated_at: !ruby/object:DateTime 2015-11-25 19:45:35.501000000 Z title: ETHGOD0010011 description: url: "//images.ctfassets.net/xt8ne4gbbocd/5Q738mIexa8sWUwqsai8Ai/89f7045007c92e674ef5854118853c04/ETHGOD0010011.jpg" caption: ": Panel infilled with painted camels, unidentified quadrupeds and geometric signs. Goda Ajewa, Ethiopia. 2013,2034.16466 © <NAME>/TARA" col_link: http://bit.ly/2jztgzY citations: - sys: id: 6KRR3bOPjUYGU8m6eA4QkC created_at: !ruby/object:DateTime 2015-11-25 18:41:41.635000000 Z updated_at: !ruby/object:DateTime 2015-12-11 11:45:00.268000000 Z content_type_id: citation revision: 2 citation_line: | <NAME>. (1971): Rock paintings of Laga Oda (Ethiopia). *Paideuma*, 17: 121-136. <NAME>. (1954): T*he Prehistoric Cultures of the Horn of Africa*. Octagon Press, New York. <NAME>. (1990): Distribution of Rock Paintings and Engravings in Ethiopia. *Proceedings of the First National Conference of Ethiopian Studies, Addis Ababa*, 1990: 289-302. background_images: - sys: id: 1rbiMJhqHeiAa6oiAy2Mug created_at: !ruby/object:DateTime 2015-11-30 14:05:39.497000000 Z updated_at: !ruby/object:DateTime 2015-11-30 14:05:39.497000000 Z title: ETHNAS0028 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1rbiMJhqHeiAa6oiAy2Mug/4a6a13cedc28fe85e925719829a46581/ETHNAS0028.jpg" - sys: id: 17M4rE7cWIwUqEcIQ6ASOw created_at: !ruby/object:DateTime 2015-11-30 14:06:21.758000000 Z updated_at: !ruby/object:DateTime 2015-11-30 14:06:21.758000000 Z title: ETHSID0050006 description: url: "//images.ctfassets.net/xt8ne4gbbocd/17M4rE7cWIwUqEcIQ6ASOw/4461313a4e2ce3f84537375936c49049/ETHSID0050006.jpg" - sys: id: 1wWti7IQucyomYeIMcYuYw created_at: !ruby/object:DateTime 2015-11-30 14:06:59.751000000 Z updated_at: !ruby/object:DateTime 2015-11-30 14:06:59.751000000 Z title: ETHLAG0010060 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1wWti7IQucyomYeIMcYuYw/84a27825be04931174d1933d7e37ec69/ETHLAG0010060.jpg" region: Eastern and central Africa ---<file_sep>/_coll_country/morocco.md --- contentful: sys: id: OVTOPBl4COkU8SqsoSWYw created_at: !ruby/object:DateTime 2015-11-26 18:52:36.781000000 Z updated_at: !ruby/object:DateTime 2018-05-17 17:11:24.639000000 Z content_type_id: country revision: 10 name: Morocco slug: morocco col_url: http://www.britishmuseum.org/research/collection_online/search.aspx?people=197356&place=40983 map_progress: true intro_progress: true image_carousel: - sys: id: 1h9eCgWFYce8eqiq2KSGkU created_at: !ruby/object:DateTime 2015-11-25 15:10:29.053000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:03:01.253000000 Z title: '2013,2034.5894' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3614035&partId=1&searchText=2013,2034.5894&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/1h9eCgWFYce8eqiq2KSGkU/830a45b1b9107528469498e3dc8c12d5/2013_2034.5894.jpg" - sys: id: 3OAdh6uCrCIgCeuQ2E0koa created_at: !ruby/object:DateTime 2015-11-25 15:10:29.049000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:03:43.993000000 Z title: '2013,2034.5874' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3613873&partId=1&searchText=2013,2034.5874&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/3OAdh6uCrCIgCeuQ2E0koa/a9fe9a0740e535707c227440bac46571/2013_2034.5874.jpg" - sys: id: 2iKZIRebewsGGQiKiOgQq created_at: !ruby/object:DateTime 2015-11-26 12:38:42.729000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:04:25.512000000 Z title: '2013,2034.5558' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3605427&partId=1&searchText=2013,2034.5558&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/2iKZIRebewsGGQiKiOgQq/7a6ea71bedef21c05b78d13fe9883716/2013_2034.5558.jpg" featured_site: sys: id: 3ljdBZ1Fra2Kokks0oYiwW created_at: !ruby/object:DateTime 2015-11-25 15:15:17.431000000 Z updated_at: !ruby/object:DateTime 2015-12-08 14:39:26.150000000 Z content_type_id: featured_site revision: 5 title: Oukaïmeden, Morocco slug: oukaimeden chapters: - sys: id: 5ggUMhTP3y0uOGcMkYkEI created_at: !ruby/object:DateTime 2015-11-25 15:16:09.455000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:16:09.455000000 Z content_type_id: chapter revision: 1 title_internal: 'Morocco: featured site, chapter 1' body: |- Oukaïmeden is an alpine-like valley set 2,630 metres above sea level at the core of Morocco’s High Atlas. Records from the 16th century onwards refer to its seasonal profit as summer pasturage by herders coming from villages settled at mid-altitude. It is a well-known place due to the existence of a ski resort, and a well-frequented tourist destination for people coming from Marrakech during the summer. It is also home to one of the most impressive collections of rock art engravings in Morocco, with about 250 rock art sites and one thousand depictions scattered throughout the valley. Oukaïmeden rock art has been thoroughly studied by Malhome (1959, 1961) and Rodrigue (1999), and along with the Yagour plateau and Jbel Rat constitute the core of High Atlas rock art. - sys: id: 5rhQdcEWMo0ewS4Sq4OWcu created_at: !ruby/object:DateTime 2015-11-25 15:11:07.744000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:11:07.744000000 Z content_type_id: image revision: 1 image: sys: id: 5A7q4PnbI4sYmQsi2u4yYg created_at: !ruby/object:DateTime 2015-11-25 15:10:29.077000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:10:29.077000000 Z title: '2013,2034.5863' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5A7q4PnbI4sYmQsi2u4yYg/95ab9db2de0532159c59d4bbe3e12316/2013_2034.5863.jpg" caption: General view of Oukaimeden valley. 2013,2034.5863 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3613833&partId=1&images=true&people=197356&museumno=2013,2034.5863&page=1 - sys: id: 5VOOpZKsb6eY2MMYacY6G4 created_at: !ruby/object:DateTime 2015-11-25 15:11:50.001000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:11:50.001000000 Z content_type_id: image revision: 1 image: sys: id: 1h9eCgWFYce8eqiq2KSGkU created_at: !ruby/object:DateTime 2015-11-25 15:10:29.053000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:03:01.253000000 Z title: '2013,2034.5894' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3614035&partId=1&searchText=2013,2034.5894&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/1h9eCgWFYce8eqiq2KSGkU/830a45b1b9107528469498e3dc8c12d5/2013_2034.5894.jpg" caption: Engraved anthropomorph surrounded by a dagger and a rectangular shield. 2013,2034.5894 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3614035&partId=1&museumno=2013%2c2034.5894&page=1 - sys: id: 6uSaQ0ylC88yMwE4sKCkcq created_at: !ruby/object:DateTime 2015-11-25 15:16:30.214000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:16:30.214000000 Z content_type_id: chapter revision: 1 title_internal: 'Morocco: featured site, chapter 2' body: High Atlas rock art is remarkably different not only from the rest of Moroccan rock art, but also from most other depictions documented throughout the Sahara. Although some of the engravings correspond to cattle depictions similar to those of nearby regions, there are other images known only in this region. One particular type comprises detailed, large human figures represented frontally, surrounded by weapons and other symbols. Another common kind of depiction is circular shapes with inner designs, which most probably represent shields. Weapons are also very common, usually depicted in isolation, but not held by warriors as is common in most of the North African images. Together with these themes, Oukaïmeden is characterised by a significant number of elephant representations (something surprising considering its altitude!) and a huge number of complex, geometric symbols whose interpretation remains obscure. - sys: id: 4uVJ5RvCgUiCuEEsKAogs2 created_at: !ruby/object:DateTime 2015-11-25 15:12:18.882000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:12:18.882000000 Z content_type_id: image revision: 1 image: sys: id: 3OAdh6uCrCIgCeuQ2E0koa created_at: !ruby/object:DateTime 2015-11-25 15:10:29.049000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:03:43.993000000 Z title: '2013,2034.5874' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3613873&partId=1&searchText=2013,2034.5874&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/3OAdh6uCrCIgCeuQ2E0koa/a9fe9a0740e535707c227440bac46571/2013_2034.5874.jpg" caption: Circular engravings (shields?). 2013,2034.5874 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3613873&partId=1&museumno=2013%2c2034.5874&page=1 - sys: id: 2rFEuu8dXSEmUYccCEwUAE created_at: !ruby/object:DateTime 2015-11-25 15:12:51.006000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:12:51.006000000 Z content_type_id: image revision: 1 image: sys: id: 2joH7nmXU42sE00g0GUgMq created_at: !ruby/object:DateTime 2015-11-25 15:10:29.068000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:10:29.068000000 Z title: '2013,2034.5907' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2joH7nmXU42sE00g0GUgMq/36076d52020d185a340141311398c879/2013_2034.5907.jpg" caption: Engraved Bronze Age halberds (two-handed pole weapons). 2013,2034.5907 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3614147&partId=1&museumno=2013%2c2034.5907+&page=1 - sys: id: 51fcUCW4Skk64u24W2yEam created_at: !ruby/object:DateTime 2015-11-25 15:16:49.016000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:16:49.016000000 Z content_type_id: chapter revision: 1 title_internal: 'Morocco: featured site, chapter 3' body: Chronologically speaking, it seems Oukaïmeden engravings started to appear during the mid-3rd millennium BC, when the Sahara desert became increasingly drier and summer grazing became more and more important. The earliest depictions consisted mainly of animals, especially cattle, which was the species that benefited the most from green pastures. As time passed, pressure on this resource grew and tensions arose among the communities that used the valley. From the 2nd millennium BC onwards, animal depictions were replaced by images of weapons and warriors, showing a different, more violent way of reclaiming rights over pastures. That situation continued during the long Libyan-Berber period that started around the mid-1st millennium BC and lasted until the Muslim conquest of the area, around the 7th century AD. The arrival of Islam does not imply the immediate disappearance of rock art engravings, but their number decreased significantly and they progressively lost their significance, becoming incidental in Oukaïmeden history. - sys: id: 1x3JfrZOaUEKmcAmkosm02 created_at: !ruby/object:DateTime 2015-11-25 15:13:24.362000000 Z updated_at: !ruby/object:DateTime 2017-01-06 15:38:01.412000000 Z content_type_id: image revision: 3 image: sys: id: 2nGxKesCSgWOeqSqa2eoAc created_at: !ruby/object:DateTime 2015-11-25 15:10:29.081000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:10:29.081000000 Z title: '2013,2034.5916' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2nGxKesCSgWOeqSqa2eoAc/6bd751f25420e92c5655a1af86e277de/2013_2034.5916.jpg" caption: Pecked bull on a prominent place within the valley. 2013,2034.5916 © <NAME>/TARA col_link: http://bit.ly/2jbIt5Q - sys: id: 7DEhcGYGoogSOGqOMmImam created_at: !ruby/object:DateTime 2015-11-25 15:17:08.360000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:17:08.360000000 Z content_type_id: chapter revision: 1 title_internal: 'Morocco: featured site, chapter 4' body: 'Unlike most of the rock art sites in North Africa, Oukaïmeden was not inhabited the whole year: the heavy snow that falls during the winter prevented occupation during the winter season. But that same snow made the valley a strategic resource for the villages placed in the surrounding, lower areas. During summer, when pastures became drier in the area around Marrakech, herders would take their sheep and cattle to Oukaïmeden for grazing, much in the way as it is still done today.' - sys: id: 1PdfGxdelmo8gkSyeu4kWK created_at: !ruby/object:DateTime 2015-11-25 15:14:00.276000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:14:00.276000000 Z content_type_id: image revision: 1 image: sys: id: RXRm1UgosSw248YEayEgC created_at: !ruby/object:DateTime 2015-11-25 15:10:29.031000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:10:29.031000000 Z title: '2013,2034.5879' description: url: "//images.ctfassets.net/xt8ne4gbbocd/RXRm1UgosSw248YEayEgC/32ef250086422ca87ff06855c563174d/2013_2034.5879.jpg" caption: Elephants’ Frieze. Several elephants and a rhinoceros or warthog are depicted facing right, where two human figures are represented. 2013,2034.5879 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3613935&partId=1&images=true&people=197356&museumno=2013,2034.5879&page=1 - sys: id: 28aOey79CAaGems6OOqW4C created_at: !ruby/object:DateTime 2015-11-25 15:17:25.702000000 Z updated_at: !ruby/object:DateTime 2017-01-06 15:38:58.399000000 Z content_type_id: chapter revision: 2 title_internal: 'Morocco: featured site, chapter 5' body: |- Although Oukaïmeden rock art is distributed throughout the valley, there are some sites with scenes that stand above the rest due to their complexity and significance. One of them is the so-called Elephants’ Frieze, a horizontal rock face where four elephants, a feline, a rhinoceros or warthog and two human figures facing the animals were depicted. Two later, vertical Libyan-Berber inscriptions were added to the panel. The scene is placed near a shelter, facing a stream which constitutes one of the main access routes to the valley grazing areas. The relevance of Oukaïmeden rock art is renowned, and the whole area has been protected since 1951 by the Moroccan government, while the National Centre of Rock Art Heritage in Marrakech has carried on several research projects in the area. However, the interest in the site doesn’t mean its preservation is assured: the growing incidence of tourism, the extraction of stones for building purposes in nearby Marrakech and vandalism are threats that have still to be dealt with. The fragile environment of Oukaïmeden valley adds an extra concern about the preservation of one of the most complete and better-preserved rock sites in Morocco. citations: - sys: id: 5qcDvyXGlUeO0OYGECIQYG created_at: !ruby/object:DateTime 2015-11-25 15:14:50.132000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:14:50.132000000 Z content_type_id: citation revision: 1 citation_line: |- <NAME>. 1959. *Corpus des gravures rupestres du Grand Atlas*, vol. 1. Marrakech, Publications du Service des Antiquités du Maroc 13 Malhomme, J. 1961. *Corpus des gravures rupestres du Grand Atlas*, vol. 2. Marrakech, Publications du Service des Antiquités du Maroc 14 Rodrigue, A. 1999. *L'art rupestre du Haut Atlas Marocain*. Paris, L'Harmattan Simoneau, A. 1977. *Catalogue des sites rupestres du Sud-Marocain*. Rabat, Ministere d'Etat charge des Affaires Culturelles background_images: - sys: id: 1FXFD6ckcAWESOOCMGo4gE created_at: !ruby/object:DateTime 2015-12-07 20:09:20.487000000 Z updated_at: !ruby/object:DateTime 2015-12-07 20:09:20.487000000 Z title: '2013,2034.5874' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1FXFD6ckcAWESOOCMGo4gE/03c7c921ee08e8d8d359eddc273fc2e5/2013_2034.5874.jpg" - sys: id: 1fKpdeWDQu46gMIW8i4gki created_at: !ruby/object:DateTime 2015-12-07 20:09:33.601000000 Z updated_at: !ruby/object:DateTime 2015-12-07 20:09:33.601000000 Z title: '2013,2034.5879' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1fKpdeWDQu46gMIW8i4gki/efd0d1ecaeb976c4d94c4244a8066f4b/2013_2034.5879.jpg" key_facts: sys: id: 55xcaWNyV2q0u8YuWKWgCU created_at: !ruby/object:DateTime 2015-11-26 11:27:12.053000000 Z updated_at: !ruby/object:DateTime 2015-11-26 11:27:12.053000000 Z content_type_id: country_key_facts revision: 1 title_internal: 'Morocco: key facts' image_count: 921 images date_range: Mostly 3,000 BC to AD 700 main_areas: High Atlas, Draa Valley, Saguiet el Hamra Valley techniques: predominantly engravings main_themes: Cattle, wild animals, weapons, hunting, war scenes with riders thematic_articles: - sys: id: 5QHjLLZ7gs846I0a68CGCg created_at: !ruby/object:DateTime 2015-11-25 17:59:00.673000000 Z updated_at: !ruby/object:DateTime 2015-12-11 12:29:03.345000000 Z content_type_id: thematic revision: 6 title: 'Written in stone: the Libyco-Berber scripts' slug: written-in-stone lead_image: sys: id: 5m9CnpjjOgEIeiaW6k6SYk created_at: !ruby/object:DateTime 2015-11-25 17:39:38.305000000 Z updated_at: !ruby/object:DateTime 2015-12-08 08:25:55.339000000 Z title: '2013,2034.4200' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5m9CnpjjOgEIeiaW6k6SYk/3dd6ae7d242722aa740c7229eb70d4e7/ALGDJA0040010.jpg" chapters: - sys: id: 3fpuPIJW9i2ESgqYsEMe02 created_at: !ruby/object:DateTime 2015-11-25 17:49:07.520000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:49:16.531000000 Z content_type_id: chapter revision: 2 title_internal: 'Libyco-Berber: thematic, chapter 1' body: 'A remarkable feature of North African rock art is the existence of numerous engraved or painted inscriptions which can be found throughout the Sahara Desert. These inscriptions, generically named Libyco-Berber, are found from the west of Egypt to the Canary Islands and from the Mediterranean Sea to the Sahel countries to the south. Together with Egyptian hieroglyphs, they show us one of the earliest written languages in Africa and represent a most interesting and challenging topic in North African history. They appear in two different formats: engraved on *stelae* (mainly on the Mediterranean coast and its hinterland) or on rock faces, either isolated or alongside rock art paintings or engravings of the later periods of rock art.' - sys: id: 6MFGcsOw2QYceK2eWSsGqY created_at: !ruby/object:DateTime 2015-11-25 17:43:10.618000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:32:20.694000000 Z content_type_id: image revision: 3 image: sys: id: 5m9CnpjjOgEIeiaW6k6SYk created_at: !ruby/object:DateTime 2015-11-25 17:39:38.305000000 Z updated_at: !ruby/object:DateTime 2015-12-08 08:25:55.339000000 Z title: '2013,2034.4200' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5m9CnpjjOgEIeiaW6k6SYk/3dd6ae7d242722aa740c7229eb70d4e7/ALGDJA0040010.jpg" caption: View of red wolf or lion with an spiral tail. A Libyco-Berber script has been written under the belly, and another one can be seen to the lower left of the photograph. <NAME>, Tassili n'Ajjer, Algeria. 2013,2034.4200 ©TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3601330&partId=1&searchText=2013,2034.4200&page=1 - sys: id: TwRWy4YkkUmg2yMGIWOQw created_at: !ruby/object:DateTime 2015-11-25 17:49:54.544000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:33:58.483000000 Z content_type_id: chapter revision: 3 title_internal: 'Libyco-Berber: thematic, chapter 2' body: Libyco-Berber characters were identified as written language as early as the 17th century, when some inscriptions in the language were documented in the Roman city of Dougga (Tunisia). They were deciphered by <NAME>ulcy in 1843 through the comparison of personal names with equivalent Punic names in bilingual scenes, although a few characters still remain uncertain. Since the beginning of the 19th century onwards many different proposals have been made to explain the origin, expansion and translation of these alphabets. There are three main explanations of its origin - the most accepted theory considers that the Libyco-Berber alphabet and principles of writing were borrowed from the Phoenician script, with other symbols added locally. - sys: id: pfjxB9ZjI4c68SYYOcc6C created_at: !ruby/object:DateTime 2015-11-25 17:43:34.886000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:35:37.505000000 Z content_type_id: image revision: 3 image: sys: id: 1i0U2eePgyWQKE8WgOEuug created_at: !ruby/object:DateTime 2015-11-25 17:40:16.321000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:56:27.808000000 Z title: Libyco theme figure 2 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1i0U2eePgyWQKE8WgOEuug/03cf171fe9cde8389b055b4740f8d1fd/29-10-2015_11.05.jpg" caption: Half of a bilingual inscription written in Numidian, part of a monument dedicated to Ateban, a Numidian prince. Numidian is one of the languages written in Libyco-Berber alphabets. 1852,0305.1 ©Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=368104&partId=1&searchText=1852,0305.1&page=1 - sys: id: 2QHgN5FuFGK4aoaWUcKuG2 created_at: !ruby/object:DateTime 2015-11-25 17:50:30.377000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:50:30.377000000 Z content_type_id: chapter revision: 1 title_internal: 'Libyco-Berber: thematic, chapter 3' body: A second, recent proposal has defended an indigenous (autochthonous) origin deriving from a stock of ancient signs –tribal tattoos, marks of ownership, or even geometric rock art- which could have resulted in the creation of the alphabet. Finally, a mixture of both theories accepts the borrowing of the idea of script and some Phoenician signs, which would be complemented with indigenous symbols. Although none of these theories can be fully accepted or refuted at the present moment, the proposal of a Phoenician borrowing has a wider support among linguistics and archaeologists. - sys: id: 67cDVCAn3GMK8m2guKMeuY created_at: !ruby/object:DateTime 2015-11-25 17:44:09.415000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:37:11.219000000 Z content_type_id: image revision: 2 image: sys: id: 4kXC2w9xCwAASweyCgwg2O created_at: !ruby/object:DateTime 2015-11-25 17:40:34.619000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:40:34.619000000 Z title: '2013,2034.4996' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4kXC2w9xCwAASweyCgwg2O/4d864b520d505029c7c8b90cd9e5fde2/ALGTOD0050035.jpg" caption: Engraved panel full of camels and human figures, surrounded by Libyco-Berber graffiti. <NAME> n’<NAME>. 2013,2034.4996 ©TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3623989&partId=1&searchText=2013,2034.4996&page=1 - sys: id: 4UXtnuK0VGkYKMGyuqseKI created_at: !ruby/object:DateTime 2015-11-25 17:50:56.343000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:50:56.343000000 Z content_type_id: chapter revision: 1 title: title_internal: 'Libyco-Berber: thematic, chapter 4' body: 'How is the Libyco-Berber alphabet composed? In fact, we should talk about Libyco-Berber alphabets, as one of the main characteristics of these scripts is their variety. In the mid-20th century, two main groups (eastern and western) were proposed, but this division is not so evident, and some studies have identified up to 25 different groups (grouped in 5 major families); some of them show strong similarities while between others up to half of the alphabetic symbols may be different. However, all these variants share common features: Libyco-Berber alphabetic symbols tend to be geometric, consisting of straight lines, circles and dots combined in different ways.' - sys: id: 13CDv9voc48oCmC0wqG4AA created_at: !ruby/object:DateTime 2015-11-25 17:44:51.935000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:37:41.169000000 Z content_type_id: image revision: 2 image: sys: id: 5rTkM78qGckOKu2q4AIUAI created_at: !ruby/object:DateTime 2015-11-25 17:40:51.188000000 Z updated_at: !ruby/object:DateTime 2015-12-08 08:28:43.019000000 Z title: '2013,2034.9338' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5rTkM78qGckOKu2q4AIUAI/1868823d4c9b78591d8fd94d156a8afc/NIGEAM0040013.jpg" caption: View of Libyan warrior holding a spear, surrounded by Libyco-Berber scripts. Ibel, Niger. 2013,2034.9338 ©TARA/<NAME>oulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3641907&partId=1&searchText=2013,2034.9338&page=1 - sys: id: 1gWJWaxXZYc4IiUyiC8IkQ created_at: !ruby/object:DateTime 2015-11-25 17:51:32.328000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:51:32.328000000 Z content_type_id: chapter revision: 1 title_internal: 'Libyco-Berber: thematic, chapter 5' body: 'The study of Libyco-Berber script faces some huge challenges. In addition to its aforementioned variability, it is necessary to differentiate the ancient languages spoken and written in North Africa during the Classical Antiquity for which a generic term of Libyco-Berber is used. Furthermore, Tifinagh script, the modern script of Tuareg people shares some symbols with the Libyco-Berber alphabet, but otherwise is a quite different language. Contemporary Tuareg cannot understand the old Libyco-Berber inscriptions although they recognize some symbols. Chronology represents another challenge: although the first dated inscription on a *stela* is from 138 BC, some pottery sherds with Libyco-Berber symbols could date from the 3rd century BC. For some researchers the oldest date (as old as the 7th century BC) is believed to correspond to an engraving located in the Moroccan High Atlas, although that theory is still under discussion. Finally, the characteristics of the scripts present some problems: they are usually short, repetitive and in many cases incomplete. Moreover, Libyco-Berber can be written in different directions (from right to left, bottom to top), complicating the identification, transcription and translation of the inscriptions. ' - sys: id: 6K1hjSQHrGSmMIwyi4aEci created_at: !ruby/object:DateTime 2015-11-25 17:46:00.776000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:39:20.711000000 Z content_type_id: image revision: 4 image: sys: id: 373GOE3JagQYoyY2gySyMy created_at: !ruby/object:DateTime 2015-11-25 17:41:18.933000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:41:18.933000000 Z title: '2013,2034.5878' description: url: "//images.ctfassets.net/xt8ne4gbbocd/373GOE3JagQYoyY2gySyMy/75c096cc7f233cedc2f75f58b0b41290/Oukaimeden_adapted.jpg" caption: Panel with elephants and human figures superimposed by two Libyco-Berber inscriptions, which some consider one of the oldest written in this alphabet, enhanced for a better view of the symbols. Oukaïmeden, Morocco. 2013,2034.5878 ©TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3613939&partId=1&searchText=2013,2034.5878&page=1 - sys: id: 3ik84OMvkQaEu6yOAeCMS6 created_at: !ruby/object:DateTime 2015-11-25 17:51:51.719000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:51:51.719000000 Z content_type_id: chapter revision: 1 title_internal: 'Libyco-Berber: thematic, chapter 6' body: Considering all these problems, what do we know about Libyco-Berber scripts? First of all, they normally used only consonants, although due to the influence of Punic (the language used in areas controlled or influenced by Carthage) and Latin, vowels were added in some alphabet variants. The translation of Libyco-Berber scripts is complicated, since the existing texts are very short and can only be translated through comparison with equivalent texts in Punic or Latin. Most of the translated scripts are very simple and correspond to personal and site names, or fixed formulations as “X son of Y”, characteristics of funerary epigraphy, or others such as, “It’s me, X”. Perhaps surprisingly, some of the translated inscriptions have an amorous meaning, with expressions as “I, X, love Y”. As the known Libyco-Berber corpus of inscriptions grows, it seems possible that more and more inscriptions will be translated, leading to a better understanding of the languages. - sys: id: 1t5dVxKpiIqeqy82O4McOI created_at: !ruby/object:DateTime 2015-11-25 17:46:35.246000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:43:47.775000000 Z content_type_id: image revision: 3 image: sys: id: 7x2yrpGfGEKaUQgyuiOYwk created_at: !ruby/object:DateTime 2015-11-25 17:41:38.056000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:41:38.056000000 Z title: '2013,2034.3203' description: url: "//images.ctfassets.net/xt8ne4gbbocd/7x2yrpGfGEKaUQgyuiOYwk/27f613c48b37dbb1114df7b733465787/LIBMES0180013.jpg" caption: Panel depicting cattle, giraffes and Libyco-Berber graffiti. In Galgiwen, Libya. 2013,2034.3203 ©TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3589647&partId=1&searchText=2013,2034.3203&page=1 - sys: id: 3Ju6IkGoneueE2gYQKaAQm created_at: !ruby/object:DateTime 2015-11-25 17:52:16.445000000 Z updated_at: !ruby/object:DateTime 2015-12-11 12:27:17.030000000 Z content_type_id: chapter revision: 2 title_internal: 'Libyco-Berber: thematic, chapter 7' body: Of course, the Libyco-Berber scripts evolved through time, although discussion is still going on about the chronologies and rhythms of this process. After the adoption and development of the alphabet, the Libyco-Berber reached a consideration of “official language” in the Numidian kingdom, which flourished in the north-western coast of Africa during the two latest centuries BC. The kingdom was highly influenced by Carthage and Rome, resulting in the existence of bilingual inscriptions that were the key to the translation of Libyco-Berber scripts. After Roman conquest, Libyco-Berber was progressively abandoned as a written language in the area, but inscriptions in the Sahara were still common until an unknown moment in the first millennium BC (the scripts sometimes receiving the name of Tifinagh). The Berber language, however, has been preserved and a new alphabet was developed in the 1960s to be used by Berber people. - sys: id: 1fPVVfXalmoKy2mUUCQQOw created_at: !ruby/object:DateTime 2015-11-25 17:47:18.568000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:44:36.059000000 Z content_type_id: image revision: 2 image: sys: id: 2GLzuqBeIMgoUW0wqeiiKY created_at: !ruby/object:DateTime 2015-11-25 17:41:59.073000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:41:59.073000000 Z title: '2013,2034.4468' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2GLzuqBeIMgoUW0wqeiiKY/0ec84dd4272a7227215c45d16f1451c5/ALGDJA0100009.jpg" caption: Raid scene on a camel caravan, with several interspersed Libyco-Berber inscriptions. Tassili plateau, Djanet, Algeria. 2013,2034.4468 ©TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3602846&partId=1&searchText=2013,2034.4468&page=1 - sys: id: 5GOzFzswmcs8qgiqQgcQ2q created_at: !ruby/object:DateTime 2015-11-25 17:52:52.167000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:52:52.167000000 Z content_type_id: chapter revision: 1 title_internal: 'Libyco-Berber: thematic, chapter 8' body: The many challenges that surround the study of Libyco-Berber scripts have led to a complex crossroads of terms, chronologies and theories which sometimes are contradictory and confusing. For the Rock Art Image Project, a decision had to be made to define the painted or engraved scripts in the collection and the chosen term was Libyco-Berber, as most of the images are associated with paintings of the Horse and Camel periods and thus considered to be up to 3,000 years old. Using the term Tifinagh could lead to misunderstandings with more modern scripts and the alphabet currently used by Berber peoples throughout North Africa. - sys: id: 6qjMP5OeukCMEiWWieE4O8 created_at: !ruby/object:DateTime 2015-11-25 17:47:52.571000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:46:54.999000000 Z content_type_id: image revision: 2 image: sys: id: FGpTfysHqEay4OMO66YSE created_at: !ruby/object:DateTime 2015-11-25 17:42:18.963000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:42:18.963000000 Z title: '2013,2034.2792' description: url: "//images.ctfassets.net/xt8ne4gbbocd/FGpTfysHqEay4OMO66YSE/c735c56a5dff7302beb58cec0e35bc85/LIBMES0040160.jpg" caption: Libyco-Berber inscription engraved near a cow. Wadi Mathendous, Libya. 2013,2034.2792 ©TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3584843&partId=1&searchText=2013,2034.2792&page=1 - sys: id: NeG74FoyYuOowaaaUYgQq created_at: !ruby/object:DateTime 2015-11-25 17:53:11.586000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:53:11.586000000 Z content_type_id: chapter revision: 1 title_internal: 'Libyco-Berber: thematic, chapter 9' body: Undoubtedly, the deciphering of forgotten languages captures the imagination and is one of the most exciting challenges in the study of ancient cultures. However, it is usually a difficult enterprise, as extraordinary finds which aid translation such as the Rosetta Stone are fairly exceptional and most of the time the transcription and translation of these languages is a long and difficult process in which the meaning of words and grammar rules is slowly unravelled. Although there are no shortcuts to this method, there are some initiatives that help to ease the task. One of them is making available catalogues of high quality images of inscriptions which can be studied and analysed by specialists. In that sense, the Libyco-Berber inscriptions present in the Rock Art Image Project catalogue can be truly helpful for all those interested in one of the most fascinating languages in the world; a language, which albeit modified has endured in different forms for hundreds of years. citations: - sys: id: 4r54ew5pNSwQ8ckQ8w8swY created_at: !ruby/object:DateTime 2015-11-25 17:48:24.656000000 Z updated_at: !ruby/object:DateTime 2015-12-11 12:28:59.132000000 Z content_type_id: citation revision: 2 citation_line: | <NAME>. 2012. Rock Art, Scripts and proto-scripts in Africa: the Libyco-berber example. In: Delmas, A. and Penn, P. (eds.), *Written Culture in a Colonial Context: Africa and the Americas 1500 – 1900*. Brill Academic Publishers, Boston, pp. 3-29. <NAME>. 2007. Origin and Development of the Libyco-Berber Script. Berber Studies 15. Rüdiger Köppe Verlag, Köln. [http://lbi-project.org/](http://lbi-project.org/) background_images: - sys: id: 4kXC2w9xCwAASweyCgwg2O created_at: !ruby/object:DateTime 2015-11-25 17:40:34.619000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:40:34.619000000 Z title: '2013,2034.4996' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4kXC2w9xCwAASweyCgwg2O/4d864b520d505029c7c8b90cd9e5fde2/ALGTOD0050035.jpg" - sys: id: 2GLzuqBeIMgoUW0wqeiiKY created_at: !ruby/object:DateTime 2015-11-25 17:41:59.073000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:41:59.073000000 Z title: '2013,2034.4468' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2GLzuqBeIMgoUW0wqeiiKY/0ec84dd4272a7227215c45d16f1451c5/ALGDJA0100009.jpg" - sys: id: 2t4epzwnhiUMcmeK4yIYQC created_at: !ruby/object:DateTime 2015-11-26 17:10:57.025000000 Z updated_at: !ruby/object:DateTime 2015-12-07 20:49:23.897000000 Z content_type_id: thematic revision: 6 title: Gone fishing... slug: gone-fishing lead_image: sys: id: 5O1g77GG9UEIeyWWgoCwOa created_at: !ruby/object:DateTime 2015-11-26 16:33:34.505000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:33:34.505000000 Z title: '2013,2034.4497' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5O1g77GG9UEIeyWWgoCwOa/18b8916dbaa566c488fb1d462f336b88/2013_2034.4497.jpg" chapters: - sys: id: 3FSGABeX9C2aieeekCUc6I created_at: !ruby/object:DateTime 2015-11-26 16:58:39.843000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:58:59.910000000 Z content_type_id: chapter revision: 2 title_internal: 'Thematic: fishing, chapter 1' body: Fishing is an ancient practice in Africa, dating back 100,000 years, when modern humans started moving into coastal environments. The remains of thousands of fish bones and shellfish from sites on the southern African coastline dating to the Middle Stone Age testify to its antiquity. At the same time that human populations in Africa were developing more sophisticated terrestrial hunting technologies, they were also acquiring innovative and productive fishing and riverine hunting skills. Concomitantly, marine shells were being collected to thread on to twine, probably for use as items of personal ornamentation. Archaeological research has shown that aquatic environments have been exploited for both subsistence and cultural purposes for tens of thousands of years. - sys: id: 5rah4C96eWkK6gUgYS2cKI created_at: !ruby/object:DateTime 2015-11-26 16:34:38.217000000 Z updated_at: !ruby/object:DateTime 2018-05-16 17:46:25.921000000 Z content_type_id: image revision: 2 image: sys: id: 5O1g77GG9UEIeyWWgoCwOa created_at: !ruby/object:DateTime 2015-11-26 16:33:34.505000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:33:34.505000000 Z title: '2013,2034.4497' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5O1g77GG9UEIeyWWgoCwOa/18b8916dbaa566c488fb1d462f336b88/2013_2034.4497.jpg" caption: Red outline of a fish swimming right showing dorsal fin and fish scales. A smaller fish superimposes larger fish underneath near the tail. Tassili n'Ajjer, Algeria. 2013,2034.4497 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3602875&partId=1&people=197356&museumno=2013,2034.4497&page=1 - sys: id: 1s82PsQrCsS8C0QQQ0gYie created_at: !ruby/object:DateTime 2015-11-26 16:35:04.493000000 Z updated_at: !ruby/object:DateTime 2018-05-16 17:48:40.438000000 Z content_type_id: image revision: 2 image: sys: id: 3PqImAJY3CeKKkMwqeayoe created_at: !ruby/object:DateTime 2015-11-26 16:34:03.906000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:34:03.906000000 Z title: '2013,2034.5019' description: url: "//images.ctfassets.net/xt8ne4gbbocd/3PqImAJY3CeKKkMwqeayoe/19a4c9ac1890f3aa6e7b6ef761b4373b/2013_2034.5019.jpg" caption: Outline engraving of fish facing right, incised on a sandstone slab beside a riverbed. Oued Djerat, Algeria. 2013,2034.5019 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3624043&partId=1&people=197356&museumno=2013,2034.5019&page=1 - sys: id: oie98q7G1MoEw4c6ggEai created_at: !ruby/object:DateTime 2015-11-26 16:35:28.865000000 Z updated_at: !ruby/object:DateTime 2018-05-16 17:48:58.748000000 Z content_type_id: image revision: 2 image: sys: id: 5TVVOzkAlaWKaK4oG2wqq8 created_at: !ruby/object:DateTime 2015-11-26 16:33:50.727000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:33:50.727000000 Z title: '2013,2034.801' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5TVVOzkAlaWKaK4oG2wqq8/d1654d1e9de9bdf1f9a61eca5e81cebd/2013_2034.801.jpg" caption: Painted rock art showing series of dots in vertical lines that converge at top and bottom, possibly in a fish shape, placed in area of water seep on rock face. Afforzighiar, Acacus Mountains, Libya. 2013,2034.801 © David Coulson/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3586292&partId=1&people=197356&museumno=2013,2034.801&page=1 - sys: id: cjcvGndmak60E82YEQmEC created_at: !ruby/object:DateTime 2015-11-26 16:59:31.911000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:59:31.911000000 Z content_type_id: chapter revision: 1 title_internal: 'Thematic: fishing, chapter 2' body: |- We rarely consider the Sahara as the optimum environment for fishing. Seeing painted and engraved images of fish located in these waterless and unfavourable landscapes therefore seems at odds with our present-day knowledge of this vast desert. However, as we have noted before in these project pages (see introductions to Libya and Algeria), water-dependent animals such as crocodile and hippo have regularly been depicted in Saharan rock art, illustrating a once wetter and more fertile landscape. To date, the African rock art image project has catalogued representations of aquatic species in Libya, Algeria and Morocco, depicted with varying degrees of proficiency and ease of identification. This has been an insightful encounter, because it not only informs our thinking about the nature of the environment in the past and the way people were using their available resources, but also allows us to think about the cultural importance of water-based species. The rock art in these places is a glimpse into an aquatic past that is now supported by environmental evidence. In a recent collaborative project mapping ancient watercourses in the Sahara, it has been shown that during the Holocene (a period which started around 11,700 years ago), this now arid landscape was once covered by a dense interconnected river system, as well as large bodies of water known as ‘megalakes’. When these lakes overflowed, they linked catchment areas, resulting in a dense palaeoriver network that allowed water-dependent life (fish, molluscs and amphibians) to migrate and disperse across an extensive landscape. This interlinked waterway of the Sahara formed a single and vast biogeographic area. Perhaps not surprisingly, rock art sites appear to be clustered around inland deltas where resources would have been most plentiful. Across the Sahara, at least twenty-three species of fish have been identified in archaeological deposits from the Holocene, the most common being Tilapia, Catfish, African jewelfish, Silver fish and Nile perch. But can we go as far as to correlate the archaeological record with the rock art to species level? - sys: id: 5J2YaEVcDSk8E8mqsYeYC6 created_at: !ruby/object:DateTime 2015-11-26 16:36:02.168000000 Z updated_at: !ruby/object:DateTime 2018-05-16 17:51:34.767000000 Z content_type_id: image revision: 2 image: sys: id: 62OPN6zwbKOym4YUAKCoAY created_at: !ruby/object:DateTime 2015-11-26 16:33:44.984000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:33:44.984000000 Z title: Fig. 4. African jewelfish description: url: "//images.ctfassets.net/xt8ne4gbbocd/62OPN6zwbKOym4YUAKCoAY/b23a2b5b8d528ba735cf4e91c7a748c9/Fig._4._African_jewelfish.jpg" caption: African jewelfish (Hemichromis bimaculatus). Image ©Zhyla (Wikimedia Commons) col_link: https://commons.wikimedia.org/wiki/File:Hemichromis_bimaculatus1.jpg - sys: id: 4mxD1mNZu8OegCaGC60o8o created_at: !ruby/object:DateTime 2015-11-26 16:36:34.680000000 Z updated_at: !ruby/object:DateTime 2018-05-16 18:02:17.202000000 Z content_type_id: image revision: 3 image: sys: id: oV9yR91U3YSg2McmgeCA2 created_at: !ruby/object:DateTime 2015-11-26 16:33:44.982000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:33:44.982000000 Z title: Fig. 5. Redbelly Tilapia description: url: "//images.ctfassets.net/xt8ne4gbbocd/oV9yR91U3YSg2McmgeCA2/780ac15c52522b76348ecebbd4cc123d/Fig._5._Redbelly_Tilapia.jpg" caption: Redbelly Tilapia (Tilapia zillii). Image © <NAME> (Wikimedia Commons) col_link: https://commons.wikimedia.org/wiki/File%3AFresh_tilapia.jpg - sys: id: gbhjHlWzFCKyeeiUGEkaQ created_at: !ruby/object:DateTime 2015-11-26 17:00:13.905000000 Z updated_at: !ruby/object:DateTime 2018-05-16 17:57:51.334000000 Z content_type_id: chapter revision: 2 title_internal: 'Thematic: fishing, chapter 3' body: Rock art imagery is replete with both very naturalistic representations and also those which are more conceptual or abstract in nature, and the depictions of fish are no exception. While some representations are clearly identifiable as fish, other are more difficult to identify. For example, the image above from Afforzighiar shows vertical red dots on the left of the photograph are arranged in a fish-like shape that converges at the top and bottom. Additionally it has been deliberately placed on a section of the rock face where there is water seepage, blending the art with the natural environment. The dotted pattern is reminiscent of the African jewelfish (*Hemichromis bimaculatus*) or even the Redbelly Tilapia (*Tilapia zillii*), both shown to be species of fish found throughout much of the Sahara during the Holocene. - sys: id: 5XJMMCBGveKKqoIc8kGEQU created_at: !ruby/object:DateTime 2015-11-26 16:37:00.084000000 Z updated_at: !ruby/object:DateTime 2018-05-16 18:04:03.162000000 Z content_type_id: image revision: 3 image: sys: id: 4fQKRSGFIA6OMCe8waOWmM created_at: !ruby/object:DateTime 2015-11-26 16:33:34.492000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:33:34.492000000 Z title: '2013,2034.559' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4fQKRSGFIA6OMCe8waOWmM/0a976c617609964467168ae590f831a8/2013_2034.559.jpg" caption: Five fish engraved on a rock face. Wadi Intaharin, Acacus Mountains, Libya. 2013,2034.559 ©<NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3585024&partId=1&people=197356&museumno=2013,2034.559&page=1 - sys: id: 4gUY4mSYnKYk8UIMSGAike created_at: !ruby/object:DateTime 2015-11-26 16:37:27.294000000 Z updated_at: !ruby/object:DateTime 2018-05-16 18:02:43.933000000 Z content_type_id: image revision: 3 image: sys: id: rJLJBELLi0yAYiCuM4SWi created_at: !ruby/object:DateTime 2015-11-26 16:33:40.236000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:33:40.236000000 Z title: Fig. 7. African sharptooth catfish description: url: "//images.ctfassets.net/xt8ne4gbbocd/rJLJBELLi0yAYiCuM4SWi/31fdd8fe74786561592c1d104aa2ab13/Fig._7._African_sharptooth_catfish.jpg" caption: African sharptooth catfish (Clarias gariepinus). Image ©W.<NAME> (Wie146) (Wikimedia Commons) col_link: https://commons.wikimedia.org/wiki/File%3AClarias_garie_080516_9142_tdp.jpg - sys: id: 1pIt8kfkgAQ6ueEWMSqyAM created_at: !ruby/object:DateTime 2015-11-26 16:37:55.248000000 Z updated_at: !ruby/object:DateTime 2018-05-16 17:59:58.067000000 Z content_type_id: image revision: 2 image: sys: id: 14NfPoZlKIUOoacY8GWQ4c created_at: !ruby/object:DateTime 2015-11-26 16:33:44.971000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:33:44.971000000 Z title: '2013,2034.925' description: url: "//images.ctfassets.net/xt8ne4gbbocd/14NfPoZlKIUOoacY8GWQ4c/88845134e8a0ef3fcf489e93e67f321e/2013_2034.925.jpg" caption: Engraved fish. Affozighiar, Acacus Mountains, Libya 2013,2034.925 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3587559&partId=1&people=197356&museumno=2013,2034.925&page=1 - sys: id: 5Kvn7LZDEcc0iGm0O4u6uY created_at: !ruby/object:DateTime 2015-11-26 17:00:36.225000000 Z updated_at: !ruby/object:DateTime 2018-05-16 18:00:54.782000000 Z content_type_id: chapter revision: 2 title_internal: 'Thematic: fishing, chapter 4' body: Some of the engravings bear close morphological resemblances to Catfish, with even the barbels depicted. Catfish seem to occur more regularly in rock art than other species of fish, possibly due to their physical characteristics. They possess an auxiliary breathing organ which allows them to inhabit extremely de-oxygenated water; in fact, when necessary they can obtain up to 50% of their total oxygen requirements from the air. In some cases they will leave the water and crawl on dry ground to escape drying pools. This capacity to live in very shallow waters and to occupy the liminal spaces between land and water has elevated them to more than a simple food source and given them a place of cultural significance in many African societies. - sys: id: sTBWoIZ2yyuS04mEIYYus created_at: !ruby/object:DateTime 2015-11-26 16:38:21.905000000 Z updated_at: !ruby/object:DateTime 2018-05-16 18:01:22.453000000 Z content_type_id: image revision: 2 image: sys: id: 3nZmrbE5yUEuc2qaWc2Age created_at: !ruby/object:DateTime 2015-11-26 16:33:56.244000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:33:56.244000000 Z title: '2013,2034.5255' description: url: "//images.ctfassets.net/xt8ne4gbbocd/3nZmrbE5yUEuc2qaWc2Age/5bf831c50428a19572df28872a18e3d1/2013_2034.5255.jpg" caption: Engraved fish on a boulder. Ait Ouazik, <NAME>, Morocco. 2013,2034.5255 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3603483&partId=1&people=197356&museumno=2013,2034.5255&page=1 - sys: id: 5RuLsZVAOswgaaKG8CK0AQ created_at: !ruby/object:DateTime 2015-11-26 16:38:50.016000000 Z updated_at: !ruby/object:DateTime 2018-05-16 18:03:15.219000000 Z content_type_id: image revision: 2 image: sys: id: 7M6nZhpTuoUuOOk0oWu8ea created_at: !ruby/object:DateTime 2015-11-26 16:33:44.984000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:33:44.984000000 Z title: Fig. 10. Silver fish description: url: "//images.ctfassets.net/xt8ne4gbbocd/7M6nZhpTuoUuOOk0oWu8ea/04a411cc75ddded8230ee77128e3200a/Fig._10._Silver_fish.jpg" caption: Silver fish (Raiamas senegalensis). Image ©<NAME> (Wikimedia Commons) col_link: https://commons.wikimedia.org/wiki/File%3ACameroon2011_3_(1)_(7003774697).jpg - sys: id: 3SIbv3l2WQqe4Wa08Ew6cI created_at: !ruby/object:DateTime 2015-11-26 17:00:55.256000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:00:55.256000000 Z content_type_id: chapter revision: 1 title_internal: 'Thematic: fishing, chapter 5' body: In arid ecosystems, bodies of water are characterised by daily and seasonal fluctuations in water temperature, evaporation and other natural phenomena, and some fish species have adapted well to cope with these extreme changes in water chemistry. Catfish and Tilapia in particular are able to survive high salinity, which occurs through evaporation, while Redbelly Tilapia can also tolerate temperatures above 35° C. Both Sharptooth Catfish and Tilapia are floodplain dwellers and possess the ability to live and spawn in shallow waters, making them easily susceptible to predation. Catfish spines were also used to decorate Saharan pottery with dotted wavy-line patterns. These biological characteristics, which meant they could be easily hunted, may explain their frequent depiction in rock art. Perhaps their value was also reinforced by their being (possibly) the last fish species to survive once aridification had taken hold in the Sahara. - sys: id: 20MArnOyXuuIgo4g642QQa created_at: !ruby/object:DateTime 2015-11-26 17:01:46.522000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:01:46.522000000 Z content_type_id: chapter revision: 1 title: Fishing title_internal: 'Thematic: fishing, chapter 6' body: Fish are likely to have been caught in a variety of ways, but in the Sahara the most common technique was to use barbed bone point and/or fish hook technology, with the former being the most archaeologically visible. Barbed points may either be fixed – that is permanently attached to a spear or arrow shaft – or used as ‘harpoons’, when they separate from a shaft on impact and remain attached by a line. Barbed points can actually be used to catch multiple types of prey, but the primary use across Africa was for fish. - sys: id: 1bwCettQ98qY2wEyiQMOmU created_at: !ruby/object:DateTime 2015-11-26 16:39:23.290000000 Z updated_at: !ruby/object:DateTime 2019-02-21 14:59:03.644000000 Z content_type_id: image revision: 3 image: sys: id: 4cgsOBoxReGOAiCqw2UYM8 created_at: !ruby/object:DateTime 2015-11-26 16:33:40.242000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:33:40.242000000 Z title: Fig. 11. Bone point from Katanda description: url: "//images.ctfassets.net/xt8ne4gbbocd/4cgsOBoxReGOAiCqw2UYM8/e84d40b791670fc04e8b47d312248bd5/Fig._11._Bone_point_from_Katanda.jpg" caption: Bone point from Katanda, DRC, 80,000-90,000 BP. Image ©Human Origins Program, Smithsonian Institution col_link: hhttp://humanorigins.si.edu/evidence/behavior/getting-food/katanda-bone-harpoon-point - sys: id: 159mLyHGvyC4ccwOQMyQIs created_at: !ruby/object:DateTime 2015-11-26 17:02:05.585000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:02:05.585000000 Z content_type_id: chapter revision: 1 title_internal: 'Thematic: fishing, chapter 7' body: Chronologically, the earliest barbed bone point records are from Katanda in the Upper Semliki Valley in modern-day Democratic Republic of the Congo, dating to 80,000 – 90,000 years ago. Here people were catching Catfish weighing up to 68 kg (150 lb), sufficient to feed eighty people for two days. Research has noted the distribution of barbed bone points across the Sahara, and the correlation between these locations and the distribution of species requiring deep water. It is clear that there is continuity in sophisticated fishing technology and practice that has lasted tens of thousands of years. - sys: id: 2IWFdXQZl6WwuCgA6oUa8u created_at: !ruby/object:DateTime 2015-11-26 17:02:48.620000000 Z updated_at: !ruby/object:DateTime 2018-05-17 10:26:57.354000000 Z content_type_id: chapter revision: 2 title: Other aquatic species title_internal: 'Thematic: fishing, chapter 8' body: Other aquatic species are more difficult to identify and are much rarer. For example, the image below has been interpreted as a jelly-fish like creature. However, by manipulating the colour and lighting, the image is a little clearer and appears to share morphological characteristics, such as the rounded carapace and small flippers, with a turtle rather than a jellyfish. Furthermore, we know that softshell turtles (*Trionyx triunguis*) have been found in archaeological deposits in the Sahara dating to the Holocene. The vertical and wavy strands hanging down underneath could represent the pattern made in the sand by turtles when walking rather than being the tendrils of a jellyfish. In addition, the image from Wadi Tafak below appears to resemble a snail, and is consistent with what we know about the Capsian culture who inhabited modern Tunisia, Algeria, and parts of Libya during the early Holocene (10000–6000 BC). Their distinguishing culinary feature was a fondness for escargots – edible land snails. - sys: id: 5j7XInUteECEA6cSE48k4A created_at: !ruby/object:DateTime 2015-11-26 16:39:52.787000000 Z updated_at: !ruby/object:DateTime 2018-05-17 10:34:45.084000000 Z content_type_id: image revision: 2 image: sys: id: 7pDQ1Q7cm4u4KKkayeugGY created_at: !ruby/object:DateTime 2015-11-26 16:33:44.977000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:33:44.977000000 Z title: '2013,2034.4298' description: url: "//images.ctfassets.net/xt8ne4gbbocd/7pDQ1Q7cm4u4KKkayeugGY/094c9283ceeded55f016eafbc00e131c/2013_2034.4298.jpg" caption: Painting of a turtle (digitally manipulated) from Jabbaren, Algeria. 2013,2034.4298 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3601635&partId=1&people=197356&museumno=2013,2034.4298&page=1 - sys: id: 2pq6oldgxGsq48iIUsKEyg created_at: !ruby/object:DateTime 2015-11-26 16:40:52.658000000 Z updated_at: !ruby/object:DateTime 2018-05-17 10:35:17.649000000 Z content_type_id: image revision: 2 image: sys: id: 6k5J6VbwZOq2yg86Y4GsEc created_at: !ruby/object:DateTime 2015-11-26 16:33:40.222000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:33:40.222000000 Z title: '2013,2034.1167' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6k5J6VbwZOq2yg86Y4GsEc/3db2c57978de4879d82e7b04833d4564/2013_2034.1167.jpg" caption: Painting of a snail from Wadi Tafak, Acacus Mountains, Libya. 2013,2034.1167 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3593787&partId=1&people=197356&museumno=2013,2034.1167&page=1 - sys: id: k7ChxGbsyc2iSaOc0k62C created_at: !ruby/object:DateTime 2015-11-26 17:03:15.438000000 Z updated_at: !ruby/object:DateTime 2018-05-17 10:50:37.252000000 Z content_type_id: chapter revision: 2 title: Case study – Gobero title_internal: 'Thematic: fishing, chapter 9' body: A recently excavated cemetery site called Gobero (Sereno *et al.* 2008), situated on the western edge of the Ténéré desert in Niger, provides a uniquely preserved record of human occupation in the Sahara during the Holocene and puts into context some of the examples of rock art we have looked at here. Pollen analysis has indicated that during the Holocene, Gobero was situated in an open savannah landscape of grasses and sedges, with fig trees and tamarisk, where permanent water and marshy habitats were present. - sys: id: 7D5HIm20CW4WMy0IgyQQOu created_at: !ruby/object:DateTime 2015-11-26 16:41:18.798000000 Z updated_at: !ruby/object:DateTime 2018-05-17 10:52:51.807000000 Z content_type_id: image revision: 2 image: sys: id: 5ZHSZA9fHOyAu8kaMceGOa created_at: !ruby/object:DateTime 2015-11-26 16:33:40.277000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:33:40.277000000 Z title: Fig. 14. Aerial view of Gobero description: url: "//images.ctfassets.net/xt8ne4gbbocd/5ZHSZA9fHOyAu8kaMceGOa/a546de3d31a679d75b67e4e2f4e41c68/Fig._14._Aerial_view_of_Gobero.jpg" caption: Aerial view of Gobero archaeological site (from Sereno et al. 2008). col_link: http://journals.plos.org/plosone/article?id=10.1371/journal.pone.0002995 - sys: id: 1wHHAMslowaeSOAWaue4Om created_at: !ruby/object:DateTime 2015-11-26 17:03:47.119000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:03:47.119000000 Z content_type_id: chapter revision: 1 title_internal: 'Thematic: fishing, chapter 10' body: |- Approximately 200 burials, ranging over a 5000-year period, were found on the edge of an ancient lake. Grave goods include bones or tusks from wild fauna, ceramics, lithic projectile points, and bone, ivory and shell ornaments. One adult male was buried in a recumbent pose seated on the carapace of a mud turtle. Microliths, bone harpoon points and hooks, and ceramics with dotted wavy-line and zigzag impressed motifs were found in the burial fill, in an associated midden area, and in nearby paleolake deposits. Nile perch (*Lates niloticus*), large catfish, and tilapia dominate the midden fauna, which also includes bones and teeth from hippos, several bovids, small carnivores, softshell turtles and crocodiles. The early Holocene occupants at Gobero (7700–6300 BC.) were largely sedentary hunter-fisher-gatherers with lakeside funerary sites. Across the ‘green’ Sahara, Catfish, Tilapia and turtles played important roles socially, economically and culturally. We can see this most explicitly in the burial within a turtle carapace in Gobero, but the representation of aquatic animals in rock art is a significant testament to their value. citations: - sys: id: 6JNu3sK5DGaUyWo4omoc2M created_at: !ruby/object:DateTime 2015-11-26 16:58:14.227000000 Z updated_at: !ruby/object:DateTime 2019-02-21 15:03:53.071000000 Z content_type_id: citation revision: 2 citation_line: '<NAME>., <NAME>., <NAME>., <NAME>., Saliège J-F., et al. 2008. *Lakeside Cemeteries in the Sahara: 5000 Years of Holocene Population and Environmental Change*. PLoS ONE 3(8): [https://doi.org/10.1371/journal.pone.0002995](https://doi.org/10.1371/journal.pone.0002995)' background_images: - sys: id: 1MzxjY9CecYwee0IWcCQqe created_at: !ruby/object:DateTime 2015-12-07 18:22:52.418000000 Z updated_at: !ruby/object:DateTime 2015-12-07 18:22:52.418000000 Z title: EAF 141260 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1MzxjY9CecYwee0IWcCQqe/61da964c9b38a509ca9f602f7ac5747c/EAF_141260.jpg" - sys: id: BdGy2n8Krecyks0s4oe8e created_at: !ruby/object:DateTime 2015-12-07 18:22:52.407000000 Z updated_at: !ruby/object:DateTime 2015-12-07 18:22:52.407000000 Z title: 01557634 001 description: url: "//images.ctfassets.net/xt8ne4gbbocd/BdGy2n8Krecyks0s4oe8e/7130c75aba21829540524182a5350677/01557634_001.jpg" - sys: id: 7oNFGUa6g8qSweyAyyiCAe created_at: !ruby/object:DateTime 2015-11-26 18:11:30.861000000 Z updated_at: !ruby/object:DateTime 2015-12-07 20:51:34.879000000 Z content_type_id: thematic revision: 4 title: The domesticated horse in northern African rock art slug: the-domesticated-horse lead_image: sys: id: n2MxgdjbMW2gm0IoOKkCU created_at: !ruby/object:DateTime 2015-11-26 17:51:43.133000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:43.133000000 Z title: Fig. 1. Painted horse description: url: "//images.ctfassets.net/xt8ne4gbbocd/n2MxgdjbMW2gm0IoOKkCU/e2c7369ef1e4ab11c71023a769f8fe0d/Fig._1._Painted_horse.jpg" chapters: - sys: id: 27bcd1mylKoMWiCQ2KuKMa created_at: !ruby/object:DateTime 2015-11-26 18:00:19.777000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:00:19.777000000 Z content_type_id: chapter revision: 1 title_internal: 'Thematic: horse, chapter 1' body: Throughout northern Africa, there is a wealth of rock art depicting the domestic horse and its various uses, providing valuable evidence for the uses of horses at various times in history, as well as a testament to their importance to Saharan peoples. - sys: id: 2EbfpTN9L6E0sYmuGyiaec created_at: !ruby/object:DateTime 2015-11-26 17:52:26.605000000 Z updated_at: !ruby/object:DateTime 2018-05-15 16:39:29.412000000 Z content_type_id: image revision: 2 image: sys: id: n2MxgdjbMW2gm0IoOKkCU created_at: !ruby/object:DateTime 2015-11-26 17:51:43.133000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:43.133000000 Z title: Fig. 1. Painted horse description: url: "//images.ctfassets.net/xt8ne4gbbocd/n2MxgdjbMW2gm0IoOKkCU/e2c7369ef1e4ab11c71023a769f8fe0d/Fig._1._Painted_horse.jpg" caption: 'Painted horse and rider, Ennedi Plateau, Chad. 2013,2034.6406 © TARA/David Coulson. ' col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3641775&partId=1&searchText=2013,2034.6406&page=1 - sys: id: 4QexWBEVXiAksikIK6g2S4 created_at: !ruby/object:DateTime 2015-11-26 18:00:49.116000000 Z updated_at: !ruby/object:DateTime 2018-05-15 16:40:28.446000000 Z content_type_id: chapter revision: 2 title: Horses and chariots title_internal: 'Thematic: horse, chapter 2' body: The first introduction of the domestic horse to Ancient Egypt- and thereby to Africa- is usually cited at around 1600 BC, linked with the arrival in Egypt of the Hyksos, a group from the Levant who ruled much of Northern Egypt during the Second Intermediate Period. By this point, horses had probably only been domesticated for about 2,000 years, but with the advent of the chariot after the 3rd millennium BC in Mesopotamia, the horse proved to be a valuable martial asset in the ancient world. One of the first clear records of the use of horses and chariots in battle in Africa is found in depictions from the mortuary complex of the Pharaoh Ahmose at Abydos from around 1525 BC, showing their use by Egyptians in defeating the Hyksos, and horses feature prominently in later Egyptian art. - sys: id: 22x06a7DteI0C2U6w6oKes created_at: !ruby/object:DateTime 2015-11-26 17:52:52.323000000 Z updated_at: !ruby/object:DateTime 2018-05-15 16:40:52.214000000 Z content_type_id: image revision: 2 image: sys: id: 1AZD3AxiUwwoYUWSWY8MGW created_at: !ruby/object:DateTime 2015-11-26 17:51:50.284000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:50.284000000 Z title: '2013,2034.1001' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1AZD3AxiUwwoYUWSWY8MGW/b68bd24c9b19c5c8c7752bfb75a5db0e/2013_2034.1001.jpg" caption: Painted two-horse chariot, Acacus Mountains, Libya. 2013,2034.1001 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3588526&partId=1&people=197356&museumno=2013,2034.1001&page=1 - sys: id: 1voXfvqIcQkgUYqq4w8isQ created_at: !ruby/object:DateTime 2015-11-26 18:01:15.173000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:01:15.173000000 Z content_type_id: chapter revision: 1 title_internal: 'Thematic: horse, chapter 3' body: 'Some of the most renowned images of horses in Saharan rock art are also those of chariot teams: in particular, those of the so-called ‘flying gallop’ style chariot pictures, from the Tassili n’Ajjer and Acacus mountains in modern Algeria and Libya. These distinctive images are characterised by depictions of one or more horses pulling a chariot with their legs outstretched in a stylised manner and are sometimes attributed to the Garamantes, a group who were a local power in the central Sahara from about 500 BC-700 AD. But the Ajjer Plateau is over a thousand miles from the Nile- how and when did the horse and chariot first make their way across the Western Desert to the rest of North Africa in the first place? Egyptian accounts indicate that by the 11th century BC Libyans (people living on the north African coast around the border of modern Egypt and Libya) were using chariots in war. Classical sources later write about the chariots of the Garamantes and of chariot use by peoples of the far western Sahara continuing into the 1st century BC, by which time the chariot horse had largely been eclipsed in war by the cavalry mount.' - sys: id: LWROS2FhUkywWI60eQYIy created_at: !ruby/object:DateTime 2015-11-26 17:53:42.845000000 Z updated_at: !ruby/object:DateTime 2018-05-15 16:41:33.841000000 Z content_type_id: image revision: 2 image: sys: id: 6N6BF79qk8EUygwkIgwcce created_at: !ruby/object:DateTime 2015-11-26 17:51:44.708000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:44.708000000 Z title: '2013,2034.4574' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6N6BF79qk8EUygwkIgwcce/ac95a5214a326794542e0707c0d819d7/2013_2034.4574.jpg" caption: Painted human figure and horse. Tarssed Jebest, Tassili n’Ajjer, Algeria. Horse displays Arabian breed-type characteristics such as dished face and high tail carriage. 2013,2034.4574 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3603790&partId=1&people=197356&museumno=2013,2034.4574+&page=1 - sys: id: 6eaH84QdUs46sEQoSmAG2u created_at: !ruby/object:DateTime 2015-11-26 18:01:48.835000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:01:48.835000000 Z content_type_id: chapter revision: 1 title: Horse Riding title_internal: 'Thematic: horse, chapter 4' body: As well as the unique iconography of rock art chariot depictions, there are also numerous paintings and engravings across northern Africa of people riding horses. Riding may have been practiced since the earliest times of horse domestication, though the earliest definitive depictions of horses being ridden come from the Middle East in the late 3rd and early 2nd millennia BC. Images of horses and riders in rock art occur in various areas of Morocco, Egypt and Sudan and are particularly notable in the Ennedi region of Chad and the Adrar and Tagant plateaus in Mauritania (interestingly, however, no definite images of horses are known in the Gilf Kebir/Jebel Uweinat area at the border of Egypt, Sudan and Libya). - sys: id: 6LTzLWMCTSak4IIukAAQMa created_at: !ruby/object:DateTime 2015-11-26 17:54:23.846000000 Z updated_at: !ruby/object:DateTime 2018-05-15 16:41:52.743000000 Z content_type_id: image revision: 2 image: sys: id: 4NdhGNLc9yEck4My4uQwIo created_at: !ruby/object:DateTime 2015-11-26 17:51:43.495000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:43.495000000 Z title: ME22958 description: url: "//images.ctfassets.net/xt8ne4gbbocd/4NdhGNLc9yEck4My4uQwIo/703945afad6a8e3c97d10b09c487381c/ME22958.jpg" caption: Terracotta mould of man on horseback, Old Babylonian, Mesopotamia 2000-1600 BC. One of the oldest known depictions of horse riding in the world. British Museum ME22958 © Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=388860&partId=1&people=197356&museumno=22958&page=1 - sys: id: 5YkSCzujy8o08yuomIu6Ei created_at: !ruby/object:DateTime 2015-11-26 17:54:43.227000000 Z updated_at: !ruby/object:DateTime 2018-05-16 11:12:34.068000000 Z content_type_id: image revision: 2 image: sys: id: 1tpjS4kZZ6YoeiWeIi8I4C created_at: !ruby/object:DateTime 2015-11-26 17:51:43.188000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:43.188000000 Z title: Fig. 5. Painted ‘bitriangular’ description: url: "//images.ctfassets.net/xt8ne4gbbocd/1tpjS4kZZ6YoeiWeIi8I4C/c798c1afb41006855c34363ec2b54557/Fig._5._Painted____bitriangular___.jpg" caption: Painted ‘bi-triangular’ horse and rider with saddle. Oued Jrid, Assaba, Mauritania. 2013,2034.12285 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3645983&partId=1&searchText=2013,2034.12285&page=1 - sys: id: 1vZDFfKXU0US2qkuaikG8m created_at: !ruby/object:DateTime 2015-11-26 18:02:13.433000000 Z updated_at: !ruby/object:DateTime 2018-05-16 11:14:56.468000000 Z content_type_id: chapter revision: 2 title_internal: 'Thematic: horse, chapter 5' body: Traditional chronologies for Saharan rock art areas tend to place depictions of ridden horses chronologically after those of horses and chariots, and in general use horse depictions to categorise regional stylistic periods of rock art according to broad date boundaries. As such, in most places, the ‘horse’ rock art period is usually said to cover about a thousand years from the end of the 2nd millennium BC. It is then considered to be succeeded by a ‘camel’ period, where the appearance of images of dromedaries – known only to have been introduced to the eastern Sahara from Arabia at the end of the 1st century BC – reflects the next momentous influx of a beast of burden to the area and thus a new dating parameter ([read more about depictions of camels in the Sahara](https://africanrockart.britishmuseum.org/thematic/camels-in-saharan-rock-art/)). However, such simplistic categorisation can be misleading. For one thing, although mounting horses certainly gained popularity over driving them, it is not always clear that depictions of ridden horses are not contemporary with those of chariots. Further, the horse remained an important martial tool after the use of war-chariots declined. Even after the introduction of the camel, there are several apparently contemporary depictions featuring both horse and camel riders. - sys: id: 2gaHPgtyEwsyQcUqEIaGaq created_at: !ruby/object:DateTime 2015-11-26 17:55:29.704000000 Z updated_at: !ruby/object:DateTime 2018-05-16 11:32:44.364000000 Z content_type_id: image revision: 3 image: sys: id: 6quML2y0nuYgSaeG0GGYy4 created_at: !ruby/object:DateTime 2015-11-26 17:51:50.292000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:50.292000000 Z title: '2013,2034.5739' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6quML2y0nuYgSaeG0GGYy4/7f48ae9c550dd6b4f0e80b8da10a3da6/2013_2034.5739.jpg" caption: Engraved ridden horse and camel. Draa Valley, Morocco. 2013,2034.5739 ©TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3619780&partId=1&people=197356&museumno=2013,2034.5739+&page=1 - sys: id: 583LKSbz9SSg00uwsqquAG created_at: !ruby/object:DateTime 2015-11-26 18:02:41.576000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:02:41.576000000 Z content_type_id: chapter revision: 1 title: Berber Horses title_internal: 'Thematic: horse, chapter 6' body: As the more manoeuvrable rider rose in popularity against the chariot as a weapon of war, historical reports from classical authors like Strabo tell us of the prowess of African horsemen such as the cavalry of the Numidians, a Berber group that allied with Carthage against the Romans in the 3rd century BC. Berber peoples would remain heavily associated with horse breeding and riding, and the later rock art of Mauritania has been attributed to Berber horsemen, or the sight of them. Although horses may already have reached the areas of modern Mauritania and Mali by this point, archaeological evidence does not confirm their presence in these south-westerly regions of the Sahara until much later, in the mid-1st millennium AD, and it has been suggested that some of the horse paintings in Mauritania may be as recent as 16th century. - sys: id: 7zrBlvCEGkW86Qm8k2GQAK created_at: !ruby/object:DateTime 2015-11-26 17:56:24.617000000 Z updated_at: !ruby/object:DateTime 2018-05-16 11:16:52.557000000 Z content_type_id: image revision: 2 image: sys: id: uOFcng0Q0gU8WG8kI2kyy created_at: !ruby/object:DateTime 2015-11-26 17:51:44.717000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:44.717000000 Z title: '2013,2034.5202' description: url: "//images.ctfassets.net/xt8ne4gbbocd/uOFcng0Q0gU8WG8kI2kyy/7fba0330e151fc416d62333f3093d950/2013_2034.5202.jpg" caption: Engraved horses and riders surrounded by Libyan-Berber script. Oued <NAME>. These images appear to depict riders using Arab-style saddles and stirrups, thus making them probably no older than 7th c. AD. 2013,2034.5202 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3624404&partId=1&people=197356&museumno=2013,2034.5202&page=1 - sys: id: 45vpX8SP7aGeOS0qGaoo4a created_at: !ruby/object:DateTime 2015-11-26 18:03:14.279000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:03:14.279000000 Z content_type_id: chapter revision: 1 title_internal: 'Thematic: horse, chapter 7' body: 'Certainly, from the 14th century AD, horses became a key commodity in trans-Saharan trade routes and became items of great military value in West Africa following the introduction of equipment such as saddles with structured trees (frames). Indeed, discernible images of such accoutrements in Saharan rock art can help to date it following the likely introduction of the equipment to the area: for example, the clear depiction of saddles suggests an image to be no older than the 1st century AD; images including stirrups are even more recent.' - sys: id: 7GeTQBofPamw0GeEAuGGee created_at: !ruby/object:DateTime 2015-11-26 17:56:57.851000000 Z updated_at: !ruby/object:DateTime 2018-05-16 11:29:02.520000000 Z content_type_id: image revision: 2 image: sys: id: 5MaSKooQvYssI4us8G0MyO created_at: !ruby/object:DateTime 2015-11-26 17:51:43.501000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:43.501000000 Z title: RRM12824 description: url: "//images.ctfassets.net/xt8ne4gbbocd/5MaSKooQvYssI4us8G0MyO/8c3a7c2d372f2c48a868d60201909932/RRM12824.jpg" caption: 19th-century Moroccan stirrups with typical curved base of the type possibly visible in the image above. 1939,0311.7-8 © Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=217451&partId=1&page=1 - sys: id: 6mNtqnqaEE2geSkU0IiYYe created_at: !ruby/object:DateTime 2015-11-26 18:03:32.195000000 Z updated_at: !ruby/object:DateTime 2018-05-16 11:29:50.228000000 Z content_type_id: chapter revision: 2 title_internal: 'Thematic: horse, chapter 8' body: 'Another intriguing possibility is that of gaining clues on the origins of modern horse breeds from rock art, in particular the ancient Barb breed native to the Maghreb, where it is still bred. Ancient Mesopotamian horses were generally depicted as heavily-built, and it has been suggested that the basic type for the delicate Arabian horse, with its dished (concave) facial profile and high-set tail, may have been developed in north-east Africa prior to its subsequent appearance and cultivation in Arabia, and that these features may be observed in Ancient Egyptian images from the New Kingdom. Likewise, there is the possibility that some of the more naturalistic paintings from the central Sahara show the similarly gracile features of the progenitors of the Barb, distinguishable from the Arab by its straight profile and low-set tail. Like the Arab, the Barb is a desert horse: hardy, sure-footed and able to withstand great heat; it is recognised as an ancient breed with an important genetic legacy, both in the ancestry of the Iberian horses later used throughout the Americas, and that of the modern racing thoroughbred.' - sys: id: 3OM1XJI6ruwGOwwmkKOKaY created_at: !ruby/object:DateTime 2015-11-26 17:57:25.145000000 Z updated_at: !ruby/object:DateTime 2018-05-16 11:30:30.915000000 Z content_type_id: image revision: 2 image: sys: id: 6ZmNhZjLCoQSEIYKIYUUuk created_at: !ruby/object:DateTime 2015-11-26 17:51:50.293000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:50.293000000 Z title: '2013,2034.1452' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6ZmNhZjLCoQSEIYKIYUUuk/45bbff5b29985eb19679e1e513499d6b/2013_2034.1452.jpg" caption: Engraved horses and riders, Awis, Acacus Mountains, Libya. High head carriage and full rumps suggest Arabian/Barb breed type features. Riders have been obscured. 2013,2034.1452 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3592678&partId=1&people=197356&museumno=2013,2034.1452&page=1 - sys: id: 40E0pTCrUIkk00uGWsus4M created_at: !ruby/object:DateTime 2015-11-26 17:57:49.497000000 Z updated_at: !ruby/object:DateTime 2018-05-16 11:33:55.443000000 Z content_type_id: image revision: 2 image: sys: id: 5mbJWrbZV6aQQOyamKMqIa created_at: !ruby/object:DateTime 2015-11-26 17:51:43.468000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:43.468000000 Z title: Fig. 10. Barb horses description: url: "//images.ctfassets.net/xt8ne4gbbocd/5mbJWrbZV6aQQOyamKMqIa/87f29480513be0a531e0a93b51f9eae5/Fig._10._Barb_horses.jpg" caption: Barb horses ridden at a festival in Agadir, Morocco. ©Notwist (Wikimedia Commons) col_link: https://commons.wikimedia.org/wiki/File:Berber_warriors_show.JPG - sys: id: 3z5YSVu9y8caY6AoYWge2q created_at: !ruby/object:DateTime 2015-11-26 18:04:02.770000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:04:02.770000000 Z content_type_id: chapter revision: 1 title: The symbolism of the horse title_internal: 'Thematic: horse, chapter 9' body: However, caution must be taken in drawing such comparisons based on morphology alone, especially given the gulf of time that has elapsed and the relative paucity of ‘naturalistic’ rock art images. Indeed, there is huge diversity of horse depictions throughout northern Africa, with some forms highly schematic. This variation is not only in style – and, as previously noted, in time period and geography – but also in context, as of course images of one subject cannot be divorced from the other images around them, on whichever surface has been chosen, and are integral to these surroundings. - sys: id: 1FRP1Z2hyQEWUSOoKqgic2 created_at: !ruby/object:DateTime 2015-11-26 17:58:21.234000000 Z updated_at: !ruby/object:DateTime 2019-02-21 15:41:39.821000000 Z content_type_id: image revision: 2 image: sys: id: 4EatwZfN72waIquQqWEeOs created_at: !ruby/object:DateTime 2015-11-26 17:51:43.121000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:43.121000000 Z title: '2013,2034.11147' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4EatwZfN72waIquQqWEeOs/d793f6266f2ff486e0e99256c2c0ca39/2013_2034.11147.jpg" caption: Engraved ‘Libyan Warrior-style’ figure with horse. Indakatte, Western Aïr Mountains, Niger. 2013,2034.11147 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3637713&partId=1&people=197356&museumno=2013,2034.11147+&page=1 - sys: id: 45pI4ivRk4IM6gaG40gUU0 created_at: !ruby/object:DateTime 2015-11-26 17:58:41.308000000 Z updated_at: !ruby/object:DateTime 2019-02-21 15:41:59.784000000 Z content_type_id: image revision: 2 image: sys: id: 2FcYImmyd2YuqMKQMwAM0s created_at: !ruby/object:DateTime 2015-11-26 17:51:43.117000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:43.117000000 Z title: Fig. 12. Human figure description: url: "//images.ctfassets.net/xt8ne4gbbocd/2FcYImmyd2YuqMKQMwAM0s/e48fda8e2a23b12e6afde5c560c3f164/Fig._12._Human_figure.jpg" caption: Human figure painted over by horse to appear mounted (digitally enhanced image). © TARA/<NAME> - sys: id: 54hoc6Htwck8eyewsa6kA8 created_at: !ruby/object:DateTime 2015-11-26 18:04:26.929000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:04:26.929000000 Z content_type_id: chapter revision: 1 title_internal: 'Thematic: horse, chapter 10' body: The nature of the depictions in this sense speaks intriguingly of the apparent symbolism and implied value of the horse image in different cultural contexts. Where some Tassilian horses are delicately painted in lifelike detail, the stockier images of horses associated with the so-called ‘Libyan Warrior’ style petroglyphs of the Aïr mountains and Adrar des Ifoghas in Niger and Mali appear more as symbolic accoutrements to the central human figures and tend not to be shown as ridden. By contrast, there are paintings in the Ennedi plateau of Chad where galloping horse figures have clearly been painted over existing walking human figures to make them appear as if riding. - sys: id: 4XMm1Mdm7Y0QacMuy44EKa created_at: !ruby/object:DateTime 2015-11-26 17:59:06.184000000 Z updated_at: !ruby/object:DateTime 2019-02-21 15:42:27.444000000 Z content_type_id: image revision: 2 image: sys: id: 21xnJrk3dKwW6uSSkGumMS created_at: !ruby/object:DateTime 2015-11-26 17:51:44.697000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:44.697000000 Z title: '2013,2034.6297' description: url: "//images.ctfassets.net/xt8ne4gbbocd/21xnJrk3dKwW6uSSkGumMS/698c254a9a10c5a9a56d69e0525bca83/2013_2034.6297.jpg" caption: Engraved horse, <NAME>, <NAME>, Chad. 2013,2034.6297 © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3637529&partId=1&people=197356&museumno=2013,2034.6297&page=1 - sys: id: 4rB9FCopjOCC4iA2wOG48w created_at: !ruby/object:DateTime 2015-11-26 17:59:26.549000000 Z updated_at: !ruby/object:DateTime 2019-02-21 15:43:34.211000000 Z content_type_id: image revision: 2 image: sys: id: 3PfHuSbYGcqeo2U4AEKsmM created_at: !ruby/object:DateTime 2015-11-26 17:51:43.196000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:43.196000000 Z title: Fig. 14. Engraved horse description: url: "//images.ctfassets.net/xt8ne4gbbocd/3PfHuSbYGcqeo2U4AEKsmM/33a068fa954954fd3b9b446c943e0791/Fig._14._Engraved_horse.jpg" caption: Engraved horse, Eastern Aïr Mountains. 2013,2034.9421 ©TARA/<NAME>. col_link: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3640574&partId=1&searchText=2013,2034.9421&page=1 - sys: id: 6tFSQzFupywiK6aESCgCia created_at: !ruby/object:DateTime 2015-11-26 18:04:56.612000000 Z updated_at: !ruby/object:DateTime 2019-02-21 15:47:26.838000000 Z content_type_id: chapter revision: 2 title_internal: 'Thematic: horse, chapter 11' body: |- In each of these cases, the original symbolic intent of the artists have been lost to time, but with these horse depictions, as with so much African rock art imagery, there is great scope for further future analysis. Particularly intriguing, for example, are the striking stylistic similarities in horse depictions across great distances, such the horse depictions with bi-triangular bodies (see above), or with fishbone-style tails which may be found almost two thousand miles apart in Chad and Mauritania. Whatever the myriad circumstances and significances of the images, it is clear that following its introduction to the continent, the hardy and surefooted desert horse’s usefulness for draught, transport and fighting purposes transformed the societies which used it and gave it a powerful symbolic value. - sys: id: 2P6ERbclfOIcGEgI6e0IUq created_at: !ruby/object:DateTime 2015-11-26 17:59:46.042000000 Z updated_at: !ruby/object:DateTime 2019-02-21 15:45:12.419000000 Z content_type_id: image revision: 2 image: sys: id: 3UXc5NiGTYQcmu2yuU42g created_at: !ruby/object:DateTime 2015-11-26 17:51:43.128000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:43.128000000 Z title: Fig. 15. Painted horse, Terkei description: url: "//images.ctfassets.net/xt8ne4gbbocd/3UXc5NiGTYQcmu2yuU42g/7586f05e83f708ca9d9fca693ae0cd83/Fig._15._Painted_horse__Terkei.jpg" caption: Painted horse, Terkei, Ennedi Plateau, Chad. 2013,2034.6537 © TARA/David Coulson col_link: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3640682&partId=1&searchText=2013,2034.6537&page=1 citations: - sys: id: 32AXGC1EcoSi4KcogoY2qu created_at: !ruby/object:DateTime 2015-11-26 17:51:20.602000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:20.602000000 Z content_type_id: citation revision: 1 citation_line: "<NAME>. & <NAME>. 2000, *The Origins and Development of African Livestock: archaeology, genetics, linguistics and ethnography*. London; New York, NY: UCL Press\n \nCurtis, C., <NAME>., <NAME>., 2012. *The Horse: From Arabia to Royal Ascot*. London: British Museum Press\n \nLaw, R., 1980. *The Horse in West African History*. Oxford: Oxford University Press\n \nHachid, M. 2000. *Les Premieres Berbères*. Aix-en-Provence: Edisud\n \nLhote, H. 1952. 'Le cheval et le chameau dans les peintures et gravures rupestres du Sahara', *Bulletin de l'Institut franç ais de l'Afrique noire* 15: 1138-228\n \n<NAME>. & <NAME>. 2010, *A gift from the desert: the art, history, and culture of the Arabian horse*. Lexington, KY: Kentucky Horse Park\n\n" background_images: - sys: id: 2avgKlHUm8CauWie6sKecA created_at: !ruby/object:DateTime 2015-12-07 18:44:31.346000000 Z updated_at: !ruby/object:DateTime 2015-12-07 18:44:31.346000000 Z title: EAF 141485 description: url: "//images.ctfassets.net/xt8ne4gbbocd/2avgKlHUm8CauWie6sKecA/cf02168ca83c922f27eca33f16e8cc90/EAF_141485.jpg" - sys: id: 1wtaUDwbSk4MiyGiISE6i8 created_at: !ruby/object:DateTime 2015-12-07 18:43:51.804000000 Z updated_at: !ruby/object:DateTime 2015-12-07 18:43:51.804000000 Z title: 01522751 001 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1wtaUDwbSk4MiyGiISE6i8/5918544d0289f9c4b2b4724f4cda7a2d/01522751_001.jpg" - sys: id: 1hw0sVC0XOUA4AsiG4AA0q created_at: !ruby/object:DateTime 2017-11-23 11:49:41.362000000 Z updated_at: !ruby/object:DateTime 2017-11-23 11:49:41.362000000 Z content_type_id: thematic revision: 1 title: 'Introduction to rock art in northern Africa ' slug: rock-art-in-northern-africa lead_image: sys: id: 1fzfpavYuGaOKaAM2ko6es created_at: !ruby/object:DateTime 2015-11-26 15:53:30.004000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:53:30.004000000 Z title: '2013,2034.3840' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1fzfpavYuGaOKaAM2ko6es/f1e27e311dca40ce58657e5e88cb8526/2013_2034.3840.jpg" chapters: - sys: id: axu12ftQUoS04AQkcSWYI created_at: !ruby/object:DateTime 2015-11-26 15:58:10.885000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:58:10.885000000 Z content_type_id: chapter revision: 1 title: title_internal: 'North Africa: regional, chapter 1' body: 'The Sahara is the largest non-polar desert in the world, covering almost 8,600,000 km² and comprising most of northern Africa, from the Red Sea to the Atlantic Ocean. Although it is considered a distinct entity, it is composed of a variety of geographical regions and environments, including sand seas, hammadas (stone deserts), seasonal watercourses, oases, mountain ranges and rocky plains. Rock art is found throughout this area, principally in the desert mountain and hill ranges, where stone ''canvas'' is abundant: the highlands of Adrar in Mauritania and Adrar des Ifoghas in Mali, the Atlas Mountains of Morocco and Algeria, the Tassili n’Ajjer and Ahaggar Mountains in Algeria, the mountainous areas of Tadrart Acacus and Messak in Libya, the Aïr Mountains of Nigeria, the Ennedi Plateau and Tibesti Mountains in Chad, the Gilf Kebir plateau of Egypt and Sudan, as well as the length of the Nile Valley.' - sys: id: 4DelCmwI7mQ4MC2WcuAskq created_at: !ruby/object:DateTime 2015-11-26 15:54:19.234000000 Z updated_at: !ruby/object:DateTime 2016-12-22 10:12:21.657000000 Z content_type_id: image revision: 2 image: sys: id: 1fzfpavYuGaOKaAM2ko6es created_at: !ruby/object:DateTime 2015-11-26 15:53:30.004000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:53:30.004000000 Z title: '2013,2034.3840' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1fzfpavYuGaOKaAM2ko6es/f1e27e311dca40ce58657e5e88cb8526/2013_2034.3840.jpg" caption: Bubalus Period engraving. Pelorovis Antiquus, Wadi Mathendous, Libya. 2013,2034.3840 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3593438&partId=1&images=true&people=197356&museumno=2013,2034.3840&page=1 - sys: id: 2XmfdPdXW0Y4cy6k4O4caO created_at: !ruby/object:DateTime 2015-11-26 15:58:31.891000000 Z updated_at: !ruby/object:DateTime 2016-10-17 13:40:03.509000000 Z content_type_id: chapter revision: 3 title: Types of rock art and distribution title_internal: 'North Africa: regional, chapter 2' body: |+ Although the styles and subjects of north African rock art vary, there are commonalities: images are most often figurative and frequently depict animals, both wild and domestic. There are also many images of human figures, sometimes with accessories such as recognisable weaponry or clothing. These may be painted or engraved, with frequent occurrences of both, at times in the same context. Engravings are generally more common, although this may simply be a preservation bias due to their greater durability. The physical context of rock art sites varies depending on geographical and topographical factors – for example, Moroccan rock engravings are often found on open rocky outcrops, while Tunisia’s Djebibina rock art sites have all been found in rock shelters. Rock art in the vast and harsh environments of the Sahara is often inaccessible and hard to find, and there is probably a great deal of rock art that is yet to be seen by archaeologists; what is known has mostly been documented within the last century. - sys: id: 2HqgiB8BAkqGi4uwao68Ci created_at: !ruby/object:DateTime 2016-10-17 13:41:30.844000000 Z updated_at: !ruby/object:DateTime 2016-10-17 13:41:30.844000000 Z content_type_id: chapter revision: 1 title: History of research title_internal: 'North Africa: regional chapter 2.5' body: Although the existence of rock art throughout the Sahara was known to local communities, it was not until the nineteenth century that it became known to Europeans, thanks to explorers such as <NAME>, who crossed the Messak Plateau in Libya in 1850, first noting the existence of engravings. Further explorations in the early twentieth century by celebrated travellers, ethnographers and archaeologists such as <NAME>, <NAME>, László Almásy, <NAME> and <NAME> brought the rock art of Sahara, and northern Africa in general, to the awareness of a European public. - sys: id: 5I9fUCNjB668UygkSQcCeK created_at: !ruby/object:DateTime 2015-11-26 15:54:54.847000000 Z updated_at: !ruby/object:DateTime 2016-12-22 10:13:53.921000000 Z content_type_id: image revision: 2 image: sys: id: 2N4uhoeNLOceqqIsEM6iCC created_at: !ruby/object:DateTime 2015-11-26 15:53:37.250000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:53:37.250000000 Z title: '2013,2034.1424' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2N4uhoeNLOceqqIsEM6iCC/240a45012afba4ff5508633fcaea3462/2013_2034.1424.jpg" caption: Pastoral Period painting, cattle and human figure. <NAME>, Acacus Mountains, Libya. 2013,2034.1424 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3592663 - sys: id: 5OkqapzKtqEcomSucG0EoQ created_at: !ruby/object:DateTime 2015-11-26 15:58:52.432000000 Z updated_at: !ruby/object:DateTime 2016-10-17 13:45:37.885000000 Z content_type_id: chapter revision: 4 title: Attribution and dating title_internal: 'North Africa: regional, chapter 3' body: 'The investigations of these researchers and those who have followed them have sought to date and attribute these artworks, with varying measures of success. Rock art may be associated with certain cultures through known parallels with the imagery in other artefacts, such as Naqada Period designs in Egyptian rock art that mirror those on dateable pottery. Authorship may be also guessed at through corroborating evidence: for example, due to knowledge of their chariot use, and the location of rock art depicting chariots in the central Sahara, it has been suggested that it was produced by – or at the same time as – the height of the Garamantes culture, a historical ethnic group who formed a local power around what is now southern Libya from 500 BC–700 AD. However, opportunities to anchor rock art imagery in this way to known ancient cultures are few and far between, and rock art is generally ascribed to anonymous hunter-gatherers, nomadic peoples, or pastoralists, with occasional imagery-based comparisons made with contemporary groups, such as the Fulani peoples.' - sys: id: 2KmaZb90L6qoEAK46o46uK created_at: !ruby/object:DateTime 2015-11-26 15:55:22.104000000 Z updated_at: !ruby/object:DateTime 2016-12-22 10:16:53.318000000 Z content_type_id: image revision: 2 image: sys: id: 5A1AwRfu9yM8mQ8EeOeI2I created_at: !ruby/object:DateTime 2015-11-26 15:53:37.288000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:53:37.288000000 Z title: '2013,2034.1152' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5A1AwRfu9yM8mQ8EeOeI2I/cac0592abfe1b31d7cf7f589355a216e/2013_2034.1152.jpg" caption: Round Head Period painting, human figures. Wadi Tafak, Acacus Mountains, Libya. 2013,2034.1152 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3592099&partId=1&images=true&people=197356&page=1 - sys: id: 27ticyFfocuOIGwioIWWYA created_at: !ruby/object:DateTime 2015-11-26 15:59:26.852000000 Z updated_at: !ruby/object:DateTime 2016-10-17 15:18:29.234000000 Z content_type_id: chapter revision: 2 title_internal: 'North Africa: regional, chapter 4' body: |- Occasionally, association with writing in the form of, for example, Libyan-Berber or Arabic graffiti can give a known dating margin, but in general, lack of contemporary writing and written sources (Herodotus wrote about the Garamantes) leaves much open to conjecture. Other forms of (rare) circumstantial evidence, such as rock art covered by a dateable stratigraphic layer, and (more common) stylistic image-based dating have been used instead to form a chronology of Saharan rock art periods that is widely agreed upon, although dates are contested. The first stage, known as the Early Hunter, Wild Fauna or Bubalus Period, is posited at about 12,000–6,000 years ago, and is typified by naturalistic engravings of wild animals, in particular an extinct form of buffalo identifiable by its long horns. - sys: id: q472iFYzIsWgqWG2esg28 created_at: !ruby/object:DateTime 2015-11-26 15:55:58.985000000 Z updated_at: !ruby/object:DateTime 2016-12-22 10:19:11.991000000 Z content_type_id: image revision: 2 image: sys: id: 1YAVmJPnZ2QQiguCQsgOUi created_at: !ruby/object:DateTime 2015-11-26 15:53:29.989000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:53:29.989000000 Z title: '2013,2034.4570' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1YAVmJPnZ2QQiguCQsgOUi/4080b87891cb255e12a17216d7e71286/2013_2034.4570.jpg" caption: Horse Period painting, charioteer and standing horses. Tarssed Jebest, <NAME>, Algeria. 2013,2034.4570 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3603794 - sys: id: 7tsWGNvkQgACuKEMmC0uwG created_at: !ruby/object:DateTime 2015-11-26 15:59:47.880000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:59:47.880000000 Z content_type_id: chapter revision: 1 title_internal: 'North Africa: regional, chapter 5' body: A possibly concurrent phase is known as the Round Head Period (about 10,000 to 8,000 years ago) due to the large discoid heads of the painted human figures. Following this is the most widespread style, the Pastoral Period (around 7,500 to 4,000 years ago), which is characterised by numerous paintings and engravings of cows, as well as occasional hunting scenes. The Horse Period (around 3,000 to 2,000 years ago) features recognisable horses and chariots and the final Camel Period (around 2,000 years ago to present) features domestic dromedary camels, which we know to have been widely used across the Sahara from that time. - sys: id: 13V2nQ2cVoaGiGaUwWiQAC created_at: !ruby/object:DateTime 2015-11-26 15:56:25.598000000 Z updated_at: !ruby/object:DateTime 2016-12-22 10:39:22.861000000 Z content_type_id: image revision: 2 image: sys: id: 6MOI9r5tV6Gkae0CEiQ2oQ created_at: !ruby/object:DateTime 2015-11-26 15:53:29.964000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:53:29.964000000 Z title: 2013,2034.1424 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6MOI9r5tV6Gkae0CEiQ2oQ/bad4ec8dd7c6ae553d623e4238641561/2013_2034.1424_1.jpg" caption: Camel engraving. <NAME>, Jebel Uweinat, Sudan. 2013,2034.335 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3586831 - sys: id: 3A64bY4VeMGkKCsGCGwu4a created_at: !ruby/object:DateTime 2015-11-26 16:00:04.267000000 Z updated_at: !ruby/object:DateTime 2016-10-17 15:30:04.896000000 Z content_type_id: chapter revision: 2 title_internal: 'North Africa: regional, chapter 6' body: "While this chronology serves as a useful framework, it must be remembered that the area – and the time period in which rock art was produced – is extensive and there is significant temporal and spatial variability within and across sites. There are some commonalities in rock art styles and themes across the Sahara, but there are also regional variations and idiosyncrasies, and a lack of evidence that any of these were directly, or even indirectly, related. The engravings of weaponry motifs from Morocco and the painted ‘swimming’ figures of the Gilf Kebir Plateau in Egypt and Sudan are not only completely different, but unique to their areas. Being thousands of kilometres apart and so different in style and composition, they serve to illustrate the limitations inherent in examining northern African rock art as a unit. The contemporary political and environmental challenges to accessing rock art sites in countries across the Sahara serves as another limiting factor in their study, but as dating techniques improve and further discoveries are made, this is a field with the potential to help illuminate much of the prehistory of northern Africa.\n\n" citations: - sys: id: 4AWHcnuAVOAkkW0GcaK6We created_at: !ruby/object:DateTime 2016-10-17 15:15:38.284000000 Z updated_at: !ruby/object:DateTime 2016-10-17 15:15:38.284000000 Z content_type_id: citation revision: 1 citation_line: | <NAME>. 1998. Art rupestre et préhistoire du Sahara: le Messak Libyen. Paris: Payot & Rivages Muzzolini, A. 1995. Les images rupestres du Sahara. — Toulouse (author’s ed.), p. 447 <NAME>. 2001. Saharan Africa in (ed) David S. Whitley, Handbook of Rock Art Research, pp 605-636. AltaMira Press, Walnut Creek <NAME>. 2013. Dating the rock art of Wadi Sura, in Wadi Sura – The Cave of Beasts, Kuper, R. (ed). Africa Praehistorica 26 – Köln: Heinrich-Barth-Institut, pp. 38-39 <NAME>. 1999. L'art rupestre du Haut Atlas Marocain. Paris, L'Harmattan <NAME>. 2012. Round Heads: The Earliest Rock Paintings in the Sahara. Newcastle upon Tyne: Cambridge Scholars Publishing Vernet, R. 1993. Préhistoire de la Mauritanie. Centre Culturel Français A. de Saint Exupéry-Sépia, Nouakchott background_images: - sys: id: 3ZTCdLVejemGiCIWMqa8i created_at: !ruby/object:DateTime 2015-12-07 19:41:46.025000000 Z updated_at: !ruby/object:DateTime 2015-12-07 19:41:46.025000000 Z title: EAF135068 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3ZTCdLVejemGiCIWMqa8i/5a0d13fdd2150f0ff81a63afadd4258e/EAF135068.jpg" - sys: id: 2jvgN3MMfqoAW6GgO8wGWo created_at: !ruby/object:DateTime 2015-12-07 19:41:50.029000000 Z updated_at: !ruby/object:DateTime 2015-12-07 19:41:50.029000000 Z title: EAF131007 description: url: "//images.ctfassets.net/xt8ne4gbbocd/2jvgN3MMfqoAW6GgO8wGWo/393c91068f4dc0ca540c35a79b965288/EAF131007.jpg" country_introduction: sys: id: 6aJoaZnAAMsKUGGaAmkYIe created_at: !ruby/object:DateTime 2015-11-26 12:42:41.014000000 Z updated_at: !ruby/object:DateTime 2015-12-07 13:41:48.166000000 Z content_type_id: country_information revision: 3 title: 'Morocco: country introduction' chapters: - sys: id: 3PqAqA0X0cKoOKsc2ciiae created_at: !ruby/object:DateTime 2015-11-26 12:43:14.313000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:43:14.313000000 Z content_type_id: chapter revision: 1 title: Introduction title_internal: 'Morocco: country, chapter 1' body: 'Morocco is located at the north-western corner of Africa, in a unique area forming a link between the Mediterranean Sea, the Atlantic Ocean, Europe and Africa. More than 300 rock art sites have been documented in the country so far, mainly located in two areas: the High Atlas Mountains, and the Sahara desert region to the south and east. They comprise mainly engravings, which could be up to 5,000 years old, and include domestic and wild animals, warriors, weapons and scenes of battles and hunting. Antelope and cattle are the most represented animals in Moroccan rock art, although elephants and rhinoceros are common too.' - sys: id: 4htOF13DGEcYas2yAUI6oI created_at: !ruby/object:DateTime 2015-11-26 12:39:31.073000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:39:31.073000000 Z content_type_id: image revision: 1 image: sys: id: 4Jt8P55Z56SkEegOMO6euY created_at: !ruby/object:DateTime 2015-11-26 12:38:42.713000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:38:42.713000000 Z title: '2013,2034.5277' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4Jt8P55Z56SkEegOMO6euY/698f587066b8b4fa30b14b0badf55817/2013_2034.5277.jpg" caption: Engraved rock art of a rhinoceros and an oval shape, from Ait Ouazik, Draa valley, Ouazarzate province, Morocco. 2013,2034.5277 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3603526&partId=1&images=true&people=197356&place=40983&page=2 - sys: id: 2UTNFDWbM4wCMAA2weoWUw created_at: !ruby/object:DateTime 2015-11-26 12:39:56.904000000 Z updated_at: !ruby/object:DateTime 2017-01-06 15:32:33.859000000 Z content_type_id: image revision: 2 image: sys: id: 46fV0mfFKMUYyywY0iUGYK created_at: !ruby/object:DateTime 2015-11-26 12:38:42.713000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:38:42.713000000 Z title: '2013,2034.5654' description: url: "//images.ctfassets.net/xt8ne4gbbocd/46fV0mfFKMUYyywY0iUGYK/5341c01a6cc0cc3baed490b90509e26f/2013_2034.5654.jpg" caption: Southern Morocco landscape, with the Anti-Atlas mountains in the background. 2013,2034.5654 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3605659&partId=1&images=true&people=197356&place=40983&museumno=2013,2034.5654&page=1 - sys: id: 4Dc0V6fW8wWcquEyqkemKK created_at: !ruby/object:DateTime 2015-11-26 12:44:00.368000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:44:00.368000000 Z content_type_id: chapter revision: 1 title: Geography and rock art distribution title_internal: 'Morocco: country, chapter 2' body: Morocco has a very variable geography, with the Atlas Mountains crossing the country from the southwest to the northeast and separating the coastal plains to the west from the Sahara Desert that runs to the east and south. The distribution of rock art in the country is very irregular, with some zones crowded with sites and others almost devoid of depictions. The two main areas of rock art sites are the High Atlas zone and the area to the east and south of the Atlas Mountains. The first area groups more than seven thousand engravings around the Oukaïmeden valley, the Yagour plateau and the Jebel Rat site. They are at high altitude (more than 2000 metres above sea level), and mainly represent weapons, cattle and anthropomorphic figures, along with numerous geometric symbols. - sys: id: 1ZpASVa0UcU4EEagkAm4MQ created_at: !ruby/object:DateTime 2015-11-26 12:40:26.929000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:40:26.929000000 Z content_type_id: image revision: 1 image: sys: id: 6AO1Pff4UowYQMsYU444qS created_at: !ruby/object:DateTime 2015-11-26 12:38:47.431000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:38:47.432000000 Z title: '2013,2034.5866' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6AO1Pff4UowYQMsYU444qS/63b08d76fe217ca864a582ef1b634b1f/2013_2034.5866.jpg" caption: Circular engravings in the valley of Oukaïmeden, High Atlas. 2013,2034.5866 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3613845&partId=1&images=true&people=197356&place=40983&museumno=2013,2034.5866+&page=1 - sys: id: 30E1RdstwIuyse04A6sAUE created_at: !ruby/object:DateTime 2015-11-26 12:44:21.467000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:44:21.467000000 Z content_type_id: chapter revision: 1 title_internal: 'Morocco: country, chapter 3' body: The second main zone, an arid region where the majority of Moroccan rock art sites are situated, contains the oldest engravings in the country, some of them linked to the Saharan styles. The variety of themes depicted is wide, from abundant scenes of riders to isolated animals or complex geometric symbols. This collection comprises about seven hundred images, most of them corresponding to the southern area of Morocco around the Draa valley and the town of Tata, although a High Atlas (Oukaïmeden) site is also included. - sys: id: 1GwI61s72o2AgsESI8kkCI created_at: !ruby/object:DateTime 2015-11-26 12:44:44.525000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:44:44.525000000 Z content_type_id: chapter revision: 1 title: Research history title_internal: 'Morocco: country, chapter 4' body: 'European audiences began studying the rock art in Morocco decades after the study of rock art in Algeria and Libya, with the first news of rock art coming from French and German travellers late in the 19th century. The most significant boost came after the Treaty of Fes in 1912, when the presence of the colonial authorities led indirectly to an increasing knowledge of rock art sites, as Spanish and French officers started to show interest in the engravings. However, it was not until after Moroccan independence in 1956 that systematic research began throughout the country. Since then, archaeological information has progressively grown, although regional syntheses are still scarce: only the Atlas (Malhomme, Rodrigue) and part of southern Morocco (Simoneau) have exhaustive catalogues of sites. The first comprehensive study of Moroccan rock art was made in 2001 (Searight), when for the first time, a global approach to Moroccan rock art areas, themes and chronology was undertaken.' - sys: id: 4Rkp5dL3BegaOyGkisoMwg created_at: !ruby/object:DateTime 2015-11-26 12:45:02.929000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:45:02.929000000 Z content_type_id: chapter revision: 1 title: Themes title_internal: 'Morocco: country, chapter 5' body: 'As in most countries, mammals are the most frequent depictions, especially cattle, horses and different types of antelope. Many other animals, such as giraffes, elephants, rhinoceros, dromedaries or lions are depicted, if more scarcely. The second main theme is human figures, especially in the south of the country, where depictions of Libyan-Berber riders are very common. In the High Atlas area they are usually depicted isolated, surrounded by weapons, which are another big theme in Moroccan rock art: a panoply of these can be seen, including daggers, bows and arrows, spears, shields, axes and halberds.' - sys: id: ZigzuAFbcOgC8IEGkwEQi created_at: !ruby/object:DateTime 2015-11-26 12:40:59.047000000 Z updated_at: !ruby/object:DateTime 2017-01-06 15:36:19.352000000 Z content_type_id: image revision: 2 image: sys: id: 2iKZIRebewsGGQiKiOgQq created_at: !ruby/object:DateTime 2015-11-26 12:38:42.729000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:04:25.512000000 Z title: '2013,2034.5558' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3605427&partId=1&searchText=2013,2034.5558&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/2iKZIRebewsGGQiKiOgQq/7a6ea71bedef21c05b78d13fe9883716/2013_2034.5558.jpg" caption: 'Antelope engravings, Tazina style. 2013,2034.5558 © TARA/<NAME> ' col_link: http://bit.ly/2jbUc4v - sys: id: 2XErL5q2oE6yg4sYSseM8C created_at: !ruby/object:DateTime 2015-11-26 12:45:24.616000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:45:24.616000000 Z content_type_id: chapter revision: 1 title: Chronology title_internal: 'Morocco: country, chapter 6' body: A consensus has yet to be achieved about Moroccan rock art chronology between the supporters of a long chronology, starting around 4000 BC, and those that defend a short one, from 2500 BC onwards. The oldest engravings represented in Moroccan rock art correspond to the Tazina and Pecked Cattle styles, depicting mainly mammals. From the second half of the second millennium BC onwards, depictions of human figures start to appear in the High Atlas, associated with daggers and shields, defining the so-called Dagger/Halberd/Anthropomorph style. During the first millennium BC, Libyan-Berber hunting and battle scenes start to appear in southern Morocco; riders, infantrymen and animals depicted in a very schematic style. The last period of Moroccan rock art, as in the rest of the Sahara, is the so-called Camel Period, characterized by the appearance of dromedaries. - sys: id: 6wwVooOVZSw6SyKQ6eooma created_at: !ruby/object:DateTime 2015-11-26 12:41:29.715000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:41:29.715000000 Z content_type_id: image revision: 1 image: sys: id: 2nR1MWquOoWQiikYooK22Q created_at: !ruby/object:DateTime 2015-11-26 12:38:42.719000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:38:42.719000000 Z title: '2013,2034.5776' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2nR1MWquOoWQiikYooK22Q/3db626f582b41622c7a89a91ff6a6d12/2013_2034.5776.jpg" caption: Pecked cattle-style engravings. 2013,2034.5776 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3619818&partId=1&people=197356&museumno=2013,2034.5776&page=1 citations: - sys: id: UN3bodv8KAWYgsEuyCM2E created_at: !ruby/object:DateTime 2015-11-26 12:42:11.373000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:42:11.373000000 Z content_type_id: citation revision: 1 citation_line: |+ <NAME>. 1959. *Corpus des gravures rupestres du Grand Atlas*, vol. 1. Marrakech, Publications du Service des Antiquités du Maroc 13 Malhomme, J. 1961. *Corpus des gravures rupestres du Grand Atlas*, vol. 2. Marrakech, Publications du Service des Antiquités du Maroc 14 Rodrigue, A. 1999. *L'art rupestre du Haut Atlas Marocain*. Paris, L'Harmattan Simoneau, A. 1977. *Catalogue des sites rupestres du Sud-Marocain*. Rabat, Ministere d'Etat charge des Affaires Culturelles background_images: - sys: id: 5A7q4PnbI4sYmQsi2u4yYg created_at: !ruby/object:DateTime 2015-11-25 15:10:29.077000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:10:29.077000000 Z title: '2013,2034.5863' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5A7q4PnbI4sYmQsi2u4yYg/95ab9db2de0532159c59d4bbe3e12316/2013_2034.5863.jpg" - sys: id: 4Jt8P55Z56SkEegOMO6euY created_at: !ruby/object:DateTime 2015-11-26 12:38:42.713000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:38:42.713000000 Z title: '2013,2034.5277' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4Jt8P55Z56SkEegOMO6euY/698f587066b8b4fa30b14b0badf55817/2013_2034.5277.jpg" - sys: id: 3OAdh6uCrCIgCeuQ2E0koa created_at: !ruby/object:DateTime 2015-11-25 15:10:29.049000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:03:43.993000000 Z title: '2013,2034.5874' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3613873&partId=1&searchText=2013,2034.5874&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/3OAdh6uCrCIgCeuQ2E0koa/a9fe9a0740e535707c227440bac46571/2013_2034.5874.jpg" region: Northern / Saharan Africa ---<file_sep>/_coll_thematic/gone-fishing.md --- contentful: sys: id: 2t4epzwnhiUMcmeK4yIYQC created_at: !ruby/object:DateTime 2015-11-26 17:10:57.025000000 Z updated_at: !ruby/object:DateTime 2015-12-07 20:49:23.897000000 Z content_type_id: thematic revision: 6 title: Gone fishing... slug: gone-fishing lead_image: sys: id: 5O1g77GG9UEIeyWWgoCwOa created_at: !ruby/object:DateTime 2015-11-26 16:33:34.505000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:33:34.505000000 Z title: '2013,2034.4497' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5O1g77GG9UEIeyWWgoCwOa/18b8916dbaa566c488fb1d462f336b88/2013_2034.4497.jpg" chapters: - sys: id: 3FSGABeX9C2aieeekCUc6I created_at: !ruby/object:DateTime 2015-11-26 16:58:39.843000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:58:59.910000000 Z content_type_id: chapter revision: 2 title_internal: 'Thematic: fishing, chapter 1' body: Fishing is an ancient practice in Africa, dating back 100,000 years, when modern humans started moving into coastal environments. The remains of thousands of fish bones and shellfish from sites on the southern African coastline dating to the Middle Stone Age testify to its antiquity. At the same time that human populations in Africa were developing more sophisticated terrestrial hunting technologies, they were also acquiring innovative and productive fishing and riverine hunting skills. Concomitantly, marine shells were being collected to thread on to twine, probably for use as items of personal ornamentation. Archaeological research has shown that aquatic environments have been exploited for both subsistence and cultural purposes for tens of thousands of years. - sys: id: 5rah4C96eWkK6gUgYS2cKI created_at: !ruby/object:DateTime 2015-11-26 16:34:38.217000000 Z updated_at: !ruby/object:DateTime 2018-05-16 17:46:25.921000000 Z content_type_id: image revision: 2 image: sys: id: 5O1g77GG9UEIeyWWgoCwOa created_at: !ruby/object:DateTime 2015-11-26 16:33:34.505000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:33:34.505000000 Z title: '2013,2034.4497' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5O1g77GG9UEIeyWWgoCwOa/18b8916dbaa566c488fb1d462f336b88/2013_2034.4497.jpg" caption: Red outline of a fish swimming right showing dorsal fin and fish scales. A smaller fish superimposes larger fish underneath near the tail. Tassili n'Ajjer, Algeria. 2013,2034.4497 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3602875&partId=1&people=197356&museumno=2013,2034.4497&page=1 - sys: id: 1s82PsQrCsS8C0QQQ0gYie created_at: !ruby/object:DateTime 2015-11-26 16:35:04.493000000 Z updated_at: !ruby/object:DateTime 2018-05-16 17:48:40.438000000 Z content_type_id: image revision: 2 image: sys: id: 3PqImAJY3CeKKkMwqeayoe created_at: !ruby/object:DateTime 2015-11-26 16:34:03.906000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:34:03.906000000 Z title: '2013,2034.5019' description: url: "//images.ctfassets.net/xt8ne4gbbocd/3PqImAJY3CeKKkMwqeayoe/19a4c9ac1890f3aa6e7b6ef761b4373b/2013_2034.5019.jpg" caption: Outline engraving of fish facing right, incised on a sandstone slab beside a riverbed. <NAME>. 2013,2034.5019 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3624043&partId=1&people=197356&museumno=2013,2034.5019&page=1 - sys: id: oie98q7G1MoEw4c6ggEai created_at: !ruby/object:DateTime 2015-11-26 16:35:28.865000000 Z updated_at: !ruby/object:DateTime 2018-05-16 17:48:58.748000000 Z content_type_id: image revision: 2 image: sys: id: 5TVVOzkAlaWKaK4oG2wqq8 created_at: !ruby/object:DateTime 2015-11-26 16:33:50.727000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:33:50.727000000 Z title: '2013,2034.801' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5TVVOzkAlaWKaK4oG2wqq8/d1654d1e9de9bdf1f9a61eca5e81cebd/2013_2034.801.jpg" caption: Painted rock art showing series of dots in vertical lines that converge at top and bottom, possibly in a fish shape, placed in area of water seep on rock face. Afforzighiar, Acacus Mountains, Libya. 2013,2034.801 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3586292&partId=1&people=197356&museumno=2013,2034.801&page=1 - sys: id: cjcvGndmak60E82YEQmEC created_at: !ruby/object:DateTime 2015-11-26 16:59:31.911000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:59:31.911000000 Z content_type_id: chapter revision: 1 title_internal: 'Thematic: fishing, chapter 2' body: |- We rarely consider the Sahara as the optimum environment for fishing. Seeing painted and engraved images of fish located in these waterless and unfavourable landscapes therefore seems at odds with our present-day knowledge of this vast desert. However, as we have noted before in these project pages (see introductions to Libya and Algeria), water-dependent animals such as crocodile and hippo have regularly been depicted in Saharan rock art, illustrating a once wetter and more fertile landscape. To date, the African rock art image project has catalogued representations of aquatic species in Libya, Algeria and Morocco, depicted with varying degrees of proficiency and ease of identification. This has been an insightful encounter, because it not only informs our thinking about the nature of the environment in the past and the way people were using their available resources, but also allows us to think about the cultural importance of water-based species. The rock art in these places is a glimpse into an aquatic past that is now supported by environmental evidence. In a recent collaborative project mapping ancient watercourses in the Sahara, it has been shown that during the Holocene (a period which started around 11,700 years ago), this now arid landscape was once covered by a dense interconnected river system, as well as large bodies of water known as ‘megalakes’. When these lakes overflowed, they linked catchment areas, resulting in a dense palaeoriver network that allowed water-dependent life (fish, molluscs and amphibians) to migrate and disperse across an extensive landscape. This interlinked waterway of the Sahara formed a single and vast biogeographic area. Perhaps not surprisingly, rock art sites appear to be clustered around inland deltas where resources would have been most plentiful. Across the Sahara, at least twenty-three species of fish have been identified in archaeological deposits from the Holocene, the most common being Tilapia, Catfish, African jewelfish, Silver fish and Nile perch. But can we go as far as to correlate the archaeological record with the rock art to species level? - sys: id: 5J2YaEVcDSk8E8mqsYeYC6 created_at: !ruby/object:DateTime 2015-11-26 16:36:02.168000000 Z updated_at: !ruby/object:DateTime 2018-05-16 17:51:34.767000000 Z content_type_id: image revision: 2 image: sys: id: 62OPN6zwbKOym4YUAKCoAY created_at: !ruby/object:DateTime 2015-11-26 16:33:44.984000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:33:44.984000000 Z title: Fig. 4. African jewelfish description: url: "//images.ctfassets.net/xt8ne4gbbocd/62OPN6zwbKOym4YUAKCoAY/b23a2b5b8d528ba735cf4e91c7a748c9/Fig._4._African_jewelfish.jpg" caption: African jewelfish (Hemichromis bimaculatus). Image ©Zhyla (Wikimedia Commons) col_link: https://commons.wikimedia.org/wiki/File:Hemichromis_bimaculatus1.jpg - sys: id: 4mxD1mNZu8OegCaGC60o8o created_at: !ruby/object:DateTime 2015-11-26 16:36:34.680000000 Z updated_at: !ruby/object:DateTime 2018-05-16 18:02:17.202000000 Z content_type_id: image revision: 3 image: sys: id: oV9yR91U3YSg2McmgeCA2 created_at: !ruby/object:DateTime 2015-11-26 16:33:44.982000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:33:44.982000000 Z title: Fig. 5. Redbelly Tilapia description: url: "//images.ctfassets.net/xt8ne4gbbocd/oV9yR91U3YSg2McmgeCA2/780ac15c52522b76348ecebbd4cc123d/Fig._5._Redbelly_Tilapia.jpg" caption: Redbelly Tilapia (Tilapia zillii). Image © <NAME> (Wikimedia Commons) col_link: https://commons.wikimedia.org/wiki/File%3AFresh_tilapia.jpg - sys: id: gbhjHlWzFCKyeeiUGEkaQ created_at: !ruby/object:DateTime 2015-11-26 17:00:13.905000000 Z updated_at: !ruby/object:DateTime 2018-05-16 17:57:51.334000000 Z content_type_id: chapter revision: 2 title_internal: 'Thematic: fishing, chapter 3' body: Rock art imagery is replete with both very naturalistic representations and also those which are more conceptual or abstract in nature, and the depictions of fish are no exception. While some representations are clearly identifiable as fish, other are more difficult to identify. For example, the image above from Afforzighiar shows vertical red dots on the left of the photograph are arranged in a fish-like shape that converges at the top and bottom. Additionally it has been deliberately placed on a section of the rock face where there is water seepage, blending the art with the natural environment. The dotted pattern is reminiscent of the African jewelfish (*Hemichromis bimaculatus*) or even the Redbelly Tilapia (*Tilapia zillii*), both shown to be species of fish found throughout much of the Sahara during the Holocene. - sys: id: 5XJMMCBGveKKqoIc8kGEQU created_at: !ruby/object:DateTime 2015-11-26 16:37:00.084000000 Z updated_at: !ruby/object:DateTime 2018-05-16 18:04:03.162000000 Z content_type_id: image revision: 3 image: sys: id: 4fQKRSGFIA6OMCe8waOWmM created_at: !ruby/object:DateTime 2015-11-26 16:33:34.492000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:33:34.492000000 Z title: '2013,2034.559' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4fQKRSGFIA6OMCe8waOWmM/0a976c617609964467168ae590f831a8/2013_2034.559.jpg" caption: Five fish engraved on a rock face. <NAME>, Acacus Mountains, Libya. 2013,2034.559 ©<NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3585024&partId=1&people=197356&museumno=2013,2034.559&page=1 - sys: id: 4gUY4mSYnKYk8UIMSGAike created_at: !ruby/object:DateTime 2015-11-26 16:37:27.294000000 Z updated_at: !ruby/object:DateTime 2018-05-16 18:02:43.933000000 Z content_type_id: image revision: 3 image: sys: id: rJLJBELLi0yAYiCuM4SWi created_at: !ruby/object:DateTime 2015-11-26 16:33:40.236000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:33:40.236000000 Z title: Fig. 7. African sharptooth catfish description: url: "//images.ctfassets.net/xt8ne4gbbocd/rJLJBELLi0yAYiCuM4SWi/31fdd8fe74786561592c1d104aa2ab13/Fig._7._African_sharptooth_catfish.jpg" caption: African sharptooth catfish (Clarias gariepinus). Image ©<NAME> (Wie146) (Wikimedia Commons) col_link: https://commons.wikimedia.org/wiki/File%3AClarias_garie_080516_9142_tdp.jpg - sys: id: 1pIt8kfkgAQ6ueEWMSqyAM created_at: !ruby/object:DateTime 2015-11-26 16:37:55.248000000 Z updated_at: !ruby/object:DateTime 2018-05-16 17:59:58.067000000 Z content_type_id: image revision: 2 image: sys: id: 14NfPoZlKIUOoacY8GWQ4c created_at: !ruby/object:DateTime 2015-11-26 16:33:44.971000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:33:44.971000000 Z title: '2013,2034.925' description: url: "//images.ctfassets.net/xt8ne4gbbocd/14NfPoZlKIUOoacY8GWQ4c/88845134e8a0ef3fcf489e93e67f321e/2013_2034.925.jpg" caption: Engraved fish. Affozighiar, Acacus Mountains, Libya 2013,2034.925 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3587559&partId=1&people=197356&museumno=2013,2034.925&page=1 - sys: id: 5Kvn7LZDEcc0iGm0O4u6uY created_at: !ruby/object:DateTime 2015-11-26 17:00:36.225000000 Z updated_at: !ruby/object:DateTime 2018-05-16 18:00:54.782000000 Z content_type_id: chapter revision: 2 title_internal: 'Thematic: fishing, chapter 4' body: Some of the engravings bear close morphological resemblances to Catfish, with even the barbels depicted. Catfish seem to occur more regularly in rock art than other species of fish, possibly due to their physical characteristics. They possess an auxiliary breathing organ which allows them to inhabit extremely de-oxygenated water; in fact, when necessary they can obtain up to 50% of their total oxygen requirements from the air. In some cases they will leave the water and crawl on dry ground to escape drying pools. This capacity to live in very shallow waters and to occupy the liminal spaces between land and water has elevated them to more than a simple food source and given them a place of cultural significance in many African societies. - sys: id: sTBWoIZ2yyuS04mEIYYus created_at: !ruby/object:DateTime 2015-11-26 16:38:21.905000000 Z updated_at: !ruby/object:DateTime 2018-05-16 18:01:22.453000000 Z content_type_id: image revision: 2 image: sys: id: 3nZmrbE5yUEuc2qaWc2Age created_at: !ruby/object:DateTime 2015-11-26 16:33:56.244000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:33:56.244000000 Z title: '2013,2034.5255' description: url: "//images.ctfassets.net/xt8ne4gbbocd/3nZmrbE5yUEuc2qaWc2Age/5bf831c50428a19572df28872a18e3d1/2013_2034.5255.jpg" caption: Engraved fish on a boulder. <NAME>, <NAME>, Morocco. 2013,2034.5255 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3603483&partId=1&people=197356&museumno=2013,2034.5255&page=1 - sys: id: 5RuLsZVAOswgaaKG8CK0AQ created_at: !ruby/object:DateTime 2015-11-26 16:38:50.016000000 Z updated_at: !ruby/object:DateTime 2018-05-16 18:03:15.219000000 Z content_type_id: image revision: 2 image: sys: id: 7M6nZhpTuoUuOOk0oWu8ea created_at: !ruby/object:DateTime 2015-11-26 16:33:44.984000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:33:44.984000000 Z title: Fig. 10. Silver fish description: url: "//images.ctfassets.net/xt8ne4gbbocd/7M6nZhpTuoUuOOk0oWu8ea/04a411cc75ddded8230ee77128e3200a/Fig._10._Silver_fish.jpg" caption: Silver fish (Raiamas senegalensis). Image ©<NAME> (Wikimedia Commons) col_link: https://commons.wikimedia.org/wiki/File%3ACameroon2011_3_(1)_(7003774697).jpg - sys: id: 3SIbv3l2WQqe4Wa08Ew6cI created_at: !ruby/object:DateTime 2015-11-26 17:00:55.256000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:00:55.256000000 Z content_type_id: chapter revision: 1 title_internal: 'Thematic: fishing, chapter 5' body: In arid ecosystems, bodies of water are characterised by daily and seasonal fluctuations in water temperature, evaporation and other natural phenomena, and some fish species have adapted well to cope with these extreme changes in water chemistry. Catfish and Tilapia in particular are able to survive high salinity, which occurs through evaporation, while Redbelly Tilapia can also tolerate temperatures above 35° C. Both Sharptooth Catfish and Tilapia are floodplain dwellers and possess the ability to live and spawn in shallow waters, making them easily susceptible to predation. Catfish spines were also used to decorate Saharan pottery with dotted wavy-line patterns. These biological characteristics, which meant they could be easily hunted, may explain their frequent depiction in rock art. Perhaps their value was also reinforced by their being (possibly) the last fish species to survive once aridification had taken hold in the Sahara. - sys: id: 20MArnOyXuuIgo4g642QQa created_at: !ruby/object:DateTime 2015-11-26 17:01:46.522000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:01:46.522000000 Z content_type_id: chapter revision: 1 title: Fishing title_internal: 'Thematic: fishing, chapter 6' body: Fish are likely to have been caught in a variety of ways, but in the Sahara the most common technique was to use barbed bone point and/or fish hook technology, with the former being the most archaeologically visible. Barbed points may either be fixed – that is permanently attached to a spear or arrow shaft – or used as ‘harpoons’, when they separate from a shaft on impact and remain attached by a line. Barbed points can actually be used to catch multiple types of prey, but the primary use across Africa was for fish. - sys: id: 1bwCettQ98qY2wEyiQMOmU created_at: !ruby/object:DateTime 2015-11-26 16:39:23.290000000 Z updated_at: !ruby/object:DateTime 2019-02-21 14:59:03.644000000 Z content_type_id: image revision: 3 image: sys: id: 4cgsOBoxReGOAiCqw2UYM8 created_at: !ruby/object:DateTime 2015-11-26 16:33:40.242000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:33:40.242000000 Z title: Fig. 11. Bone point from Katanda description: url: "//images.ctfassets.net/xt8ne4gbbocd/4cgsOBoxReGOAiCqw2UYM8/e84d40b791670fc04e8b47d312248bd5/Fig._11._Bone_point_from_Katanda.jpg" caption: Bone point from Katanda, DRC, 80,000-90,000 BP. Image ©Human Origins Program, Smithsonian Institution col_link: hhttp://humanorigins.si.edu/evidence/behavior/getting-food/katanda-bone-harpoon-point - sys: id: 159mLyHGvyC4ccwOQMyQIs created_at: !ruby/object:DateTime 2015-11-26 17:02:05.585000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:02:05.585000000 Z content_type_id: chapter revision: 1 title_internal: 'Thematic: fishing, chapter 7' body: Chronologically, the earliest barbed bone point records are from Katanda in the Upper Semliki Valley in modern-day Democratic Republic of the Congo, dating to 80,000 – 90,000 years ago. Here people were catching Catfish weighing up to 68 kg (150 lb), sufficient to feed eighty people for two days. Research has noted the distribution of barbed bone points across the Sahara, and the correlation between these locations and the distribution of species requiring deep water. It is clear that there is continuity in sophisticated fishing technology and practice that has lasted tens of thousands of years. - sys: id: 2IWFdXQZl6WwuCgA6oUa8u created_at: !ruby/object:DateTime 2015-11-26 17:02:48.620000000 Z updated_at: !ruby/object:DateTime 2018-05-17 10:26:57.354000000 Z content_type_id: chapter revision: 2 title: Other aquatic species title_internal: 'Thematic: fishing, chapter 8' body: Other aquatic species are more difficult to identify and are much rarer. For example, the image below has been interpreted as a jelly-fish like creature. However, by manipulating the colour and lighting, the image is a little clearer and appears to share morphological characteristics, such as the rounded carapace and small flippers, with a turtle rather than a jellyfish. Furthermore, we know that softshell turtles (*Trionyx triunguis*) have been found in archaeological deposits in the Sahara dating to the Holocene. The vertical and wavy strands hanging down underneath could represent the pattern made in the sand by turtles when walking rather than being the tendrils of a jellyfish. In addition, the image from Wadi Tafak below appears to resemble a snail, and is consistent with what we know about the Capsian culture who inhabited modern Tunisia, Algeria, and parts of Libya during the early Holocene (10000–6000 BC). Their distinguishing culinary feature was a fondness for escargots – edible land snails. - sys: id: 5j7XInUteECEA6cSE48k4A created_at: !ruby/object:DateTime 2015-11-26 16:39:52.787000000 Z updated_at: !ruby/object:DateTime 2018-05-17 10:34:45.084000000 Z content_type_id: image revision: 2 image: sys: id: 7pDQ1Q7cm4u4KKkayeugGY created_at: !ruby/object:DateTime 2015-11-26 16:33:44.977000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:33:44.977000000 Z title: '2013,2034.4298' description: url: "//images.ctfassets.net/xt8ne4gbbocd/7pDQ1Q7cm4u4KKkayeugGY/094c9283ceeded55f016eafbc00e131c/2013_2034.4298.jpg" caption: Painting of a turtle (digitally manipulated) from Jabbaren, Algeria. 2013,2034.4298 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3601635&partId=1&people=197356&museumno=2013,2034.4298&page=1 - sys: id: 2pq6oldgxGsq48iIUsKEyg created_at: !ruby/object:DateTime 2015-11-26 16:40:52.658000000 Z updated_at: !ruby/object:DateTime 2018-05-17 10:35:17.649000000 Z content_type_id: image revision: 2 image: sys: id: 6k5J6VbwZOq2yg86Y4GsEc created_at: !ruby/object:DateTime 2015-11-26 16:33:40.222000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:33:40.222000000 Z title: '2013,2034.1167' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6k5J6VbwZOq2yg86Y4GsEc/3db2c57978de4879d82e7b04833d4564/2013_2034.1167.jpg" caption: Painting of a snail from Wadi Tafak, Acacus Mountains, Libya. 2013,2034.1167 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3593787&partId=1&people=197356&museumno=2013,2034.1167&page=1 - sys: id: k7ChxGbsyc2iSaOc0k62C created_at: !ruby/object:DateTime 2015-11-26 17:03:15.438000000 Z updated_at: !ruby/object:DateTime 2018-05-17 10:50:37.252000000 Z content_type_id: chapter revision: 2 title: Case study – Gobero title_internal: 'Thematic: fishing, chapter 9' body: A recently excavated cemetery site called Gobero (Sereno *et al.* 2008), situated on the western edge of the Ténéré desert in Niger, provides a uniquely preserved record of human occupation in the Sahara during the Holocene and puts into context some of the examples of rock art we have looked at here. Pollen analysis has indicated that during the Holocene, Gobero was situated in an open savannah landscape of grasses and sedges, with fig trees and tamarisk, where permanent water and marshy habitats were present. - sys: id: 7D5HIm20CW4WMy0IgyQQOu created_at: !ruby/object:DateTime 2015-11-26 16:41:18.798000000 Z updated_at: !ruby/object:DateTime 2018-05-17 10:52:51.807000000 Z content_type_id: image revision: 2 image: sys: id: 5ZHSZA9fHOyAu8kaMceGOa created_at: !ruby/object:DateTime 2015-11-26 16:33:40.277000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:33:40.277000000 Z title: Fig. 14. Aerial view of Gobero description: url: "//images.ctfassets.net/xt8ne4gbbocd/5ZHSZA9fHOyAu8kaMceGOa/a546de3d31a679d75b67e4e2f4e41c68/Fig._14._Aerial_view_of_Gobero.jpg" caption: Aerial view of Gobero archaeological site (from Sereno et al. 2008). col_link: http://journals.plos.org/plosone/article?id=10.1371/journal.pone.0002995 - sys: id: 1wHHAMslowaeSOAWaue4Om created_at: !ruby/object:DateTime 2015-11-26 17:03:47.119000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:03:47.119000000 Z content_type_id: chapter revision: 1 title_internal: 'Thematic: fishing, chapter 10' body: |- Approximately 200 burials, ranging over a 5000-year period, were found on the edge of an ancient lake. Grave goods include bones or tusks from wild fauna, ceramics, lithic projectile points, and bone, ivory and shell ornaments. One adult male was buried in a recumbent pose seated on the carapace of a mud turtle. Microliths, bone harpoon points and hooks, and ceramics with dotted wavy-line and zigzag impressed motifs were found in the burial fill, in an associated midden area, and in nearby paleolake deposits. Nile perch (*Lates niloticus*), large catfish, and tilapia dominate the midden fauna, which also includes bones and teeth from hippos, several bovids, small carnivores, softshell turtles and crocodiles. The early Holocene occupants at Gobero (7700–6300 BC.) were largely sedentary hunter-fisher-gatherers with lakeside funerary sites. Across the ‘green’ Sahara, Catfish, Tilapia and turtles played important roles socially, economically and culturally. We can see this most explicitly in the burial within a turtle carapace in Gobero, but the representation of aquatic animals in rock art is a significant testament to their value. citations: - sys: id: 6JNu3sK5DGaUyWo4omoc2M created_at: !ruby/object:DateTime 2015-11-26 16:58:14.227000000 Z updated_at: !ruby/object:DateTime 2019-02-21 15:03:53.071000000 Z content_type_id: citation revision: 2 citation_line: '<NAME>., <NAME>., <NAME>., <NAME>., <NAME>., et al. 2008. *Lakeside Cemeteries in the Sahara: 5000 Years of Holocene Population and Environmental Change*. PLoS ONE 3(8): [https://doi.org/10.1371/journal.pone.0002995](https://doi.org/10.1371/journal.pone.0002995)' background_images: - sys: id: 1MzxjY9CecYwee0IWcCQqe created_at: !ruby/object:DateTime 2015-12-07 18:22:52.418000000 Z updated_at: !ruby/object:DateTime 2015-12-07 18:22:52.418000000 Z title: EAF 141260 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1MzxjY9CecYwee0IWcCQqe/61da964c9b38a509ca9f602f7ac5747c/EAF_141260.jpg" - sys: id: BdGy2n8Krecyks0s4oe8e created_at: !ruby/object:DateTime 2015-12-07 18:22:52.407000000 Z updated_at: !ruby/object:DateTime 2015-12-07 18:22:52.407000000 Z title: 01557634 001 description: url: "//images.ctfassets.net/xt8ne4gbbocd/BdGy2n8Krecyks0s4oe8e/7130c75aba21829540524182a5350677/01557634_001.jpg" ---<file_sep>/_coll_thematic/the-domesticated-horse.md --- contentful: sys: id: 7oNFGUa6g8qSweyAyyiCAe created_at: !ruby/object:DateTime 2015-11-26 18:11:30.861000000 Z updated_at: !ruby/object:DateTime 2015-12-07 20:51:34.879000000 Z content_type_id: thematic revision: 4 title: The domesticated horse in northern African rock art slug: the-domesticated-horse lead_image: sys: id: n2MxgdjbMW2gm0IoOKkCU created_at: !ruby/object:DateTime 2015-11-26 17:51:43.133000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:43.133000000 Z title: Fig. 1. Painted horse description: url: "//images.ctfassets.net/xt8ne4gbbocd/n2MxgdjbMW2gm0IoOKkCU/e2c7369ef1e4ab11c71023a769f8fe0d/Fig._1._Painted_horse.jpg" chapters: - sys: id: 27bcd1mylKoMWiCQ2KuKMa created_at: !ruby/object:DateTime 2015-11-26 18:00:19.777000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:00:19.777000000 Z content_type_id: chapter revision: 1 title_internal: 'Thematic: horse, chapter 1' body: Throughout northern Africa, there is a wealth of rock art depicting the domestic horse and its various uses, providing valuable evidence for the uses of horses at various times in history, as well as a testament to their importance to Saharan peoples. - sys: id: 2EbfpTN9L6E0sYmuGyiaec created_at: !ruby/object:DateTime 2015-11-26 17:52:26.605000000 Z updated_at: !ruby/object:DateTime 2018-05-15 16:39:29.412000000 Z content_type_id: image revision: 2 image: sys: id: n2MxgdjbMW2gm0IoOKkCU created_at: !ruby/object:DateTime 2015-11-26 17:51:43.133000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:43.133000000 Z title: Fig. 1. Painted horse description: url: "//images.ctfassets.net/xt8ne4gbbocd/n2MxgdjbMW2gm0IoOKkCU/e2c7369ef1e4ab11c71023a769f8fe0d/Fig._1._Painted_horse.jpg" caption: 'Painted horse and rider, Ennedi Plateau, Chad. 2013,2034.6406 © TARA/David Coulson. ' col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3641775&partId=1&searchText=2013,2034.6406&page=1 - sys: id: 4QexWBEVXiAksikIK6g2S4 created_at: !ruby/object:DateTime 2015-11-26 18:00:49.116000000 Z updated_at: !ruby/object:DateTime 2018-05-15 16:40:28.446000000 Z content_type_id: chapter revision: 2 title: Horses and chariots title_internal: 'Thematic: horse, chapter 2' body: The first introduction of the domestic horse to Ancient Egypt- and thereby to Africa- is usually cited at around 1600 BC, linked with the arrival in Egypt of the Hyksos, a group from the Levant who ruled much of Northern Egypt during the Second Intermediate Period. By this point, horses had probably only been domesticated for about 2,000 years, but with the advent of the chariot after the 3rd millennium BC in Mesopotamia, the horse proved to be a valuable martial asset in the ancient world. One of the first clear records of the use of horses and chariots in battle in Africa is found in depictions from the mortuary complex of the Pharaoh Ahmose at Abydos from around 1525 BC, showing their use by Egyptians in defeating the Hyksos, and horses feature prominently in later Egyptian art. - sys: id: 22x06a7DteI0C2U6w6oKes created_at: !ruby/object:DateTime 2015-11-26 17:52:52.323000000 Z updated_at: !ruby/object:DateTime 2018-05-15 16:40:52.214000000 Z content_type_id: image revision: 2 image: sys: id: 1AZD3AxiUwwoYUWSWY8MGW created_at: !ruby/object:DateTime 2015-11-26 17:51:50.284000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:50.284000000 Z title: '2013,2034.1001' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1AZD3AxiUwwoYUWSWY8MGW/b68bd24c9b19c5c8c7752bfb75a5db0e/2013_2034.1001.jpg" caption: Painted two-horse chariot, Acacus Mountains, Libya. 2013,2034.1001 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3588526&partId=1&people=197356&museumno=2013,2034.1001&page=1 - sys: id: 1voXfvqIcQkgUYqq4w8isQ created_at: !ruby/object:DateTime 2015-11-26 18:01:15.173000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:01:15.173000000 Z content_type_id: chapter revision: 1 title_internal: 'Thematic: horse, chapter 3' body: 'Some of the most renowned images of horses in Saharan rock art are also those of chariot teams: in particular, those of the so-called ‘flying gallop’ style chariot pictures, from the Tassili n’Ajjer and Acacus mountains in modern Algeria and Libya. These distinctive images are characterised by depictions of one or more horses pulling a chariot with their legs outstretched in a stylised manner and are sometimes attributed to the Garamantes, a group who were a local power in the central Sahara from about 500 BC-700 AD. But the Ajjer Plateau is over a thousand miles from the Nile- how and when did the horse and chariot first make their way across the Western Desert to the rest of North Africa in the first place? Egyptian accounts indicate that by the 11th century BC Libyans (people living on the north African coast around the border of modern Egypt and Libya) were using chariots in war. Classical sources later write about the chariots of the Garamantes and of chariot use by peoples of the far western Sahara continuing into the 1st century BC, by which time the chariot horse had largely been eclipsed in war by the cavalry mount.' - sys: id: LWROS2FhUkywWI60eQYIy created_at: !ruby/object:DateTime 2015-11-26 17:53:42.845000000 Z updated_at: !ruby/object:DateTime 2018-05-15 16:41:33.841000000 Z content_type_id: image revision: 2 image: sys: id: 6N6BF79qk8EUygwkIgwcce created_at: !ruby/object:DateTime 2015-11-26 17:51:44.708000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:44.708000000 Z title: '2013,2034.4574' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6N6BF79qk8EUygwkIgwcce/ac95a5214a326794542e0707c0d819d7/2013_2034.4574.jpg" caption: Painted human figure and horse. Tarssed Jebest, Tassili n’Ajjer, Algeria. Horse displays Arabian breed-type characteristics such as dished face and high tail carriage. 2013,2034.4574 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3603790&partId=1&people=197356&museumno=2013,2034.4574+&page=1 - sys: id: 6eaH84QdUs46sEQoSmAG2u created_at: !ruby/object:DateTime 2015-11-26 18:01:48.835000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:01:48.835000000 Z content_type_id: chapter revision: 1 title: Horse Riding title_internal: 'Thematic: horse, chapter 4' body: As well as the unique iconography of rock art chariot depictions, there are also numerous paintings and engravings across northern Africa of people riding horses. Riding may have been practiced since the earliest times of horse domestication, though the earliest definitive depictions of horses being ridden come from the Middle East in the late 3rd and early 2nd millennia BC. Images of horses and riders in rock art occur in various areas of Morocco, Egypt and Sudan and are particularly notable in the Ennedi region of Chad and the Adrar and Tagant plateaus in Mauritania (interestingly, however, no definite images of horses are known in the Gilf Kebir/Jebel Uweinat area at the border of Egypt, Sudan and Libya). - sys: id: 6LTzLWMCTSak4IIukAAQMa created_at: !ruby/object:DateTime 2015-11-26 17:54:23.846000000 Z updated_at: !ruby/object:DateTime 2018-05-15 16:41:52.743000000 Z content_type_id: image revision: 2 image: sys: id: 4NdhGNLc9yEck4My4uQwIo created_at: !ruby/object:DateTime 2015-11-26 17:51:43.495000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:43.495000000 Z title: ME22958 description: url: "//images.ctfassets.net/xt8ne4gbbocd/4NdhGNLc9yEck4My4uQwIo/703945afad6a8e3c97d10b09c487381c/ME22958.jpg" caption: Terracotta mould of man on horseback, Old Babylonian, Mesopotamia 2000-1600 BC. One of the oldest known depictions of horse riding in the world. British Museum ME22958 © Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=388860&partId=1&people=197356&museumno=22958&page=1 - sys: id: 5YkSCzujy8o08yuomIu6Ei created_at: !ruby/object:DateTime 2015-11-26 17:54:43.227000000 Z updated_at: !ruby/object:DateTime 2018-05-16 11:12:34.068000000 Z content_type_id: image revision: 2 image: sys: id: 1tpjS4kZZ6YoeiWeIi8I4C created_at: !ruby/object:DateTime 2015-11-26 17:51:43.188000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:43.188000000 Z title: Fig. 5. Painted ‘bitriangular’ description: url: "//images.ctfassets.net/xt8ne4gbbocd/1tpjS4kZZ6YoeiWeIi8I4C/c798c1afb41006855c34363ec2b54557/Fig._5._Painted____bitriangular___.jpg" caption: Painted ‘bi-triangular’ horse and rider with saddle. Oued Jrid, Assaba, Mauritania. 2013,2034.12285 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3645983&partId=1&searchText=2013,2034.12285&page=1 - sys: id: 1vZDFfKXU0US2qkuaikG8m created_at: !ruby/object:DateTime 2015-11-26 18:02:13.433000000 Z updated_at: !ruby/object:DateTime 2018-05-16 11:14:56.468000000 Z content_type_id: chapter revision: 2 title_internal: 'Thematic: horse, chapter 5' body: Traditional chronologies for Saharan rock art areas tend to place depictions of ridden horses chronologically after those of horses and chariots, and in general use horse depictions to categorise regional stylistic periods of rock art according to broad date boundaries. As such, in most places, the ‘horse’ rock art period is usually said to cover about a thousand years from the end of the 2nd millennium BC. It is then considered to be succeeded by a ‘camel’ period, where the appearance of images of dromedaries – known only to have been introduced to the eastern Sahara from Arabia at the end of the 1st century BC – reflects the next momentous influx of a beast of burden to the area and thus a new dating parameter ([read more about depictions of camels in the Sahara](https://africanrockart.britishmuseum.org/thematic/camels-in-saharan-rock-art/)). However, such simplistic categorisation can be misleading. For one thing, although mounting horses certainly gained popularity over driving them, it is not always clear that depictions of ridden horses are not contemporary with those of chariots. Further, the horse remained an important martial tool after the use of war-chariots declined. Even after the introduction of the camel, there are several apparently contemporary depictions featuring both horse and camel riders. - sys: id: 2gaHPgtyEwsyQcUqEIaGaq created_at: !ruby/object:DateTime 2015-11-26 17:55:29.704000000 Z updated_at: !ruby/object:DateTime 2018-05-16 11:32:44.364000000 Z content_type_id: image revision: 3 image: sys: id: 6quML2y0nuYgSaeG0GGYy4 created_at: !ruby/object:DateTime 2015-11-26 17:51:50.292000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:50.292000000 Z title: '2013,2034.5739' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6quML2y0nuYgSaeG0GGYy4/7f48ae9c550dd6b4f0e80b8da10a3da6/2013_2034.5739.jpg" caption: Engraved ridden horse and camel. Draa Valley, Morocco. 2013,2034.5739 ©TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3619780&partId=1&people=197356&museumno=2013,2034.5739+&page=1 - sys: id: 583LKSbz9SSg00uwsqquAG created_at: !ruby/object:DateTime 2015-11-26 18:02:41.576000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:02:41.576000000 Z content_type_id: chapter revision: 1 title: Berber Horses title_internal: 'Thematic: horse, chapter 6' body: As the more manoeuvrable rider rose in popularity against the chariot as a weapon of war, historical reports from classical authors like Strabo tell us of the prowess of African horsemen such as the cavalry of the Numidians, a Berber group that allied with Carthage against the Romans in the 3rd century BC. Berber peoples would remain heavily associated with horse breeding and riding, and the later rock art of Mauritania has been attributed to Berber horsemen, or the sight of them. Although horses may already have reached the areas of modern Mauritania and Mali by this point, archaeological evidence does not confirm their presence in these south-westerly regions of the Sahara until much later, in the mid-1st millennium AD, and it has been suggested that some of the horse paintings in Mauritania may be as recent as 16th century. - sys: id: 7zrBlvCEGkW86Qm8k2GQAK created_at: !ruby/object:DateTime 2015-11-26 17:56:24.617000000 Z updated_at: !ruby/object:DateTime 2018-05-16 11:16:52.557000000 Z content_type_id: image revision: 2 image: sys: id: uOFcng0Q0gU8WG8kI2kyy created_at: !ruby/object:DateTime 2015-11-26 17:51:44.717000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:44.717000000 Z title: '2013,2034.5202' description: url: "//images.ctfassets.net/xt8ne4gbbocd/uOFcng0Q0gU8WG8kI2kyy/7fba0330e151fc416d62333f3093d950/2013_2034.5202.jpg" caption: Engraved horses and riders surrounded by Libyan-Berber script. Oued Djerat, Algeria. These images appear to depict riders using Arab-style saddles and stirrups, thus making them probably no older than 7th c. AD. 2013,2034.5202 © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3624404&partId=1&people=197356&museumno=2013,2034.5202&page=1 - sys: id: 45vpX8SP7aGeOS0qGaoo4a created_at: !ruby/object:DateTime 2015-11-26 18:03:14.279000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:03:14.279000000 Z content_type_id: chapter revision: 1 title_internal: 'Thematic: horse, chapter 7' body: 'Certainly, from the 14th century AD, horses became a key commodity in trans-Saharan trade routes and became items of great military value in West Africa following the introduction of equipment such as saddles with structured trees (frames). Indeed, discernible images of such accoutrements in Saharan rock art can help to date it following the likely introduction of the equipment to the area: for example, the clear depiction of saddles suggests an image to be no older than the 1st century AD; images including stirrups are even more recent.' - sys: id: 7GeTQBofPamw0GeEAuGGee created_at: !ruby/object:DateTime 2015-11-26 17:56:57.851000000 Z updated_at: !ruby/object:DateTime 2018-05-16 11:29:02.520000000 Z content_type_id: image revision: 2 image: sys: id: 5MaSKooQvYssI4us8G0MyO created_at: !ruby/object:DateTime 2015-11-26 17:51:43.501000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:43.501000000 Z title: RRM12824 description: url: "//images.ctfassets.net/xt8ne4gbbocd/5MaSKooQvYssI4us8G0MyO/8c3a7c2d372f2c48a868d60201909932/RRM12824.jpg" caption: 19th-century Moroccan stirrups with typical curved base of the type possibly visible in the image above. 1939,0311.7-8 © Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=217451&partId=1&page=1 - sys: id: 6mNtqnqaEE2geSkU0IiYYe created_at: !ruby/object:DateTime 2015-11-26 18:03:32.195000000 Z updated_at: !ruby/object:DateTime 2018-05-16 11:29:50.228000000 Z content_type_id: chapter revision: 2 title_internal: 'Thematic: horse, chapter 8' body: 'Another intriguing possibility is that of gaining clues on the origins of modern horse breeds from rock art, in particular the ancient Barb breed native to the Maghreb, where it is still bred. Ancient Mesopotamian horses were generally depicted as heavily-built, and it has been suggested that the basic type for the delicate Arabian horse, with its dished (concave) facial profile and high-set tail, may have been developed in north-east Africa prior to its subsequent appearance and cultivation in Arabia, and that these features may be observed in Ancient Egyptian images from the New Kingdom. Likewise, there is the possibility that some of the more naturalistic paintings from the central Sahara show the similarly gracile features of the progenitors of the Barb, distinguishable from the Arab by its straight profile and low-set tail. Like the Arab, the Barb is a desert horse: hardy, sure-footed and able to withstand great heat; it is recognised as an ancient breed with an important genetic legacy, both in the ancestry of the Iberian horses later used throughout the Americas, and that of the modern racing thoroughbred.' - sys: id: 3OM1XJI6ruwGOwwmkKOKaY created_at: !ruby/object:DateTime 2015-11-26 17:57:25.145000000 Z updated_at: !ruby/object:DateTime 2018-05-16 11:30:30.915000000 Z content_type_id: image revision: 2 image: sys: id: 6ZmNhZjLCoQSEIYKIYUUuk created_at: !ruby/object:DateTime 2015-11-26 17:51:50.293000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:50.293000000 Z title: '2013,2034.1452' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6ZmNhZjLCoQSEIYKIYUUuk/45bbff5b29985eb19679e1e513499d6b/2013_2034.1452.jpg" caption: Engraved horses and riders, Awis, Acacus Mountains, Libya. High head carriage and full rumps suggest Arabian/Barb breed type features. Riders have been obscured. 2013,2034.1452 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3592678&partId=1&people=197356&museumno=2013,2034.1452&page=1 - sys: id: 40E0pTCrUIkk00uGWsus4M created_at: !ruby/object:DateTime 2015-11-26 17:57:49.497000000 Z updated_at: !ruby/object:DateTime 2018-05-16 11:33:55.443000000 Z content_type_id: image revision: 2 image: sys: id: 5mbJWrbZV6aQQOyamKMqIa created_at: !ruby/object:DateTime 2015-11-26 17:51:43.468000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:43.468000000 Z title: Fig. 10. Barb horses description: url: "//images.ctfassets.net/xt8ne4gbbocd/5mbJWrbZV6aQQOyamKMqIa/87f29480513be0a531e0a93b51f9eae5/Fig._10._Barb_horses.jpg" caption: Barb horses ridden at a festival in Agadir, Morocco. ©Notwist (Wikimedia Commons) col_link: https://commons.wikimedia.org/wiki/File:Berber_warriors_show.JPG - sys: id: 3z5YSVu9y8caY6AoYWge2q created_at: !ruby/object:DateTime 2015-11-26 18:04:02.770000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:04:02.770000000 Z content_type_id: chapter revision: 1 title: The symbolism of the horse title_internal: 'Thematic: horse, chapter 9' body: However, caution must be taken in drawing such comparisons based on morphology alone, especially given the gulf of time that has elapsed and the relative paucity of ‘naturalistic’ rock art images. Indeed, there is huge diversity of horse depictions throughout northern Africa, with some forms highly schematic. This variation is not only in style – and, as previously noted, in time period and geography – but also in context, as of course images of one subject cannot be divorced from the other images around them, on whichever surface has been chosen, and are integral to these surroundings. - sys: id: 1FRP1Z2hyQEWUSOoKqgic2 created_at: !ruby/object:DateTime 2015-11-26 17:58:21.234000000 Z updated_at: !ruby/object:DateTime 2019-02-21 15:41:39.821000000 Z content_type_id: image revision: 2 image: sys: id: 4EatwZfN72waIquQqWEeOs created_at: !ruby/object:DateTime 2015-11-26 17:51:43.121000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:43.121000000 Z title: '2013,2034.11147' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4EatwZfN72waIquQqWEeOs/d793f6266f2ff486e0e99256c2c0ca39/2013_2034.11147.jpg" caption: Engraved ‘Libyan Warrior-style’ figure with horse. Indakatte, Western Aïr Mountains, Niger. 2013,2034.11147 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3637713&partId=1&people=197356&museumno=2013,2034.11147+&page=1 - sys: id: 45pI4ivRk4IM6gaG40gUU0 created_at: !ruby/object:DateTime 2015-11-26 17:58:41.308000000 Z updated_at: !ruby/object:DateTime 2019-02-21 15:41:59.784000000 Z content_type_id: image revision: 2 image: sys: id: 2FcYImmyd2YuqMKQMwAM0s created_at: !ruby/object:DateTime 2015-11-26 17:51:43.117000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:43.117000000 Z title: Fig. 12. Human figure description: url: "//images.ctfassets.net/xt8ne4gbbocd/2FcYImmyd2YuqMKQMwAM0s/e48fda8e2a23b12e6afde5c560c3f164/Fig._12._Human_figure.jpg" caption: Human figure painted over by horse to appear mounted (digitally enhanced image). © TARA/<NAME> - sys: id: 54hoc6Htwck8eyewsa6kA8 created_at: !ruby/object:DateTime 2015-11-26 18:04:26.929000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:04:26.929000000 Z content_type_id: chapter revision: 1 title_internal: 'Thematic: horse, chapter 10' body: The nature of the depictions in this sense speaks intriguingly of the apparent symbolism and implied value of the horse image in different cultural contexts. Where some Tassilian horses are delicately painted in lifelike detail, the stockier images of horses associated with the so-called ‘Libyan Warrior’ style petroglyphs of the Aïr mountains and Adrar des Ifoghas in Niger and Mali appear more as symbolic accoutrements to the central human figures and tend not to be shown as ridden. By contrast, there are paintings in the Ennedi plateau of Chad where galloping horse figures have clearly been painted over existing walking human figures to make them appear as if riding. - sys: id: 4XMm1Mdm7Y0QacMuy44EKa created_at: !ruby/object:DateTime 2015-11-26 17:59:06.184000000 Z updated_at: !ruby/object:DateTime 2019-02-21 15:42:27.444000000 Z content_type_id: image revision: 2 image: sys: id: 21xnJrk3dKwW6uSSkGumMS created_at: !ruby/object:DateTime 2015-11-26 17:51:44.697000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:44.697000000 Z title: '2013,2034.6297' description: url: "//images.ctfassets.net/xt8ne4gbbocd/21xnJrk3dKwW6uSSkGumMS/698c254a9a10c5a9a56d69e0525bca83/2013_2034.6297.jpg" caption: Engraved horse, Niola Doa, Ennedi Plateau, Chad. 2013,2034.6297 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3637529&partId=1&people=197356&museumno=2013,2034.6297&page=1 - sys: id: 4rB9FCopjOCC4iA2wOG48w created_at: !ruby/object:DateTime 2015-11-26 17:59:26.549000000 Z updated_at: !ruby/object:DateTime 2019-02-21 15:43:34.211000000 Z content_type_id: image revision: 2 image: sys: id: 3PfHuSbYGcqeo2U4AEKsmM created_at: !ruby/object:DateTime 2015-11-26 17:51:43.196000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:43.196000000 Z title: Fig. 14. Engraved horse description: url: "//images.ctfassets.net/xt8ne4gbbocd/3PfHuSbYGcqeo2U4AEKsmM/33a068fa954954fd3b9b446c943e0791/Fig._14._Engraved_horse.jpg" caption: Engraved horse, Eastern Aïr Mountains. 2013,2034.9421 ©TARA/<NAME>. col_link: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3640574&partId=1&searchText=2013,2034.9421&page=1 - sys: id: 6tFSQzFupywiK6aESCgCia created_at: !ruby/object:DateTime 2015-11-26 18:04:56.612000000 Z updated_at: !ruby/object:DateTime 2019-02-21 15:47:26.838000000 Z content_type_id: chapter revision: 2 title_internal: 'Thematic: horse, chapter 11' body: |- In each of these cases, the original symbolic intent of the artists have been lost to time, but with these horse depictions, as with so much African rock art imagery, there is great scope for further future analysis. Particularly intriguing, for example, are the striking stylistic similarities in horse depictions across great distances, such the horse depictions with bi-triangular bodies (see above), or with fishbone-style tails which may be found almost two thousand miles apart in Chad and Mauritania. Whatever the myriad circumstances and significances of the images, it is clear that following its introduction to the continent, the hardy and surefooted desert horse’s usefulness for draught, transport and fighting purposes transformed the societies which used it and gave it a powerful symbolic value. - sys: id: 2P6ERbclfOIcGEgI6e0IUq created_at: !ruby/object:DateTime 2015-11-26 17:59:46.042000000 Z updated_at: !ruby/object:DateTime 2019-02-21 15:45:12.419000000 Z content_type_id: image revision: 2 image: sys: id: 3UXc5NiGTYQcmu2yuU42g created_at: !ruby/object:DateTime 2015-11-26 17:51:43.128000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:43.128000000 Z title: Fig. 15. Painted horse, Terkei description: url: "//images.ctfassets.net/xt8ne4gbbocd/3UXc5NiGTYQcmu2yuU42g/7586f05e83f708ca9d9fca693ae0cd83/Fig._15._Painted_horse__Terkei.jpg" caption: Painted horse, Terkei, Ennedi Plateau, Chad. 2013,2034.6537 © TARA/<NAME> col_link: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3640682&partId=1&searchText=2013,2034.6537&page=1 citations: - sys: id: 32AXGC1EcoSi4KcogoY2qu created_at: !ruby/object:DateTime 2015-11-26 17:51:20.602000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:20.602000000 Z content_type_id: citation revision: 1 citation_line: "<NAME>. & <NAME>. 2000, *The Origins and Development of African Livestock: archaeology, genetics, linguistics and ethnography*. London; New York, NY: UCL Press\n \n<NAME>., <NAME>., <NAME>., 2012. *The Horse: From Arabia to Royal Ascot*. London: British Museum Press\n \nLaw, R., 1980. *The Horse in West African History*. Oxford: Oxford University Press\n \nHachid, M. 2000. *Les Premieres Berbères*. Aix-en-Provence: Edisud\n \nLhote, H. 1952. 'Le cheval et le chameau dans les peintures et gravures rupestres du Sahara', *Bulletin de l'Institut franç ais de l'Afrique noire* 15: 1138-228\n \n<NAME>. & <NAME>. 2010, *A gift from the desert: the art, history, and culture of the Arabian horse*. Lexington, KY: Kentucky Horse Park\n\n" background_images: - sys: id: 2avgKlHUm8CauWie6sKecA created_at: !ruby/object:DateTime 2015-12-07 18:44:31.346000000 Z updated_at: !ruby/object:DateTime 2015-12-07 18:44:31.346000000 Z title: EAF 141485 description: url: "//images.ctfassets.net/xt8ne4gbbocd/2avgKlHUm8CauWie6sKecA/cf02168ca83c922f27eca33f16e8cc90/EAF_141485.jpg" - sys: id: 1wtaUDwbSk4MiyGiISE6i8 created_at: !ruby/object:DateTime 2015-12-07 18:43:51.804000000 Z updated_at: !ruby/object:DateTime 2015-12-07 18:43:51.804000000 Z title: 01522751 001 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1wtaUDwbSk4MiyGiISE6i8/5918544d0289f9c4b2b4724f4cda7a2d/01522751_001.jpg" ---<file_sep>/_coll_regional_introduction/rock-art-in-southern-africa.md --- contentful: sys: id: 5dakRbuMDuCMcqeG4460w4 created_at: !ruby/object:DateTime 2015-12-08 11:50:06.853000000 Z updated_at: !ruby/object:DateTime 2017-03-12 22:07:18.359000000 Z content_type_id: regional_introduction revision: 9 title: 'Introduction to rock art in southern Africa ' intro_progress: true slug: rock-art-in-southern-africa lead_image: - sys: id: 3OZCZuXvlYK4sqSuoqQIqI created_at: !ruby/object:DateTime 2015-12-08 11:52:10.853000000 Z updated_at: !ruby/object:DateTime 2015-12-08 11:52:10.854000000 Z title: SOADRB0080007 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3OZCZuXvlYK4sqSuoqQIqI/711dc818d90fd962cbba4193146af707/SOADRB0080007.jpg" chapters: - sys: id: 5qv45Cw424smAwqkkg4066 created_at: !ruby/object:DateTime 2016-09-13 13:01:39.329000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:09:20.849000000 Z content_type_id: chapter revision: 6 title_internal: 'Southern Africa: regional, chapter 1' body: |+ The southern African countries of Zimbabwe, South Africa, Lesotho, Swaziland, Mozambique, Botswana and Namibia contain thousands of rock art sites and southern African rock art has been studied extensively. Due to perceived similarities in subject matter, even across great distances, much southern African rock art has been ascribed to hunter-gatherer painters and engravers who appear to have had a shared set of cultural references. These have been linked with beliefs and practices which remain common to modern San&#124;Bushman¹ people, a number of traditional hunter-gatherer groups who continue to live in Southern Africa, principally in Namibia, Botswana and South Africa. There are, however, differences in style and technique between regions, and various rock art traditions are attributed to other cultural groups and their ancestors. As is often the case with rock art, the accurate attribution of authorship, date and motivation is difficult to establish, but the rock art of this region continues to be studied and the richness of the material in terms of subject matter, as well as in the context of the archaeological record, has much to tell us, both about its own provenance and the lives of the people who produced it. - sys: id: r3hNyCQVUcGgGmmCKs0sY created_at: !ruby/object:DateTime 2016-09-13 13:02:04.241000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:09:49.095000000 Z content_type_id: chapter revision: 2 title: Geography and distribution title_internal: 'Southern Africa: regional, chapter 2' - sys: id: 5cKrBogJHiAaCs6mMoyqee created_at: !ruby/object:DateTime 2016-09-13 13:02:27.584000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:10:55.925000000 Z content_type_id: image revision: 4 image: sys: id: 4RBHhRPKHC2s6yWcEeWs0c created_at: !ruby/object:DateTime 2016-09-13 13:02:17.232000000 Z updated_at: !ruby/object:DateTime 2016-09-13 13:02:17.232000000 Z title: ZIMMSL0070001 description: url: "//images.ctfassets.net/xt8ne4gbbocd/4RBHhRPKHC2s6yWcEeWs0c/9d9bc5196cfac491fa099fd737b06e34/ZIMMSL0070001.jpg" caption: Yellow elephant calf painted on the roof of a shelter. Mashonaland, Zimbabwe. 2013,2034.22675 ©TARA/<NAME> col_link: http://bit.ly/2iUgvg0 - sys: id: 69tB5BiRVKG2QQEKoSYw08 created_at: !ruby/object:DateTime 2016-09-13 13:02:41.530000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:11:21.260000000 Z content_type_id: chapter revision: 3 title_internal: 'Southern Africa: regional, chapter 3' body: 'There is wide variation in the physical environments of southern Africa, ranging from the rainforests of Mozambique to the arid Namib Desert of western Namibia, with the climate tending to become drier towards the south and west. The central southern African plateau is divided by the central dip of the Kalahari basin, and bordered by the Great Escarpment, a sharp drop in altitude towards the coast which forms a ridge framing much of southern Africa. The escarpment runs in a rough inland parallel to the coastline, from northern Angola, south around the Cape and up in the east to the border between Zimbabwe and Malawi. Both painted and engraved rock art is found throughout southern Africa, with the type and distribution partially informed by the geographical characteristics of the different regions. Inland areas with exposed boulders, flat rock ‘pavements’ and rocky outcrops tend to feature engraved rock art, whereas paintings are more commonly found in the protective rock shelters of mountainous or hilly areas, often in ranges edging the Great Escarpment. ' - sys: id: 4BJ17cEGyIC6QYSYGAkoaa created_at: !ruby/object:DateTime 2016-09-13 13:03:04.486000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:11:57.877000000 Z content_type_id: image revision: 3 image: sys: id: 1hXbvhDSf2CmOss6ec0CsS created_at: !ruby/object:DateTime 2016-09-13 13:02:59.339000000 Z updated_at: !ruby/object:DateTime 2016-09-13 13:02:59.339000000 Z title: NAMBRG0030001 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1hXbvhDSf2CmOss6ec0CsS/0bb079e491ac899abae435773c74fcf4/NAMBRG0030001.jpg" caption: View out of a rock shelter in the Brandberg, Namibia. 2013,2034.20452 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3729901 - sys: id: 499lI34cAE6KAgKU4mkcqq created_at: !ruby/object:DateTime 2016-09-13 13:03:14.736000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:12:17.831000000 Z content_type_id: chapter revision: 5 title: Types of rock art title_internal: 'Southern Africa: regional, chapter 4' body: "Rock art of the type associated with hunter-gatherers is perhaps the most widely distributed rock art tradition in southern Africa, with numerous known examples in South Africa, Namibia and Zimbabwe, but also with examples found in Botswana and Mozambique. This tradition comprises paintings and engravings, with both techniques featuring images of animals and people. The type and composition varies from region to region. For example, rock art sites of the southern Drakensberg and Maloti mountains in South Africa and Lesotho contain a higher proportion of images of eland antelope, while those in Namibia in turn feature more giraffes. \ There are also regional variations in style and colour: in some sites and areas paintings are polychrome (multi-coloured) while in others they are not.\n\nDifferences also occur in composition between painting and engraving sites, with paintings more likely to feature multiple images on a single surface, often interacting with one another, while engraving sites more often include isolated images on individual rocks and boulders. However, there are commonalities in both imagery and style, with paintings throughout southern Africa often including depictions of people, particularly in procession and carrying items such as bows and arrows. \ Also heavily featured in both paintings and engravings are animals, in particular large ungulates which are often naturalistically depicted, sometimes in great detail. Additionally, images may include people and animals which appear to have the features of several species and are harder to identify. Some hunter-gatherer type paintings are described as ‘fine-line’ paintings because of the delicacy of their rendering with a thin brush. \n" - sys: id: 4NfdPoVtFKaM6K4w8I8ckg created_at: !ruby/object:DateTime 2016-09-13 13:22:13.102000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:12:40.860000000 Z content_type_id: image revision: 4 image: sys: id: 20oHYa0oEcSEMOyM8IcCcO created_at: !ruby/object:DateTime 2016-09-13 13:22:08.653000000 Z updated_at: !ruby/object:DateTime 2016-09-13 13:22:08.653000000 Z title: NAMBRT0010002 description: url: "//images.ctfassets.net/xt8ne4gbbocd/20oHYa0oEcSEMOyM8IcCcO/67a69f9814e8ec994003bfacff0962cc/NAMBRT0010002.jpg" caption: " Fine-line paintings of giraffes and line patterns, Brandberg, Namibia. \ It is thought that giraffes may have been associated with rain in local belief systems. 2013,2034.21324 © TARA/<NAME>" col_link: http://bit.ly/2j9778d - sys: id: 2nqpXdHTeoyKakEEOMUSA0 created_at: !ruby/object:DateTime 2016-09-13 13:03:40.877000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:13:26.231000000 Z content_type_id: chapter revision: 9 title_internal: 'Southern Africa: regional, chapter 5' body: "Hunter-gatherer rock paintings are found in particular concentrations in the Drakensberg-Maloti and Cape Fold Mountains in South Africa and Lesotho, the Brandberg and Erongo Mountains in Namibia and the Matobo Hills in Zimbabwe, while engraving sites are found throughout the interior, often near water courses. \n\nA different form of rock painting from the hunter-gatherer type, found mainly in the north-eastern portion of southern Africa is that of the ‘late whites’. \ Paintings in this tradition are so-called because they are usually associated with Bantu language-speaking Iron Age farming communities who entered the area from the north from around 2,000 years ago and many of these images are thought to have been painted later than some of the older hunter-gatherer paintings. ‘Late white’ paintings take many forms, but have generally been applied with a finger rather than a brush, and as the name suggests, are largely white in colour. These images represent animals, people and geometric shapes, often in quite schematic forms, in contrast to the generally more naturalistic depictions of the hunter-gatherer art. \n\nSometimes ‘late white’ art images relate to dateable events or depict objects and scenes which could only have taken place following European settlement, such as trains. Other forms of southern African rock art also depict European people and objects. These include images from the Western Cape in South Africa of a sailing ship, estimated to date from after the mid-17th century, as well as painted and engraved imagery from throughout South Africa showing people on horseback with firearms. Such images are sometimes termed ‘contact art’ as their subject matter demonstrates that they follow the period of first contact between European and indigenous people. \n" - sys: id: 1NrA6Z43fWIgwGoicy2Mw2 created_at: !ruby/object:DateTime 2016-09-13 13:03:57.014000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:13:43.550000000 Z content_type_id: image revision: 2 image: sys: id: 6QHTRqNGXmWic6K2cQU8EA created_at: !ruby/object:DateTime 2016-09-13 13:03:52.426000000 Z updated_at: !ruby/object:DateTime 2016-09-13 13:03:52.426000000 Z title: SOASWC0110006 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6QHTRqNGXmWic6K2cQU8EA/3d924964d904e34e6711c6224a7429e6/SOASWC0110006.jpg" caption: Painting of a ship from the south Western Cape in South Africa. 2013,2034.19495 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3730142&partId=1&searchText=2013%2c2034.19495&page=1 - sys: id: 4JVHOgrOyAAI8GWAuoyGY created_at: !ruby/object:DateTime 2016-09-13 13:24:14.217000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:17:20.511000000 Z content_type_id: chapter revision: 5 title_internal: 'Southern Africa: regional, chapter 6' body: "This kind of imagery is found in a variety of styles, and some of those producing ‘contact’ images in the Cape may have been people of Khoekhoen heritage. The Khoekhoen were traditionally cattle and sheep herders, culturally related to modern Nama people and more loosely to San&#124;Bushman hunter-gatherers. \ A distinct tradition of rock art has been suggested to be of ancestral Khoekhoen origin. This art is predominantly geometric in form, with a particular focus on circle and dotted motifs, and engravings in this style are often found near watercourses. \n" - sys: id: 3zUtkjM57Omyko6Q2O0YMG created_at: !ruby/object:DateTime 2016-09-13 13:04:05.564000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:17:47.538000000 Z content_type_id: chapter revision: 6 title: History of research title_internal: 'Southern Africa: regional, chapter 7' body: 'The first known reports of African rock art outside of the continent appear to come from the Bishop of Mozambique, who in 1721 reported sightings of paintings on rocks to the Royal Academy of History in Lisbon. Following this, reports, copies and publications of rock art from throughout modern South Africa were made with increasing frequency by officials and explorers. From the mid-19th century onwards, rock art from present-day Namibia, Zimbabwe and Botswana began to be documented, and during the first few decades of the twentieth century global public interest in the art was piqued by a series of illustrated publications. The hunter-gatherer rock art in particular had a strong aesthetic and academic appeal to western audiences, and reports, photographs and copied images attracted the attention of prominent figures in archaeology and ethnology such as Miles Burkitt, <NAME> and the Abbé Breuil, researchers whose interest in rock art worldwide let them to visit and write about southern African rock art sites. A further intensification of archaeological and anthropological research and recording in the 1950s-70s, resulted in new insights into the interpretations and attributions for southern African rock art. Rock art research continues throughout the area today. ' - sys: id: 5bPZwsgp3qOGkogYuCIQEs created_at: !ruby/object:DateTime 2016-09-13 13:04:30.652000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:18:07.313000000 Z content_type_id: image revision: 3 image: sys: id: 3BLPJ6SPMcccCE2qIG4eQG created_at: !ruby/object:DateTime 2016-09-13 13:04:26.508000000 Z updated_at: !ruby/object:DateTime 2016-09-13 13:04:26.508000000 Z title: BOTTSD0300015 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3BLPJ6SPMcccCE2qIG4eQG/639dd24028612b985042ea65536eef2e/BOTTSD0300015.jpg" caption: Rhinoceros and cattle painting, Tsodilo Hills, Botswana. 2013,2034.20848 © TARA/<NAME> col_link: http://bit.ly/2i5xfUJ - sys: id: 1QaeG3pF1KOEaooucoMUeE created_at: !ruby/object:DateTime 2016-09-13 13:04:37.305000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:18:34.546000000 Z content_type_id: chapter revision: 4 title: Interpretation title_internal: 'Southern Africa: regional, chapter 8' body: Rather than showing scenes from daily life, as was once assumed, it is now usually accepted that hunter-gatherer art in southern Africa shows images and motifs of spiritual and cultural importance. In particular, it is thought that some images reflect trance visions of San&#124;Bushman spiritual leaders, or shamans, during which they are considered to enter the world of spirits, where they are held to perform tasks for themselves and their communities, such as healing the sick or encouraging rain. This interpretation, which has been widely accepted, explains certain features of the art, for example the predominance of certain animals like eland antelope (due to their special cultural significance) and themes such as dot patterns and zigzag lines (interpreted as geometric patterns that shamans may see upon entering a trance state). - sys: id: 1YgT9SlSNeU8C6Cm62602E created_at: !ruby/object:DateTime 2016-09-13 13:04:53.447000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:19:08.779000000 Z content_type_id: image revision: 2 image: sys: id: 5Zk1QhSjEAOy8U6kK4yS4c created_at: !ruby/object:DateTime 2016-09-13 13:04:48.941000000 Z updated_at: !ruby/object:DateTime 2016-09-13 13:04:48.941000000 Z title: SOADRB0030002 description: url: "//images.ctfassets.net/xt8ne4gbbocd/5Zk1QhSjEAOy8U6kK4yS4c/5896c3d088678257f9acd01bd59c4b26/SOADRB0030002.jpg" caption: 'Painting of an eland and an ambiguous figure in the Drakensberg, South Africa. Both the eland and this kind of human-like figure are thought to have had symbolic associations with beliefs about gender and power. 2013,2034.18187© TARA/<NAME> ' col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3738250&partId=1&searchText=2013,2034.18187&page=1 - sys: id: 5byxQopdNCqEC2kCa0OqCm created_at: !ruby/object:DateTime 2016-09-13 13:05:00.899000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:19:37.565000000 Z content_type_id: chapter revision: 4 title_internal: 'Southern Africa: regional, chapter 9' body: "The rock art attributed to ancestral San&#124;Bushman hunter-gatherers has many varied motifs, some of which may also relate to specific themes such as initiation or rainmaking (indeed within its cultural context one image may have several significances). San&#124;Bushman informants in the 19th century told researchers that certain ambiguously shaped animals in the rock art repertoire represented animals related to water. Images such as these are known to researchers as 'rain animals' and it has been suggested that certain images could reflect—or prompt—the shaman's attempt to control rainfall. Some 'late white' art has also been proposed to have associations with rainmaking practices, and indeed the proximity of some geometric rock art images, proposed to be of possible Khoekhoen origin, to watercourses appears to emphasise the practical and spiritual significance of water among historical southern African communities. It has also been proposed that some forms of geometric art attributed to Khoekhoen people may be linked by tradition and motif to the schematic art traditions of central Africa, themselves attributed to hunter-gatherers and possibly made in connection with beliefs about water and fertility. Much in the “late white” corpus of paintings appears to be connected to initiation practices, part of a larger set of connected traditions extending north as far as Kenya. \n\nThe long time periods, cultural connections, and movements involved can make attribution difficult. For example, the idiosyncratic rock paintings of Tsodilo Hills in Botswana which appear to have similarities with the hunter-gatherer style include images of domesticates and may have been the work of herders. More localised traditions, such as that of engravings in north-western South Africa representing the homesteads of ancestral Nguni or Sotho-Tswana language speakers, or the focus on engravings of animal tracks found in Namibia, demonstrate more specific regional significances. Research continues and in recent decades, researchers, focusing on studying individual sites and sets of sites within the landscape and the local historical context, have discussed how their placement and subject matter may reflect the shifting balances of power, and changes in their communities over time. \n" - sys: id: L9AkWhM1WwUKWC4MQ4iMe created_at: !ruby/object:DateTime 2016-09-13 13:05:15.123000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:21:01.026000000 Z content_type_id: image revision: 5 image: sys: id: ETDpJFg6beKyyOmQGCsKI created_at: !ruby/object:DateTime 2016-09-13 13:05:11.473000000 Z updated_at: !ruby/object:DateTime 2016-09-13 13:05:11.473000000 Z title: NAMSNH0030006 description: url: "//images.ctfassets.net/xt8ne4gbbocd/ETDpJFg6beKyyOmQGCsKI/3dabb2ba8a3abaa559a6652eb10ea1eb/NAMSNH0030006.jpg" caption: 'Geometric rock engravings of the type suggested by some to be the work of Khoekhoen pastoralists and their ancestors. 2013,2034.22405 © TARA/David Coulson ' col_link: http://bit.ly/2iVIIoL - sys: id: ayvCEQLjk4uUk8oKikGYw created_at: !ruby/object:DateTime 2016-09-13 13:05:22.665000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:21:16.059000000 Z content_type_id: chapter revision: 6 title: Dating title_internal: 'Southern Africa: regional, chapter 10' body: "Although dating rock art is always difficult, the study of rock art sites from southern Africa has benefitted from archaeological study and excavations at rock art sites have sometimes revealed useful information for ascribing dates. \ Some of the oldest reliably dated examples of rock art in the world have been found in the region, with the most well-known examples probably being the painted plaques from Apollo 11 Cave in Namibia, dated to around 30,000 years ago. A portion of an engraved animal found in South Africa’s Northern Cape is estimated to be 10,200 years old and painted spalls from shelter walls in Zimbabwe have been dated to 12,000 years ago or older. However, it is thought that the majority of existing rock art was made more recently. As ever, subject matter is also helpful in ascribing maximum date ranges. We know, for example,that images of domestic animals are probably less than 2,000 years old. The condition of the art may also help to establish relative ages, particularly with regards to engravings, which may be in some cases be categorised by the discolouration of the patina that darkens them over time. \n\nThe multiplicity of rock art sites throughout southern Africa form a major component of southern Africa’s archaeological record, with many interesting clues about the lives of past inhabitants and, in some cases, continuing religious and cultural importance for contemporary communities. Many sites are open to the public, affording visitors the unique experience of viewing rock art in situ. Unfortunately, the exposed nature of rock art in the field leaves it open to potential damage from the environment and vandalism. Many major rock art sites in southern Africa are protected by law in their respective countries and the Maloti-Drakensberg Park in South Africa and Lesotho, Twyfelfontein/ǀUi-ǁAis in Namibia, Tsodilo Hills in Botswana and the Matobo Hills in Zimbabwe are all inscribed on the UNESCO World Heritage list. \n" - sys: id: 3Kjcm7V1dYoCuyaqKga0GM created_at: !ruby/object:DateTime 2016-09-13 13:05:38.418000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:25:17.372000000 Z content_type_id: image revision: 2 image: sys: id: 58V5qef3pmMGu2aUW4mSQU created_at: !ruby/object:DateTime 2016-09-13 13:05:34.865000000 Z updated_at: !ruby/object:DateTime 2016-09-13 13:05:34.865000000 Z title: NAMDME0080012 description: url: "//images.ctfassets.net/xt8ne4gbbocd/58V5qef3pmMGu2aUW4mSQU/dec59cd8209d3d04b13447e9c985574a/NAMDME0080012.jpg" caption: Engraved human footprints, Erongo Region, Namibia. 2013,2034.20457 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3729958&partId=1&searchText=2013,2034.20457+&page=1 - sys: id: 1kwt8c4P0gSkYOq8CO0ucq created_at: !ruby/object:DateTime 2016-09-13 13:28:16.189000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:25:44.294000000 Z content_type_id: chapter revision: 2 title_internal: 'Southern Africa: regional, chapter 11' body: "¹ San&#124;Bushmen is a collective term used to describe the many different hunter-gatherer-fisher groups living in southern Africa who have related languages and cultural traditions. Both 'San' and 'Bushmen' are considered offensive terms by some members of these groups, although others have positively adopted them." citations: - sys: id: 6GlTdq2WbeIQ6UoeOeUM84 created_at: !ruby/object:DateTime 2016-10-17 10:45:36.418000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:39:37.963000000 Z content_type_id: citation revision: 2 citation_line: |+ <NAME>., <NAME>. and <NAME>. 2010. Tsodilo Hills: Copper Bracelet of the Kalahari. East Lansing: Michigan State University Press. <NAME>. 1995. The Hunter's Vision: The Prehistoric Art of Zimbabwe. London: British Museum Press. <NAME>. 1981. Believing and Seeing: Symbolic Meanings in San&#124;BushmanRock Paintings. Johannesburg: University of Witwatersrand Press <NAME>. 1995. 'Neglected Rock Art: The Rock Engravings of Agriculturist Communities in South Africa'. South African Archaeological Bulletin. Vol. 50 No. 162. pp. 132.142. <NAME>. 1989. Rock Paintings of the Upper Brandberg. vols. I-VI. Köln: Heinrich-Barth-Institut <NAME>. & <NAME>. 2008. 'Beyond Development - Global Visions and Local Adaptations of a Contested Concept' in Limpricht, C., & M. Biesele (eds) Heritage and Cultures in modern Namibia: in-depth views of the country: a TUCSIN Festschrift. Goettingen : Klaus Hess Publishers. pp 37:46. <NAME>. 2013. 'Rock Art Research in Africa' in Mitchell, P. and P. Lane (eds), The Oxford Handbook of African Archaeology. Oxford, Oxford University Press. <NAME>. & <NAME>. 2004. 'Taking Stock: Identifying Khoekhoen Herder Rock Art in Southern Africa'. Current Anthropology Vol. 45, No. 4. pp 499-52. background_images: - sys: id: 6oQGgfcXZYWGaeaiyS44oO created_at: !ruby/object:DateTime 2016-09-13 13:05:47.458000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:41:12.556000000 Z title: ZIMMSL0120015.tiff description: url: "//images.ctfassets.net/xt8ne4gbbocd/6oQGgfcXZYWGaeaiyS44oO/c8bc0d9d1ceee0d23517a1bc68276b24/ZIMMSL0120015.tiff.jpg" - sys: id: 69ouDCLqDKo4EQWa6QCECi created_at: !ruby/object:DateTime 2016-09-13 13:05:55.993000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:41:44.910000000 Z title: SOAEFS0030008 description: url: "//images.ctfassets.net/xt8ne4gbbocd/69ouDCLqDKo4EQWa6QCECi/9c5da3bf755188e90003a9bc55550f6f/SOAEFS0030008.jpg" ---<file_sep>/_coll_country_information/sudan-country-introduction.md --- contentful: sys: id: 4fITEJHibm4iy8ykmE2s0G created_at: !ruby/object:DateTime 2015-11-26 12:22:39.465000000 Z updated_at: !ruby/object:DateTime 2015-12-07 13:42:14.925000000 Z content_type_id: country_information revision: 2 title: 'Sudan: country introduction' chapters: - sys: id: 1sqHdOmWbeyY42OCS0Sc4u created_at: !ruby/object:DateTime 2015-11-26 12:18:28.564000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:18:28.564000000 Z content_type_id: chapter revision: 1 title: Introduction title_internal: 'Sudan: country, chapter 1' body: 'Sudan''s known rock art mainly consists of paintings and engravings on exposed rock surfaces and rock shelters, largely of animals, human figures and ancient river boats. Most of the published rock art is found in disparate geographical areas in the northern section of the country: around the Nile valley and close to the country''s north-western and north-eastern borders. Images include wild fauna such as antelope, domestic animals like camels, and depictions of boats, which along with inscriptions and religious imagery can attempt to date these images.' - sys: id: 1993CZTJXsyeWaOscywWs4 created_at: !ruby/object:DateTime 2015-11-26 12:14:29.575000000 Z updated_at: !ruby/object:DateTime 2017-01-09 17:12:37.390000000 Z content_type_id: image revision: 2 image: sys: id: 4rPFCqitX2sUOAGUEAqui4 created_at: !ruby/object:DateTime 2015-11-26 12:13:55.093000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:13:55.093000000 Z title: '2013,2034.225' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4rPFCqitX2sUOAGUEAqui4/d0abf71d8e72774026c082d7ae16d71c/2013_2034.225.jpg" caption: Painted cattle. <NAME>, J<NAME>inat, Sudan. 2013,2034.225 © TARA/David Coulson col_link: http://bit.ly/2iwfHwV - sys: id: 2qQoPRbg6Q0aMQsc2WWicu created_at: !ruby/object:DateTime 2015-11-26 12:18:56.395000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:18:56.395000000 Z content_type_id: chapter revision: 1 title: Geography title_internal: 'Sudan: country, chapter 2' body: Sudan covers nearly 2,000,000 km² and is geographically diverse, dominated in the north by the desert of the southern Sahara and divided by the River Nile, which flows north from the capital city of Khartoum at the confluence of the Blue and White Niles and is joined by the Atbara River in the east. East of the Nile is the arid Nubian Desert, which is part of the larger Sahara, flanked at the north east by the Red Sea Hills and at the south by clay plains. To the south and west of the country are semi-arid zones with seasonal watercourses, with the west dominated by the Jebel Marrah volcanic massif, and the Nuba mountain range near the southern border. - sys: id: 4pTDZNCHuo8Wi22GSsSSMK created_at: !ruby/object:DateTime 2015-11-26 12:19:26.835000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:19:26.835000000 Z content_type_id: chapter revision: 1 title: Research history title_internal: 'Sudan: country, chapter 3' body: Historically, rock art research in Sudan has either been incorporated into larger investigations of the area’s rich archaeological history, or, as in the Nubian Nile valley, the result of archaeological salvage projects, aimed at documenting and conserving archaeological sites and artefacts in advance of engineered flooding events, such as the construction of the Aswan High dam in the 1960s and the Merowe dam in the early 2000s. This has resulted in significant rock art and rock gong discoveries, such as that noted near the Second Cataract (Žába, 1967) and more recently around the Fourth. Rock art remains vulnerable to damming initiatives – that at Sabu is currently under threat by the Kajbar Dam proposal at the Third Cataract. There is great scope for further research. - sys: id: 4O1OTdhzb2UIQYeuuickg6 created_at: !ruby/object:DateTime 2015-11-26 12:19:49.980000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:20:08.533000000 Z content_type_id: chapter revision: 2 title: Rock art types title_internal: 'Sudan: country, chapter 4' body: |- The rock art of Sudan is varied across both time periods and geographical regions. Numerous pecked depictions of domestic cattle can be found in the Red Sea Hills (Pluskota, 2006) as well as depictions of both domestic and wild animals closer to the River Nile, such as those found at Jebel Gorgod in a mountainous area near Sesebi (Schiff Giorgini, 1972). Engravings, like those around the Second, Third, and Fourth Cataracts (areas of rocky rapids) are varied in subject matter and in date, ranging from Neolithic engravings of wild and domestic fauna to those with Medieval Christian imagery, for example around the Dal Cataract (Mills, 1965). These are mixed with others from about 4,000 BC onwards which may be contemporary with the Predynastic cultures and Pharaonic periods of ancient Egypt and in northern Sudan, Nubian Kerma culture (known to the ancient Egyptians as the Kingdom of Kush). These include depictions of Nile river boats and later hieroglyphic inscriptions. The peripatetic nature of these traceable signatures highlights the need to look beyond modern boundaries when considering ancient rock art traditions of Africa. For millennia prior to the creation of the current Egypt/Sudan border, the highway of the river allowed movement between Egypt and Nubia, the people of the region leaving their marks on a narrow area of fertile land that fostered riverine animals like crocodiles, which are occasionally depicted in the rock engravings. From the 4th millennium BC, following several temperate millennia, savannah animals like giraffe lost their habitat in the increasingly arid environments to east and west, but remain reflected in the rock engravings of what is now desert. The range in styles and dates for Sudanese rock art emphasises its nature, not as a particular artistic style, but as personal and cultural manipulations of a specific medium. A number of stone percussive instruments known as rock gongs, which produce a sonorous tone when struck and are often apparently associated with cattle engravings, have stimulated discussion about the uses of rock art sites as multisensory ritual venues. - sys: id: 4T61G6jdTqmkMKWiEmIcEe created_at: !ruby/object:DateTime 2015-11-26 12:15:01.481000000 Z updated_at: !ruby/object:DateTime 2017-01-09 17:13:14.413000000 Z content_type_id: image revision: 2 image: sys: id: AMf0wybjzMekgCuSAs28E created_at: !ruby/object:DateTime 2015-11-26 12:13:51.741000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:06:06.627000000 Z title: '2013,2034.272' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3586260&partId=1&searchText=2013,2034.272&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/AMf0wybjzMekgCuSAs28E/2afa178fb645276aa051e8dc597f1b1e/2013_2034.272.jpg" caption: Engraved cattle, giraffe and ostrich. <NAME>, Jebel Uweinat. 2013,2034.272 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3586260&partId=1 - sys: id: 1KCSPDy6Dyqm2g6OkEeGMy created_at: !ruby/object:DateTime 2015-11-26 12:20:29.697000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:20:29.697000000 Z content_type_id: chapter revision: 1 title: Chronology title_internal: 'Sudan: country, chapter 5' body: The understanding of much of Sudanese prehistory as it relates to rock art remains subject to debate. Some of the best-preserved and most varied rock art of Sudan’s desert regions is situated only metres from the Egyptian border in the far north-west corner of the country, in a valley of Jebel Uweinat – the enormous sandstone and granite outcrop which serves as a boundary between Egypt, Sudan and Libya. Numerous paintings and engravings are found here, including images of wild animals, such as giraffe and antelope, humans, dogs and many cattle. Some of these paintings have been compared with other styles of rock art in the wider Sahara, including the later Pastoral Period (Muzzolini, 1995). Others have proposed that a different set of paintings in these sites may be older, with a stylistic link (although fragile) with the Round Head Period (Van Noten,1978). However, the scholarly community recognises the inherent difficulty of formulating conclusions of direct links with wider rock art practices. In areas around the Nile, where there are similar animal engravings, rock art is also from a wide range of time periods. - sys: id: 5E1CsZXmy4g0484oGIG2W6 created_at: !ruby/object:DateTime 2015-11-26 12:15:30.625000000 Z updated_at: !ruby/object:DateTime 2017-01-09 17:13:29.546000000 Z content_type_id: image revision: 2 image: sys: id: 4pB2o28EnCOk6w8m8IwciG created_at: !ruby/object:DateTime 2015-11-26 12:13:51.703000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:06:43.357000000 Z title: '2013,2034.347' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3586942&partId=1&searchText=2013,2034.347&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/4pB2o28EnCOk6w8m8IwciG/5ce1e4a59f58a180045818bdc3bc8c13/2013_2034.347.jpg" caption: Engraved ostriches, dogs and antelope. <NAME>, Jebel Uweinat. 2013,2034.347 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3586942&partId=1 - sys: id: 3xX43VnxhuGoG0KKMca2iG created_at: !ruby/object:DateTime 2015-11-26 12:20:54.588000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:20:54.588000000 Z content_type_id: chapter revision: 1 title: title_internal: 'Sudan: country, chapter 6' body: 'Ascribing dates to rock art like that at Jebel Uweinat is also uncertain and is more difficult than dating images such as the depictions of Nile river boats or later Christian cross engravings like those found near the Third Cataract, where similar motifs are replicated on contemporary pottery and corroborated elsewhere in the archaeological record. Occasionally rock art may be found in a dateable stratigraphic context- a giraffe engraving at Gala Abu Ahmed in Wadi Howar, an ancient Nile tributary, was recently dated to before 1,200-1,300 BC in this way (Jesse, 2005). In general, other clues are necessary, for example known domestication dates: wild animal images are often superseded with depictions of animals like horses and camels. These were only widely known in northeast Africa from the second and first millennia BC respectively and are therefore unlikely to be older. However, this is not an exact science: examination of the superimpositions and levels of patination on some Nile valley cattle engravings show that they were made over thousands of years up to the not too distant past. Faced with such challenges, classifying rock art by design style, while problematic, can prove useful in envisioning chronology.' - sys: id: 26BMChmzneksWYm4uQeK6u created_at: !ruby/object:DateTime 2015-11-26 12:16:01.977000000 Z updated_at: !ruby/object:DateTime 2017-01-09 17:13:48.660000000 Z content_type_id: image revision: 2 image: sys: id: 2JHzf9XFUACqyq0AAaw8CQ created_at: !ruby/object:DateTime 2015-11-26 12:13:51.755000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:07:20.356000000 Z title: '2013,2034.334' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3586833&partId=1&searchText=2013,2034.334&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/2JHzf9XFUACqyq0AAaw8CQ/1070836ffd26fec60872b6b97fb72ff5/2013_2034.334.jpg" caption: Engraved camels and human figures. <NAME>, Jebel Uweinat. 2013,2034.334 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3586833&partId=1 citations: - sys: id: 6LV3FmRkCkCOm8UgKQ2e26 created_at: !ruby/object:DateTime 2015-11-26 12:17:53.755000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:17:53.755000000 Z content_type_id: citation revision: 1 citation_line: |- <NAME>. 2005. *Rock Art in Lower Wadi Howar, northwest Sudan*. Sahara vol.16, pp. 27-38 <NAME>. 1965. *The Reconnaissance Survey from Gemai to Dal: A Preliminary Report for 1963- 1964*. Kush 13, pp. 1-12 <NAME>. 1995. *Les images rupestres du Sahara*. — Toulouse (author’s ed.), p. 447 <NAME>. 2006. *Kirwan Memorial Lecture: Bir Nurayet- the Rock Art Gallery of the Red Sea Hills*. Sudan & Nubia, Bulletin No. 10, pp. 2-7 <NAME>. 1972. *SOLEB, II: Les Nécropoles*. — Firenze: Sansoni Van Noten, F. 1978. *The Rock Paintings of Jebel Uweinat*. — Graz, Akademischeverlag <NAME>. 1967. *The Third Czechoslovak Expedition to Nubia in the Frame of the Safeguarding of the Nubian Monuments Project: Preliminary Report*. Fouilles en Nubie (1961-1963). Le Caire: Organisme general des impr. Gouvernementales, pp. 217-224 For further information about archaeology in Sudan, visit [sudarchs.org.uk](http://www.sudarchrs.org.uk/) ---<file_sep>/_coll_country/egypt/cave-of-swimmers.md --- breadcrumbs: - label: Countries url: "../../" - label: Egypt url: "../" layout: featured_site contentful: sys: id: 4af0chnVYAe0e4mqoQwaoy created_at: !ruby/object:DateTime 2015-11-25 15:07:32.113000000 Z updated_at: !ruby/object:DateTime 2015-12-07 20:53:48.674000000 Z content_type_id: featured_site revision: 3 title: Cave of Swimmers, Egypt slug: cave-of-swimmers chapters: - sys: id: 4pHoZkgWDegMQsumuSUekM created_at: !ruby/object:DateTime 2015-11-25 15:04:41.300000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:04:41.300000000 Z content_type_id: chapter revision: 1 title_internal: 'Egypt: featured site, chapter 1' body: The ‘Cave of Swimmers’ is one of the most famous rock art sites of the Sahara. It sits in Wadi Sura, loosely translated as the ‘Valley of Pictures’ due to the prevalence of rock art in the region. - sys: id: 1cUANarsnIIyGQ8MUGaKMM created_at: !ruby/object:DateTime 2015-11-25 15:01:11.701000000 Z updated_at: !ruby/object:DateTime 2017-01-09 15:35:42.682000000 Z content_type_id: image revision: 2 image: sys: id: 5LebP1Vcqs4A4US00uI0Q4 created_at: !ruby/object:DateTime 2015-11-25 15:00:35.480000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:00:35.480000000 Z title: '2013,2034.186' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5LebP1Vcqs4A4US00uI0Q4/56ba762bb737baf4545dc62a6a745bb3/2013_2034.186.jpg" caption: A view of the entrance to the ‘Cave of Swimmers’. On a promontory at the entrance to an inlet in Wadi Sura, Gilf Kebir, Egypt. 2013,2034.186 © <NAME> / TARA col_link: http://bit.ly/2iV11IU - sys: id: 5AJki82zIcK2AEyigEiu2g created_at: !ruby/object:DateTime 2015-11-25 15:05:05.937000000 Z updated_at: !ruby/object:DateTime 2017-01-09 15:44:27.933000000 Z content_type_id: chapter revision: 2 title_internal: 'Egypt: featured site, chapter 2' body: The ‘Cave of Swimmers’ is the larger of two shallow caves situated side by side in the southern part of the Gilf Kebir plateau in Egypt’s Western Desert, an area so remote and inaccessible that its existence only became known to European cartographers in 1926. It is so named due to the human figures painted on its walls with their limbs contorted as if swimming. It has since become world-renowned, particularly as a key location in the feature film *The English Patient* (1996), based on Michael Ondaatje’s novel of the same name. - sys: id: 1imxvhdhHEYsyKueK6coS created_at: !ruby/object:DateTime 2015-11-25 15:01:51.007000000 Z updated_at: !ruby/object:DateTime 2017-01-09 16:35:41.280000000 Z content_type_id: image revision: 2 image: sys: id: 2halaUUgAMe6ES0uycIIIG created_at: !ruby/object:DateTime 2015-11-25 15:00:35.469000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:00:35.469000000 Z title: '2013,2034.188' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2halaUUgAMe6ES0uycIIIG/ec1812c9c376a941c691641c471b7105/2013_2034.188.jpg" caption: View out of the cave mouth. 2013,2034.188 © <NAME> / TARA col_link: http://bit.ly/2iVbiVc - sys: id: 2iFZCE50AsqKM4C8ma0IO8 created_at: !ruby/object:DateTime 2015-11-25 15:05:27.680000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:05:27.680000000 Z content_type_id: chapter revision: 1 title_internal: 'Egypt: featured site, chapter 3' body: The book and film feature fictionalised versions of the cave and its real-life discoverer, <NAME>, as the title character. In reality, Almásy was a charismatic figure in pre-war Saharan exploration. He argued that the ‘swimming’ figures suggested the prior existence of abundant water in the area and was therefore evidence that it had not always been arid desert, a radical new theory at the time that has since been confirmed, although not on the basis of these paintings as evidence. Rock art is notoriously difficult to date as it was a tradition practiced for thousands of years. These paintings have been dated at between 9,000 and 6,000 years ago, although some researchers have suggested both earlier and later dates. - sys: id: 6tD8WMYexGWoiEYeEKAaIw created_at: !ruby/object:DateTime 2015-11-25 15:02:56.246000000 Z updated_at: !ruby/object:DateTime 2017-01-09 16:36:48.650000000 Z content_type_id: image revision: 2 image: sys: id: 3R3Ri8y5pe2I4AM8iauayW created_at: !ruby/object:DateTime 2015-11-25 15:00:35.477000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:28:16.164000000 Z title: '2013,2034.190' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3577611&partId=1&searchText=2013,2034.190&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/3R3Ri8y5pe2I4AM8iauayW/5e53609e755eba8130847a5017e32268/2013_2034.190.jpg" caption: The main painted panel on the cave wall, showing the famous ‘swimming’ figures (bottom centre and top right). 2013,2034.190 © <NAME> / TARA col_link: http://bit.ly/2j0fxBy - sys: id: 5VeXJi6wN2Cq00COCo08Sk created_at: !ruby/object:DateTime 2015-11-25 15:05:49.205000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:05:49.205000000 Z content_type_id: chapter revision: 1 title_internal: 'Egypt: featured site, chapter 4' body: 'New rock art discoveries in this area have been made in recent years and add to the debate, which has continued, as have expeditions by academics, tourists and others. These visitors have sometimes left their own marks on the rock faces in the form of graffiti, and in the surrounding sand, where the tracks from previous parties (including Almásy’s) lie undisturbed, adding to the sense of history: not only of those who produced the paintings, but also of the site itself. Meanwhile the condition of the paintings, prone to flaking, continues to deteriorate, further obscuring this tantalising glimpse into the past.' - sys: id: QzRyY82AYSMgMGCUcws2m created_at: !ruby/object:DateTime 2015-11-25 15:03:54.190000000 Z updated_at: !ruby/object:DateTime 2017-01-09 16:37:39.120000000 Z content_type_id: image revision: 2 image: sys: id: 6Fqf4hcw1OeG2IIO442ckW created_at: !ruby/object:DateTime 2015-11-25 15:00:35.492000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:00:35.492000000 Z title: '2013,2034.192' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6Fqf4hcw1OeG2IIO442ckW/6d975af11e82e634f913ca9aed815e44/2013_2034.192.jpg" caption: Two ‘negative’ hand prints from the left side of the main panel, blown in different pigments. Three crouched figures are painted across the lower handprint. 2013,2034.192 © <NAME> / TARA col_link: http://bit.ly/2iaUQ4J - sys: id: 23YZHecGleqeiKYiAQQcq0 created_at: !ruby/object:DateTime 2015-11-25 15:06:06.304000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:06:06.304000000 Z content_type_id: chapter revision: 1 title_internal: 'Egypt: featured site, chapter 5' body: 'The ‘swimmers’ are not the only humans depicted here: there are others, some heavily adorned, some apparently engaged in activities. A meticulously engraved antelope’s hoofprint adds another element to this fascinating site. Perhaps most striking are the numerous ‘negative’ handprints, produced by the artist blowing pigment onto the rock face over splayed fingers. As with so much rock art, they leave an imprint as immediate and familiar as it is elusive and enigmatic.' background_images: - sys: id: 2halaUUgAMe6ES0uycIIIG created_at: !ruby/object:DateTime 2015-11-25 15:00:35.469000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:00:35.469000000 Z title: '2013,2034.188' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2halaUUgAMe6ES0uycIIIG/ec1812c9c376a941c691641c471b7105/2013_2034.188.jpg" - sys: id: 6Fqf4hcw1OeG2IIO442ckW created_at: !ruby/object:DateTime 2015-11-25 15:00:35.492000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:00:35.492000000 Z title: '2013,2034.192' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6Fqf4hcw1OeG2IIO442ckW/6d975af11e82e634f913ca9aed815e44/2013_2034.192.jpg" ---<file_sep>/_coll_thematic/rockartvr.md --- contentful: sys: id: 2fRpwDPsrmiQaUQMqSI8oA created_at: !ruby/object:DateTime 2017-03-13 02:40:28.121000000 Z updated_at: !ruby/object:DateTime 2017-03-13 02:40:28.121000000 Z content_type_id: thematic revision: 1 title: Rock Art VR - Game Pass Shelter Mobile App slug: rockartvr lead_image: sys: id: 2Sqy60hy3YSo4sQE2Ame6m created_at: !ruby/object:DateTime 2017-03-12 22:34:27.617000000 Z updated_at: !ruby/object:DateTime 2017-03-12 22:34:27.617000000 Z title: Screen Shot 2016-12-12 at 3.34.33 PM description: url: "//images.ctfassets.net/xt8ne4gbbocd/2Sqy60hy3YSo4sQE2Ame6m/b58f2bdd6c004b4111987aba5c2bd362/Screen_Shot_2016-12-12_at_3.34.33_PM.png" chapters: - sys: id: 6nHJUYFyucgyyMKs6iYwwo created_at: !ruby/object:DateTime 2017-03-13 02:11:18.812000000 Z updated_at: !ruby/object:DateTime 2017-03-27 14:35:10.794000000 Z content_type_id: image revision: 2 image: sys: id: 3uawILzjCMg28ISmOO2Eyk created_at: !ruby/object:DateTime 2017-03-13 02:10:04.401000000 Z updated_at: !ruby/object:DateTime 2017-03-13 02:13:43.629000000 Z title: BM RockArt Title Screen description: BM RockArt Title Screen url: "//images.ctfassets.net/xt8ne4gbbocd/3uawILzjCMg28ISmOO2Eyk/6bc41794e439f8cdf8effeb37301dc85/BM_RockArt_Title_Screen.jpg" caption: BM RockArt Title Screen - sys: id: 2oGC8YIQnmIaewkKes6EqI created_at: !ruby/object:DateTime 2017-03-13 02:15:13.768000000 Z updated_at: !ruby/object:DateTime 2017-03-13 02:40:23.061000000 Z content_type_id: chapter revision: 2 title_internal: 'Thematic: rockartvr, chapter 1' body: "Come and explore a rock art site in South Africa! Using digital imagery from the African Rock Art Image Project at the British Museum, this interactive mobile app uses VR technology optimized for Cardboard headsets ([https://vr.google.com/cardboard/](https://vr.google.com/cardboard/)) to allow you to explore the famous rock art site of Game Pass Shelter in South Africa via an immersive 360° tour with embedded 3D models. \n\n<iframe width=\"560\" height=\"315\" src=\"https://www.youtube.com/embed/epYu2ONt7cA\" frameborder=\"0\" allowfullscreen></iframe>" - sys: id: 5rjsmkdjUcSEOWIYKuuCIi created_at: !ruby/object:DateTime 2017-03-13 02:17:09.190000000 Z updated_at: !ruby/object:DateTime 2017-03-13 02:17:09.190000000 Z content_type_id: image revision: 1 image: sys: id: 45vNSBVEZqgGyOcIAAsOw4 created_at: !ruby/object:DateTime 2017-03-13 02:16:21.372000000 Z updated_at: !ruby/object:DateTime 2017-03-13 02:16:29.085000000 Z title: Screen Shot1 description: Fig. 1. Sample view of the Game Pass Shelter in the app via the Cardboard headset. url: "//images.ctfassets.net/xt8ne4gbbocd/45vNSBVEZqgGyOcIAAsOw4/d15aa91a686ea13808e9dd699dc6ccb6/Screen_Shot1a.png" caption: Fig. 1 - Sample view of the Game Pass Shelter in the app via the Cardboard headset. - sys: id: 4iG66vQ2MUu24GywiUEOYG created_at: !ruby/object:DateTime 2017-03-13 02:17:54.604000000 Z updated_at: !ruby/object:DateTime 2017-03-13 02:17:54.604000000 Z content_type_id: chapter revision: 1 title_internal: 'Thematic: rockartvr, chapter 2' body: This app will take you to Game Pass Shelter, one of the most well-known rock art sites in South Africa. Situated in the Drakensberg mountains, the shelter is a sandstone recess atop a steep slope exhibiting vibrant rock paintings of people and animals. The interactive experience is a 360° tour and panoramic view of Game Pass, creating the backdrop of the context of the valley from the photography available, with interactive ‘hotspots’ with embedded 3D models and additional information from the Rock Art archive. - sys: id: 2XMhIpm5TW4mUySacSUggg created_at: !ruby/object:DateTime 2017-03-13 02:19:05.899000000 Z updated_at: !ruby/object:DateTime 2017-03-13 02:19:05.899000000 Z content_type_id: image revision: 1 image: sys: id: 6Z7Fmlzd0kSYk2qU2S0eoo created_at: !ruby/object:DateTime 2017-03-13 02:18:53.908000000 Z updated_at: !ruby/object:DateTime 2017-03-13 02:18:53.908000000 Z title: Screen Shot2 description: Panoramic views looking out from Game Pass Shelter in the app. url: "//images.ctfassets.net/xt8ne4gbbocd/6Z7Fmlzd0kSYk2qU2S0eoo/521141319e9f7a15483d263998245658/Screen_Shot2.png" caption: Fig. 2 - Panoramic views looking out from Game Pass Shelter in the app. - sys: id: 4f4xPt1kfeakUO4AE42yeg created_at: !ruby/object:DateTime 2017-03-13 02:20:07.762000000 Z updated_at: !ruby/object:DateTime 2017-03-13 02:20:07.762000000 Z content_type_id: chapter revision: 1 title_internal: 'Thematic: rockartvr, chapter 3' body: This app uses images from the African Rock Art Image Project, the largest archive of digitised images (also known as ‘born digital’ artifacts) recording rock art sites across Africa. Over 25,000 digital photographs of rock art from across Africa have been catalogued – originally from the Trust for African Rock Art (TARA) – through generous support from the Arcadia Fund. The central remit of the project is to ensure global open access to the TARA archive by developing new and innovative ways of engaging with the archive. - sys: id: CV5a7U4DReuiC0e2yeUai created_at: !ruby/object:DateTime 2017-03-13 02:23:08.612000000 Z updated_at: !ruby/object:DateTime 2017-03-13 02:23:08.612000000 Z content_type_id: image revision: 1 image: sys: id: 3fD4DQqyTS2UgwoyeqEYkc created_at: !ruby/object:DateTime 2017-03-13 02:22:56.001000000 Z updated_at: !ruby/object:DateTime 2017-03-13 02:22:56.001000000 Z title: GamePass2 description: Examples of image showing Game Pass Shelter in the African Rock Art Image Project archives. url: "//images.ctfassets.net/xt8ne4gbbocd/3fD4DQqyTS2UgwoyeqEYkc/846c00a66240973feacc7f3449481a1a/GamePass2.jpg" caption: Fig. 3 - Examples of image showing Game Pass Shelter in the African Rock Art Image Project archives. - sys: id: 4Nw0ySbeZiIEuaimaYIowM created_at: !ruby/object:DateTime 2017-03-13 02:25:15.926000000 Z updated_at: !ruby/object:DateTime 2017-03-13 02:25:15.926000000 Z content_type_id: chapter revision: 1 title_internal: 'Thematic: rockartvr, chapter 4' body: |- Using innovative digital technology and photogrammetry in combination with our extensive archival photographic collections, we started experimenting with making [3D models](https://sketchfab.com/britishmuseum/collections/african-rock-art) of rock art solely using 20-year-old digitised, archival photographs of the rock art sites. Building on this work, we realised it would be possible to use these techniques to further contextualize rock art sites in their landscape environment, combining archival images and records with satellite imagery and 360° images of a site -- a technique which proves hugely important for possible reconstructions of heritage sites largely using historical photos! Working closely in collaboration with the African Conservation Trust (ACT) ([http://www.projectafrica.com/](http://www.projectafrica.com/)), our colleagues in South Africa, and Soluis ([http://www.soluis.com/heritage/](http://www.soluis.com/heritage/)), our technology partner, we were able to develop the Rock Art VR mobile app by combining our archival photography with additional 360° imagery and mapping of the site of Game Pass Shelter provided by ACT. Rather than simply using modern 3D scanning and regular VR methods, Soluis developed innovative solutions in order to combine the archival imagery, 360° photos, and satellite videos to create an immersive VR tour of Game Pass Shelter that would be still be accessible on widely-available smartphone technology and simple cardboard headsets. By using widely-available mobile technology, it will be possible for ACT and our other project partners in Africa to easily use the app for education and outreach purposes, in particular at rock art centres (Kamberg, Didima, and KZM museum) in South Africa where local custodians teach school children about rock art and its importance. - sys: id: 5i0X5VKYQEuYgCCUEUGsQm created_at: !ruby/object:DateTime 2017-03-13 02:26:10.014000000 Z updated_at: !ruby/object:DateTime 2017-03-13 02:26:20.136000000 Z content_type_id: image revision: 2 image: sys: id: 6hYygcn6LKye0KQu4WE2Qi created_at: !ruby/object:DateTime 2017-03-13 02:25:58.576000000 Z updated_at: !ruby/object:DateTime 2017-03-13 02:25:58.576000000 Z title: Site%20map description: Mapping the key features of Game Pass Shelter, as part of the creation of the Rock Art VR app. url: "//images.ctfassets.net/xt8ne4gbbocd/6hYygcn6LKye0KQu4WE2Qi/d29bf98b8aa3c1330957b38d96ffaf9f/Site_20map.jpg" caption: Fig. 4 - Mapping the key features of Game Pass Shelter, as part of the creation of the Rock Art VR app. - sys: id: 6GhOyZzkrYAuG8agOSeA08 created_at: !ruby/object:DateTime 2017-03-13 02:26:58.085000000 Z updated_at: !ruby/object:DateTime 2017-03-13 02:26:58.085000000 Z content_type_id: chapter revision: 1 title_internal: 'Thematic: rockartvr, chapter 5' body: 'The app begins (after the title page and instructions for using the cardboard viewer) with an automated opening sequence showing the location of Game Pass Shelter in the Drakensberg National Park in South Africa from a satellite view of the park down to the site itself, with audio narration describing the history of the site (see user experience diagram below). ' - sys: id: 3O7wEtT9WgIIy6AWGw4guE created_at: !ruby/object:DateTime 2017-03-13 02:27:44.722000000 Z updated_at: !ruby/object:DateTime 2017-03-13 02:27:44.722000000 Z content_type_id: image revision: 1 image: sys: id: 4MLN0mgROgUe4e444yUUQE created_at: !ruby/object:DateTime 2017-03-13 02:27:34.108000000 Z updated_at: !ruby/object:DateTime 2017-03-13 02:27:34.108000000 Z title: App UserFlow description: User experience diagram for the Rock Art VR app. url: "//images.ctfassets.net/xt8ne4gbbocd/4MLN0mgROgUe4e444yUUQE/6d08fb56fb7f4f5111ab87bf7b63fb5e/App_UserFlow.png" caption: Fig. 5 - User experience diagram for the Rock Art VR app. - sys: id: 1cN6S7SmRywQYmGwKGsaw2 created_at: !ruby/object:DateTime 2017-03-13 02:28:22.643000000 Z updated_at: !ruby/object:DateTime 2017-03-13 02:28:22.643000000 Z content_type_id: chapter revision: 1 title_internal: 'Thematic: rockartvr, chapter 6' body: The interactive portion of the app then begins, with users following a path up the hillside to Game Pass Shelter, experiencing six places en route with 360° panoramic views (see example below). - sys: id: 75vDJziuic2I02EQKym8Gm created_at: !ruby/object:DateTime 2017-03-13 02:29:27.383000000 Z updated_at: !ruby/object:DateTime 2017-03-13 02:29:27.383000000 Z content_type_id: image revision: 1 image: sys: id: a2qVgKlOU0IgeU8CGkooi created_at: !ruby/object:DateTime 2017-03-13 02:29:15.605000000 Z updated_at: !ruby/object:DateTime 2017-03-13 02:29:15.605000000 Z title: ScreenShot3 description: Further example of the panoramic views user experience in the app via Cardboard headsets. url: "//images.ctfassets.net/xt8ne4gbbocd/a2qVgKlOU0IgeU8CGkooi/e503c9cc97a20f4f91746d82a57a5b8d/ScreenShot3.jpg" caption: Fig. 6 - Further example of the panoramic views user experience in the app via Cardboard headsets. - sys: id: 7EhyKmW3NSKGeYksYOMGs created_at: !ruby/object:DateTime 2017-03-13 02:30:08.600000000 Z updated_at: !ruby/object:DateTime 2017-03-13 02:30:08.600000000 Z content_type_id: chapter revision: 1 title_internal: 'Thematic: rockartvr, chapter 7' body: This interactive tour is self-led and culminates with the user discovering two key rock art panels at the shelter site. When the user clicks on the highlighted rock panels, the user is presented with the option to view each in detail via 3D models whose key features are highlighted and described by connected audio narration. After visiting the rock art panels, the user can revisit any part of the tour or choose to leave via the exit screen and credits. - sys: id: 3KTPOINSlW6I0O6iEysQW created_at: !ruby/object:DateTime 2017-03-13 02:32:53.962000000 Z updated_at: !ruby/object:DateTime 2017-03-13 02:32:53.962000000 Z content_type_id: image revision: 1 image: sys: id: 5bDwOlwnhm2CgCescKQoS6 created_at: !ruby/object:DateTime 2017-03-13 02:31:10.960000000 Z updated_at: !ruby/object:DateTime 2017-03-13 02:31:10.960000000 Z title: PANEL TWO 03 eland face turned towards us description: 3D model of Panel Two ("Rosetta Stone") of Game Pass Shelter, as seen in the Rock Art VR app. This model was made by combining archival photos with new imagery using photogrammetric techniques, and important features of the modeled are highlighted in the app in connection to audio descriptions. url: "//images.ctfassets.net/xt8ne4gbbocd/5bDwOlwnhm2CgCescKQoS6/df333027035218f7e6222351c7a3ad12/PANEL_TWO_04_part_human_part_animal_grasping_at_the_tail.jpg" caption: Fig. 7 - 3D model of Panel 2 ("Rosetta Stone") of Game Pass Shelter, as seen in the Rock Art VR app. This model was made by combining archival photos with new imagery and important features of the model are highlighted in connection to audio descriptions. - sys: id: 4whYOCUWdWiMY2MGiCWao0 created_at: !ruby/object:DateTime 2017-03-13 02:33:43.173000000 Z updated_at: !ruby/object:DateTime 2017-03-13 02:33:43.173000000 Z content_type_id: chapter revision: 1 title_internal: 'Thematic: rockartvr, chapter 8' body: 'The desired user’s outcomes for using the app include: 1) to gain a first-hand experience exploring an African rock art site virtually; 2) to learn about the African Rock Image Art project and the TARA rock art digital catalogue/website; 3) to increase awareness of the importance of African rock art, in connection to its endangered nature, artistic heritage, and importance to indigenous groups; 4) to introduce creative digital resources within the British Museum, and increase interest in our web resources and Collections Online.' - sys: id: AmuS3r3zIkMIgSmIEKqcK created_at: !ruby/object:DateTime 2017-03-13 02:34:51.546000000 Z updated_at: !ruby/object:DateTime 2017-03-13 02:35:02.983000000 Z content_type_id: image revision: 2 image: sys: id: 1zVZ5PiOc0ukuISI6GUKQK created_at: !ruby/object:DateTime 2017-03-13 02:34:38.442000000 Z updated_at: !ruby/object:DateTime 2017-03-13 02:34:38.442000000 Z title: IMG 6293 description: Children trying out the Rock Art VR app at our launch event in November 2016. url: "//images.ctfassets.net/xt8ne4gbbocd/1zVZ5PiOc0ukuISI6GUKQK/52e88e5d3e4768e99b0725145ae20d79/IMG_6293.jpg" caption: Fig. 8 - Children trying out the Rock Art VR app at our launch event in November 2016. - sys: id: 75ifs3faSWy0qw2eUS4Yu4 created_at: !ruby/object:DateTime 2017-03-13 02:37:17.726000000 Z updated_at: !ruby/object:DateTime 2019-02-21 16:11:08.975000000 Z content_type_id: chapter revision: 3 title_internal: 'Thematic: rockartvr, chapter 9' body: "We lauched the app in November 2016 with an event in the Great Court at the British Museum, where over 150 visitors used the app for the first time and provided us with valuable user feedback. Most people seemed to enjoy their experience of using the app and saw the huge potential that this technology could have for experiencing heritage in exciting, new ways and gaining new audiences! The overall positive feedback has inspired us to further develop new projects using similar techniques to reconstruct rock art sites destroyed in recent conflicts using our historical collection of photos.\n\nAdditionally, we hope to continue to work with our project partners in Africa to further develop educational resources and DIY digital technology to make African Rock Art Image archive accessible to both communities and researchers globally. \n\nThe Game Pass Shelter Rock Art VR app can be downloaded here: \n\nIOS [https://itunes.apple.com/gb/app/game-pass-shelter/id1176174140?mt=8 ](https://itunes.apple.com/gb/app/game-pass-shelter/id1176174140?mt=8) \n\nAndroid [https://play.google.com/store/apps/details?id=com.soluis.gamepassshelter&hl=en_GB\n](https://play.google.com/store/apps/details?id=com.soluis.gamepassshelter&hl=en_GB)\n\nThis app is made available as an educational resource under an Attribution-Non Commercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) license. Images copyright ©TARA/<NAME> & African Conservation Trust\n\nFor more information:\n[https://africanrockart.org/](https://africanrockart.org/ \"Trust for African Rock Art (TARA)\")\n[http://www.projectafrica.com/](http://www.projectafrica.com/)" - sys: id: 3dnPPXO03ecUwA2ymasCKo created_at: !ruby/object:DateTime 2017-03-13 02:38:10.252000000 Z updated_at: !ruby/object:DateTime 2017-03-13 02:38:10.252000000 Z content_type_id: image revision: 1 image: sys: id: 6p0X9HegW4ikqMIUGCuMMc created_at: !ruby/object:DateTime 2017-03-13 02:37:56.805000000 Z updated_at: !ruby/object:DateTime 2017-03-13 02:37:56.805000000 Z title: IMG 6295 description: Drawings inspired by the African Rock Art Image Project's archive on the replica 'rock wall' at our app launch event! url: "//images.ctfassets.net/xt8ne4gbbocd/6p0X9HegW4ikqMIUGCuMMc/56e4c97464c50ab73c5395ab03e06488/IMG_6295.jpg" caption: Fig. 9 - Drawings inspired by the African Rock Art Image Project's archive on the replica 'rock wall' at our app launch event! background_images: - sys: id: 2qLasAyYmAM4wUS2gOe4yg created_at: !ruby/object:DateTime 2017-03-12 22:40:18.738000000 Z updated_at: !ruby/object:DateTime 2017-03-12 22:40:18.738000000 Z title: Game Pass7 description: url: "//assets.ctfassets.net/xt8ne4gbbocd/2qLasAyYmAM4wUS2gOe4yg/50c79d5c2e310775bd444de205908a2e/Game_Pass7.tif" - sys: id: 4LZ2y95ptKWk2SwUQgwu4k created_at: !ruby/object:DateTime 2017-03-12 22:42:48.598000000 Z updated_at: !ruby/object:DateTime 2017-03-12 22:42:48.598000000 Z title: Game Pass3 description: url: "//assets.ctfassets.net/xt8ne4gbbocd/4LZ2y95ptKWk2SwUQgwu4k/a5150665772b9d769f26ccf3c6b39f03/Game_Pass3.tif" ---<file_sep>/_coll_country/nigeria/images.md --- layout: gallery title: Images breadcrumbs: - {label: Countries, url: ../../} - {label: Nigeria, url: ../} ---<file_sep>/_coll_country_information/botswana-country-introduction.md --- contentful: sys: id: 70Jk3F9iU0OaCQGQWkGqM6 created_at: !ruby/object:DateTime 2016-09-12 11:04:27.819000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:04:27.819000000 Z content_type_id: country_information revision: 1 title: 'Botswana: country introduction' chapters: - sys: id: 5wtp5JwhDUU0cMoCcWgGgy created_at: !ruby/object:DateTime 2016-09-12 11:25:13.083000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:25:13.083000000 Z content_type_id: chapter revision: 1 title: Introduction title_internal: 'Botswana: country, chapter 1' body: 'Botswana, a landlocked country in southern Africa, has a landscape defined by the Kalahari Desert in the west and the Okavango Delta in the north. Rock art can be found in the north, north-west and east of the country. One of the most well-known locations is the Tsodilo Hills in the north-west which contains evidence of human occupation that goes back 100,000 years. This area has yielded more than 4,000 paintings and has been termed the *Louvre of the Desert*. It also has engraved cupules and grooves dating back to the first millennium AD. ' - sys: id: 2UQ5NTtwJO42YcwmMkwQEC created_at: !ruby/object:DateTime 2016-09-12 11:25:32.308000000 Z updated_at: !ruby/object:DateTime 2018-05-10 15:41:27.865000000 Z content_type_id: image revision: 2 image: sys: id: 3nU9N3ePduuQ60SQsiuYUO created_at: !ruby/object:DateTime 2016-09-12 11:37:45.576000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:37:45.576000000 Z title: BOTTSD0190005 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3nU9N3ePduuQ60SQsiuYUO/726dcb36ac6ab50baa1de073e8672153/BOTTSD0190005_jpeg.jpg" caption: 'This schematic painting of a zebra can be found in the Tsodilo Hills in Botswana, now a UNESCO World Heritage Site. This image became the first logo of the National Museum and Art Gallery of Botswana. 2013,2034.20773 © TARA/ <NAME>. ' col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3758628&partId=1&searchText=2013,2034.20773&page=1 - sys: id: 2ZUfI0WpgssmaomWYocswq created_at: !ruby/object:DateTime 2016-09-12 11:26:11.853000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:26:11.853000000 Z content_type_id: chapter revision: 1 title: Geography and rock art distribution title_internal: 'Botswana: country, chapter 2' body: The Republic of Botswana is bordered by South Africa to the south, Namibia to the west and north and Zimbabwe to the north-east. It shares a short border consisting of a few hundred metres with Zambia to the north. The majority of this flat country, around 70%, is made up of the Kalahari Desert, with the Okavango Delta, one of the world’s largest inland deltas located in the north. Botswana has a subtropical climate of hot summers and warm winters due to its high altitude and is semi-arid due to the short rainy season. Rock art is scattered across the country with the main sites being found in the Tsodilo Hills in the north- west; the Gubatshaa Hills in the Chobe National Park, east of the Okavango Delta; Tuli Block in the far east of the country and Manyana in the south-east. - sys: id: 5gcQn3IFgAE6UYMQMyUgik created_at: !ruby/object:DateTime 2016-09-12 11:26:28.774000000 Z updated_at: !ruby/object:DateTime 2018-05-10 15:29:05.947000000 Z content_type_id: image revision: 2 image: sys: id: 67txlVj7aMsymikMMMKm4U created_at: !ruby/object:DateTime 2016-09-12 11:36:31.689000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:36:31.689000000 Z title: BOTTSDNAS0010017 description: url: "//images.ctfassets.net/xt8ne4gbbocd/67txlVj7aMsymikMMMKm4U/1cc7960b055b1328802e0c794a3e65b6/BOTTSDNAS0010017_jpeg.jpg" caption: 'Aerial view of Tsodilo Hills, Botswana. 2013,2034.21162 © TARA/ <NAME>. ' col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3762286&partId=1&searchText=2013,2034.21162&page=1 - sys: id: FXOBNXwFq0WAuyUQC4uGm created_at: !ruby/object:DateTime 2016-09-12 11:26:42.821000000 Z updated_at: !ruby/object:DateTime 2016-10-17 15:41:00.509000000 Z content_type_id: chapter revision: 2 title: Research history title_internal: 'Botswana: country, chapter 3' body: | German geologist Siegfried Passarge visited the Tsodilo Hills on the 1st July 1898, mapping the area, writing on the geology and photographing a few rock paintings. In 1907, he published tracings of his photos in Die Buschmänner der Kalahari. A passing mention of the Hills was made in 1913 in a brief report by <NAME>, but it was <NAME>, a French industrialist and explorer, who raised the profile of Tsodilo Hills when over two days he photographed and prepared tracings of what has come to be known as the “Rhino Panel” on September 27-28 1951. <NAME>’s publication of *The Lost World of the Kalahari* in 1958 brought Tsodilo Hills and its rock art to the attention of the wider world. Van der Post, an Afrikaner, had planned to make a film of the rock art in the region, but a number of events including the shooting of a steenbok (a severe crime locally), the cameras jamming and swarms of bees descending upon their camp, conspired against him and resulted in van der Post leaving the Hills in despair. However, he also left an apologetic note at the rock art panel he had been trying to film as a way of assuaging the wrath of the “Spirit of the Hills” as he put it. The rock face he was trying to film, comprising eland, giraffe and handprints, is now known as “Van der Post Panel”. - sys: id: vMbGVjcFe8YOcigyG6iuc created_at: !ruby/object:DateTime 2016-09-12 11:26:52.599000000 Z updated_at: !ruby/object:DateTime 2018-05-10 15:41:44.339000000 Z content_type_id: image revision: 4 image: sys: id: 54OlxJkeXK0ywWs4oQMqAK created_at: !ruby/object:DateTime 2016-09-12 11:38:11.611000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:38:11.611000000 Z title: BOTTSD0040004 description: url: "//images.ctfassets.net/xt8ne4gbbocd/54OlxJkeXK0ywWs4oQMqAK/875873fafa0f76e30cf3fcdcd7799454/BOTTSD0040004_jpeg.jpg" caption: 'View of the Van der Post Panel in the Tsodilo Hills as the sun is setting. 2013,2034.20449 © TARA/ <NAME>. ' col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3729885&partId=1&searchText=2013,2034.20449&page=1 - sys: id: dqvTnHT7xeCC0omYUgyas created_at: !ruby/object:DateTime 2016-09-12 11:26:59.386000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:26:59.386000000 Z content_type_id: chapter revision: 1 title: title_internal: 'Botswana: country, chapter 4' body: | In 1963 <NAME> visited the region with <NAME>, an ethnographer who had studied the San&#124;Bushmen in Botswana. As Director of Botswana’s National Museum, Campbell had a little government funding to record the rock art and excavate the rock shelters. Subsequently he collaborated with archaeologists <NAME>, <NAME>, and paleo-geographer <NAME>. During the 1990s, Campbell, along with the staff from the National Museum recorded around 400 rock art sites numbering over 4,000 individual paintings. In 2001 Tsodilo Hills became a UNESCO World Heritage Site because of its spiritual significance to local peoples, as well as its unique record of human settlement over many millennia. - sys: id: 6oBrvFH0WcGAAOqYEg2Q4s created_at: !ruby/object:DateTime 2016-09-12 11:27:09.816000000 Z updated_at: !ruby/object:DateTime 2018-05-10 15:41:53.538000000 Z content_type_id: image revision: 3 image: sys: id: 6Nezz3ZlxCMOeSOiEKuG0s created_at: !ruby/object:DateTime 2016-09-12 11:38:28.208000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:38:28.208000000 Z title: BOTTSD0170011 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6Nezz3ZlxCMOeSOiEKuG0s/ba6319e8dbe59b7609ad756a15489bc2/BOTTSD0170011_jpeg.jpg" caption: '<NAME> next to painted rock art at Rhino Cave in the Tsodilo Hills, Botswana. 2013,2034.20750 © TARA/ <NAME>. ' col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3758479&partId=1&searchText=2013,2034.20750&page=1 - sys: id: 7DJn8Jqhy0cwGwksoWSOIS created_at: !ruby/object:DateTime 2016-09-12 11:27:18.797000000 Z updated_at: !ruby/object:DateTime 2016-10-17 15:41:18.565000000 Z content_type_id: chapter revision: 5 title: Distribution and themes title_internal: 'Botswana: country, chapter 5' body: |- Tuli Block is a narrow fringe of land in the far east of the country that borders South Africa and lies on the banks of the Limpopo River. This area is characterised by rock engravings of human and animal footprints, and cupules, which hold spiritual importance both for San&#124;Bushman¹ hunter-gatherers and Tswana farmers. The engravings are thought to refer to a local myth that tells of an ancestor, named Matsieng, who is believed to have emerged from a waterhole followed by his animals. However, there are several localities in the region that claim this origin myth. It is thought the engravings in this area were created by the San&#124;Bushmen and linked to their belief system, appropriated later by the Tswana farmers. The most renowned rock art in Botswana comes from the Tsodilo Hills in the north-west of the country. With more than 4,500 paintings preserved in an area of 10km² it has been termed the “Louvre of the Desert”. Tsodilo is made up of four main hills; Male Hill, Female Hill, Child Hill and North Hill, and paintings occur on all four. The subject matter, comprised of red and white paintings, includes animals, human figures and geometric designs. Red paintings are likely to have been made by San&#124;Bushmen, while the white paintings are more difficult to attribute authorship to but may be a later continuation of the red tradition. There are no engraved images at Tsodilo but cupules and ground grooves are a common feature. Dating of the paintings at Tsodilo has been difficult, and because many of them occur on exposed surfaces where they are susceptible to damage by the sun, rain and wind, what remains is probably not very old. However, paintings of cattle, which are also badly faded, probably date to between AD 800 and 1150 when people kept these animals in this area. ¹ San&#124;Bushmen is a collective term used to describe the many different hunter-gatherer-fisher groups living in southern Africa who have related languages and cultural traditions. Both 'San' and 'Bushmen' are considered offensive terms by some members of these groups, although others have positively adopted them. - sys: id: 5TetNeY7kWwAQWW0gks2ya created_at: !ruby/object:DateTime 2016-09-12 11:27:26.815000000 Z updated_at: !ruby/object:DateTime 2018-05-10 15:43:00.396000000 Z content_type_id: image revision: 4 image: sys: id: 4bfNSUilHiW0aqEus0CQeI created_at: !ruby/object:DateTime 2016-09-12 11:38:44.342000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:38:44.342000000 Z title: BOTTSD0300004 description: url: "//images.ctfassets.net/xt8ne4gbbocd/4bfNSUilHiW0aqEus0CQeI/be79f76088201d6fabfcf13ed6cf9df5/BOTTSD0300004_jpeg.jpg" caption: Two painted rhinoceros on Female Hill, Tsodilo, Botswana. 2013,2034.20450 © TARA/ <NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3729906&partId=1&searchText=2013,2034.20450&page=1 - sys: id: 4zsMKPKa9qCmqy0YU4mCu0 created_at: !ruby/object:DateTime 2016-09-12 11:27:35.809000000 Z updated_at: !ruby/object:DateTime 2018-05-10 15:42:24.988000000 Z content_type_id: image revision: 4 image: sys: id: 19Wy6q0o68Saeo0uISC4e6 created_at: !ruby/object:DateTime 2016-09-12 11:39:05.578000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:39:05.578000000 Z title: BOTTSD0570002 description: url: "//images.ctfassets.net/xt8ne4gbbocd/19Wy6q0o68Saeo0uISC4e6/1b50517b69d707e8c2b03599e1a182f5/BOTTSD0570002_jpeg.jpg" caption: Known as the ‘Giraffe Panel’ this site is located on the east side of Female Hill at Tsodilo. 2013,2034.21232 © TARA/ <NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3744521&partId=1&searchText=2013,2034.21232&page=1 - sys: id: 5Uz37dTcS4WM0wsMqykGyM created_at: !ruby/object:DateTime 2016-09-12 11:27:44.093000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:27:44.093000000 Z content_type_id: chapter revision: 1 title_internal: 'Botswana: country, chapter 6' body: '250 km east of the Tsodilo Hills, on the eastern side of the Okavango Delta, lie the Gubatshaa Hills. Paintings here consist of geometric designs and finger painted animals such as eland, elephant, antelope and giraffe. Geometric designs are stylistically different from those at Tsodilo but share similarities with some painted designs in Carnarvon District, Northern Cape, South Africa. ' - sys: id: G2bUDmiGmi4UwaEcU8GeC created_at: !ruby/object:DateTime 2016-09-12 11:27:53.423000000 Z updated_at: !ruby/object:DateTime 2018-05-10 15:42:46.477000000 Z content_type_id: image revision: 3 image: sys: id: FTRXrT2TQao4qQ2O6Yiea created_at: !ruby/object:DateTime 2016-09-12 11:39:20.609000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:39:20.609000000 Z title: BOTGUB0010004 description: url: "//images.ctfassets.net/xt8ne4gbbocd/FTRXrT2TQao4qQ2O6Yiea/beb96fd5bfa4c52cf6a5ef1776c0096c/BOTGUB0010004_jpeg.jpg" caption: Geometric designs at Gubatshaa Hils. These differ from those at Tsodilo Hills but share similarities with painted design in the Northern Cape of South Africa. 2013,2034.20507 © TARA/ <NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3755221&partId=1&searchText=2013,2034.20507&page=1 - sys: id: 47oOZzqdvqw4624OYwIwMY created_at: !ruby/object:DateTime 2016-09-12 11:28:00.942000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:28:00.942000000 Z content_type_id: chapter revision: 1 title_internal: 'Botswana: country, chapter 7' body: 'Rock art is rare in the south-east of the country, but the site of Manyana is noteworthy because it is the only one that has been excavated. The paintings are found at five sites along a rock outcrop of 0.75 km at the base of the Koboleng Hills, and while once richly decorated, many of the paintings have now faded. It is difficult to determine exactly when the paintings were made, but excavation shows the use of ochre from the earliest occupation levels dating to the Late Stone Age, around AD 100 - 800, with the latest occupation levels dating to the Late Iron Age, around AD 1600-1700. Interestingly, none of the paintings were done in white, a colour found at many other sites in Botswana and other regions of southern Africa, and often attributed to paintings of Iron Age date. In addition, there are no images of eland or figures combining human/antelope form which are common occurrences in South African rock art. ' - sys: id: 2eBKXXsYDuuoy4UmoGAcce created_at: !ruby/object:DateTime 2016-09-12 11:28:09.513000000 Z updated_at: !ruby/object:DateTime 2018-05-10 15:43:52.079000000 Z content_type_id: image revision: 2 image: sys: id: 5DlH7qo75uqEUsW4qmGywg created_at: !ruby/object:DateTime 2016-09-12 11:39:36.074000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:39:36.074000000 Z title: BOTMAN0010005 description: url: "//images.ctfassets.net/xt8ne4gbbocd/5DlH7qo75uqEUsW4qmGywg/5b4e35d5e2f7648155d762f230aac57f/BOTMAN0010005_jpeg.jpg" caption: Three faded yellow giraffe at Manyana. 2013,2034.20530 © TARA/ David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3755681&partId=1&searchText=2013,2034.20530&page=1 - sys: id: dPgwiUL3AkUeqOoAcmgG0 created_at: !ruby/object:DateTime 2016-09-12 11:28:17.317000000 Z updated_at: !ruby/object:DateTime 2018-05-10 15:45:07.843000000 Z content_type_id: chapter revision: 3 title: Cupules and grooves title_internal: 'Botswana: country, chapter 8' body: Cupules and grooves can be found in the Tsodilo Hills, and also in the eastern part of the country in Tuli Block and Gubatshaa Hills. Engravings include human footprints and animal tracks. Most sites with engravings and/or cupules occur near water; for example at the site of Riverslee in the Tuli Block they encircle a waterhole while at Basinghall the cupule site is near the Limpopo River. - sys: id: 5dJBDiteWQoIui2AKAAC00 created_at: !ruby/object:DateTime 2016-09-12 11:28:26.560000000 Z updated_at: !ruby/object:DateTime 2018-05-10 15:46:13.060000000 Z content_type_id: image revision: 2 image: sys: id: 66x1NGJT6Eku8UIAYqQEMW created_at: !ruby/object:DateTime 2016-09-12 11:39:52.783000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:39:52.783000000 Z title: BOTTSD0410013 description: url: "//images.ctfassets.net/xt8ne4gbbocd/66x1NGJT6Eku8UIAYqQEMW/0390827df5133b4dad256c5abb3e6e3f/BOTTSD0410013_jpeg.jpg" caption: Boulder engraved with elongated oval grooves found in Crab Shelter on the west side of Female Hill, Tsodilo, Botswana. 2013,2034.20922 © TARA/ David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3761599&partId=1&searchText=2013,2034.20922&page=1 - sys: id: 4Jy5ySl2ByIo6wE442Ua4k created_at: !ruby/object:DateTime 2016-09-12 11:28:33.030000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:28:33.030000000 Z content_type_id: chapter revision: 1 title_internal: 'Botswana: country, chapter 9' body: Because the identity of the artists are unknown to us we can only speculate on the function and/or meanings of the art in relation to other rock art traditions in southern Africa. These may include fertility, health, abundance, protection against evil spirits or summoning rain. Contemporary communities at Tsodilo Hills believe that spirits live in the Hills and have explained how those who enter the Hills must be respectful as the spirits are capable of both curing and punishing people. In particular, White Paintings Shelter in the Tsodilo Hills was used as a place to perform curative dances that involved the placing of hands on the paintings in order to use its power. Geometric designs are more difficult to interpret but may fit into a tradition of other geometric symbols in the region and represent weather and fertility symbols. citations: - sys: id: 4MTpPfi0MgCWMswEYQocii created_at: !ruby/object:DateTime 2016-09-12 11:03:48.079000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:03:48.079000000 Z content_type_id: citation revision: 1 citation_line: "<NAME>; <NAME> (2010) Tsodilo Hills: Copper Bracelet of the Kalahari. East Lansing: Michigan State University Press.\n\n<NAME>, Maria; <NAME>; <NAME>. (2004) Rocks of potency: engravings and cupules from the Dovedale Ward, Southern Tuli Block, Botswana, in \nSouth African Archaeological Bulletin, 58 (178), pp: 53-62.\n" ---<file_sep>/_coll_country_information/ethiopia-country-introduction.md --- contentful: sys: id: 1wLn16dmUsUkcm6UgwmaoE created_at: !ruby/object:DateTime 2015-11-25 18:43:00.803000000 Z updated_at: !ruby/object:DateTime 2015-12-07 13:42:55.895000000 Z content_type_id: country_information revision: 4 title: 'Ethiopia: country introduction' chapters: - sys: id: 31sjVVkxrOsYoCakaWWIsw created_at: !ruby/object:DateTime 2015-11-25 18:38:08.693000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:38:08.693000000 Z content_type_id: chapter revision: 1 title: Introduction title_internal: 'Ethiopia: country, chapter 1' body: Ethiopia is the biggest country of the Horn of Africa, a very diverse country which has traditionally been a melting pot of cultures, religions and ethnicities, acting as a crossroads between the Nile valley region, the Red Sea and East Africa. Most rock art is located in the southern part of the country, although smaller concentrations have been documented near the borders with Eritrea, Sudan and Kenya. Ethiopian rock art shows strong similarities with other countries in the Horn of Africa as well as Sudan and mostly consists of cow depictions dated from the 3rd millennium onwards, although other animals, anthropomorphic figures and geometric symbols are also fairly common. - sys: id: 6DDVz3LoAwAoOaE6sg0qew created_at: !ruby/object:DateTime 2015-11-25 18:38:32.241000000 Z updated_at: !ruby/object:DateTime 2017-01-10 14:34:31.428000000 Z content_type_id: chapter revision: 4 title: Geography and rock art distribution title_internal: 'Ethiopia: country, chapter 2' body: The geography of Ethiopia is varied and ranges from high plateaus to savannahs and deserts. The eastern part mostly consists of a range of plateaus and high mountains, which in some cases reach more than 4000m above sea level. To the north of these mountains is Lake Tana, the biggest lake in Ethiopia and the source of the Blue Nile, one of the two tributaries of the Nile. The mountains are divided in two by the Great Rift Valley, which runs north-east to south-west, - and is one of the most important areas for the study of human evolution. The highlands are surrounded by tropical savannah and grassland regions to the west and south-west, while to the east lays the Danakil desert, one of the most inhospitable regions on earth. The south-eastern corner of Ethiopia, which borders Somalia, is a semi-desert plateau ranging from 300-1500 m above sea level. - sys: id: W4Ffii79a8aAicMksA4G0 created_at: !ruby/object:DateTime 2015-11-25 19:40:22.095000000 Z updated_at: !ruby/object:DateTime 2017-01-10 14:42:57.195000000 Z content_type_id: image revision: 3 image: sys: id: IIbbaihhGSi02y0qamaIy created_at: !ruby/object:DateTime 2015-11-25 19:43:02.833000000 Z updated_at: !ruby/object:DateTime 2015-11-25 19:43:02.833000000 Z title: ETHNAS0005 description: url: "//images.ctfassets.net/xt8ne4gbbocd/IIbbaihhGSi02y0qamaIy/b9ff2db6b1f2d89f359fe4f4278c51af/ETHNAS0005.jpg" caption: View of landscape in southern Ethiopia. 2013,2034.16171 © <NAME>/TARA col_link: http://bit.ly/2jqquJj - sys: id: 5lRTzejpleGqe2MQ0O4k0o created_at: !ruby/object:DateTime 2015-11-25 18:38:53.256000000 Z updated_at: !ruby/object:DateTime 2017-01-10 14:48:57.742000000 Z content_type_id: chapter revision: 3 title_internal: 'Ethiopia: country, chapter 3' body: 'Ethiopian rock art is located around two main areas: around the city of Harar to the east and the Sidamo region to the south-west. The first group comprises mainly painted depictions, while the second one is characterized by a bas-relief technique specific only to this area. However, rock art has also been discovered in other areas, such as the border with Eritrea, the area near Kenya and the Benishangul-Gumuz region, a lowland area along the border with Sudan. As research increases, it is likely that more rock art sites will be discovered throughout the country. In addition to these engravings and paintings, Ethiopia is also known for its decorated stelae, tall stone obelisks that are usually engraved with culturally and religiously important symbols. One of these places is Tiya, a burial place declared a World Heritage Site which has 32 richly decorated stelae. Although not strictly rock art in the traditional sense, they nevertheless represent one of the most interesting group of archaeological remains in the south of Ethiopia and demonstrate similar techniques to some of the engraved depictions.' - sys: id: 6Aw2hC2mDSGKMsEWYOa80C created_at: !ruby/object:DateTime 2015-11-25 19:46:38.477000000 Z updated_at: !ruby/object:DateTime 2017-01-10 15:06:35.150000000 Z content_type_id: image revision: 2 image: sys: id: 4w2Qic7EkEe0omyUA2i6QU created_at: !ruby/object:DateTime 2015-11-25 19:46:16.750000000 Z updated_at: !ruby/object:DateTime 2015-11-25 19:46:16.750000000 Z title: '2013,2034.16248' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4w2Qic7EkEe0omyUA2i6QU/5b36c4b2ad5132161c8e8348f760df1c/2013_2034.16248.jpg" caption: View of engraved cow with curved horns and marked udders. Shepe, Ethiopia. 2013,2034.16248 © <NAME>/TARA col_link: http://bit.ly/2i9tddD - sys: id: 2FarnK5oM0Ese246YsW2WC created_at: !ruby/object:DateTime 2015-11-25 18:39:19.763000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:39:19.763000000 Z content_type_id: chapter revision: 1 title: Research history title_internal: 'Ethiopia: country, chapter 4' body: Ethiopian rock art has played a key role in the Horn of Africa research, and the studies undertaken in this country have structured the chronologies, styles and interpretations of the whole region. Research started as early as the mid-1930s when the <NAME> proposed a classification of Ethiopian rock art through the study of the Porc-Epic and Genda-Biftou sites. This proposal stated a progressive evolution in eight steps from naturalism to schematism, and set the interpretative framework for succeeding decades. Breuil’s ideas were generally followed by <NAME> in his synthesis of the rock art in the Horn of Africa in 1954, and they also appear in the work of Paolo Graziosi (1964). During the 1960s, research was carried out by <NAME> in the Sidamo area and by <NAME> near Harar, where a report made for the Ethiopian government informed about the existence of around ten rock art sites in the same area. - sys: id: 5FlXwLASzY64aWE8kyUQi0 created_at: !ruby/object:DateTime 2015-11-25 19:41:06.599000000 Z updated_at: !ruby/object:DateTime 2017-01-10 15:20:14.088000000 Z content_type_id: image revision: 2 image: sys: id: 5rOzA2mToQEA8eCoE2S6yc created_at: !ruby/object:DateTime 2015-11-25 19:44:49.577000000 Z updated_at: !ruby/object:DateTime 2015-11-25 19:44:49.577000000 Z title: ETHLAG0010030 description: url: "//images.ctfassets.net/xt8ne4gbbocd/5rOzA2mToQEA8eCoE2S6yc/8a7fad16c52c41bab12fb032ccfc026c/ETHLAG0010030.jpg" caption: View of painted cattle and human figures. Laga Oda, Ethiopia. 2013,2034.16575 © <NAME>/TARA col_link: http://bit.ly/2j3OmG6 - sys: id: 64V0g8Z7P2EYc4AyAIKuWs created_at: !ruby/object:DateTime 2015-11-25 18:39:35.423000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:39:35.423000000 Z content_type_id: chapter revision: 1 title_internal: 'Ethiopia: country, chapter 5' body: Rock art research in Ethiopia has traditionally included the term Ethiopian-Arabian style, coined in 1971 by Červiček to show the similarities between the depictions found in the Horn of Africa and the Arabian Peninsula. The existence of this style is currently the paradigm used in most rock art interpretations of the region, although some concerns have been raised due to its too generic characteristics, which can be found in many other parts of Africa. The 1990s and 2000s have seen a remarkable increase of rock art research in the country, with the renewal of studies in the main areas and the beginning of research in the regions of Tigray and Benishangul-Gumuz. - sys: id: 5NlCEmTba0OqysyQwwQcKk created_at: !ruby/object:DateTime 2015-11-25 19:41:26.088000000 Z updated_at: !ruby/object:DateTime 2017-01-10 15:21:39.681000000 Z content_type_id: image revision: 2 image: sys: id: 6jqDCZikwg60QmgaSYKsKA created_at: !ruby/object:DateTime 2015-11-25 19:44:57.045000000 Z updated_at: !ruby/object:DateTime 2015-11-25 19:44:57.045000000 Z title: ETHDAG0010003 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6jqDCZikwg60QmgaSYKsKA/43845a952bb5271b011eed5227486ec2/ETHDAG0010003.jpg" caption: View of rock shelter full of humped cattle, human figures and unidentified shapes. Saka Sharifa, Ethiopia. 2013,2034.16397 © <NAME>/TARA col_link: http://bit.ly/2iAVSEX - sys: id: 4iWjeBjtmoEKS42IImMCYI created_at: !ruby/object:DateTime 2015-11-25 18:39:53.855000000 Z updated_at: !ruby/object:DateTime 2017-01-10 15:34:19.840000000 Z content_type_id: chapter revision: 2 title: Themes title_internal: 'Ethiopia: country, chapter 6' body: Cattle and cattle-related depictions are the main subject of Ethiopian rock art, regardless of their relative chronology. The oldest depictions (based on Červiček’s works) are of humpless cows, while in the late stages of rock art humped cows and camels appear. Goats, sheep and dogs are very occasionally depicted, and unlike the Saharan rock art, wild animals such as giraffes and antelopes are scarce. Figures of cattle appear alone or in herds, and the depictions of cows with calves are a fairly common motif not only in Ethiopia but in the whole Horn of Africa. - sys: id: 4180pjSpqg2mQKuYMq66a4 created_at: !ruby/object:DateTime 2015-11-25 19:41:45.230000000 Z updated_at: !ruby/object:DateTime 2017-01-10 15:35:54.275000000 Z content_type_id: image revision: 2 image: sys: id: cyrbFGoA8wEaS8qM4Ys4c created_at: !ruby/object:DateTime 2015-11-25 19:45:06.217000000 Z updated_at: !ruby/object:DateTime 2015-11-25 19:45:06.217000000 Z title: ETHKIM0010014 description: url: "//images.ctfassets.net/xt8ne4gbbocd/cyrbFGoA8wEaS8qM4Ys4c/dae038fef2aa592df7f64faebacd63a9/ETHKIM0010014.jpg" caption: Group of humped cattle painted in white, with round heads. Kimet, Ethiopia. 2013,2034.16534 © <NAME>/TARA col_link: http://bit.ly/2iB07QT - sys: id: 3jCmlMhq00Wq8g8aSMgqc2 created_at: !ruby/object:DateTime 2015-11-25 18:40:11.167000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:40:11.167000000 Z content_type_id: chapter revision: 1 title_internal: 'Ethiopia: country, chapter 7' body: The other main group of depictions is of anthropomorphs, which are usually schematic and often distributed in rows. In some cases, the tendency to schematism is so pronounced that human figures are reduced to an H-like shape. Sometimes, human figures are represented as warriors, carrying weapons and on occasion fighting against other humans or big felines. Along with these figurative themes, geometric signs are very common in Ethiopian rock art, including groups of dots and other motifs that have been interpreted as symbols associated with groups that historically lived in the region. - sys: id: 1eqq7kEwJUWO0EgC6cqmEY created_at: !ruby/object:DateTime 2015-11-25 19:42:03.855000000 Z updated_at: !ruby/object:DateTime 2017-01-10 16:28:50.616000000 Z content_type_id: image revision: 2 image: sys: id: 1gmLTDIgQY8i4SgKUMYSc4 created_at: !ruby/object:DateTime 2015-11-25 19:45:20.229000000 Z updated_at: !ruby/object:DateTime 2015-11-25 19:45:20.229000000 Z title: ETHKIM0010016 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1gmLTDIgQY8i4SgKUMYSc4/fb8b409508be98645c1d84812937d4ab/ETHKIM0010016.jpg" caption: View of schematic, red human figure. Kimet, Ethiopia. 2013,2034.16536 © <NAME>/TARA col_link: http://bit.ly/2jqRjNt - sys: id: 6AAXBjdFN6mACg0K8kEGcQ created_at: !ruby/object:DateTime 2015-11-25 18:40:35.934000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:40:35.934000000 Z content_type_id: chapter revision: 1 title_internal: 'Ethiopia: country, chapter 8' body: 'Not all themes are distributed in every area. In Sidamo, almost all figures depict humpless cows, while subjects in the Harar region show a far bigger variability. Again, differences in techniques are also evident: while depictions in the Harar region are mainly paintings, in Sidamo many figures are engraved in a very singular way, lowering the area around the figures to achieve a bas-relief effect. The clear differences between the Sidamo engravings (known as the Chabbé-Galma group) and those of the Harar (the Laga Oda-Sourré group) have led to criticisms about the perceived uniformity of the *Ethiopian-Arabian* style.' - sys: id: 6cRf4VoFgsiuoQUaKoG6Eq created_at: !ruby/object:DateTime 2015-11-25 19:42:26.511000000 Z updated_at: !ruby/object:DateTime 2017-01-10 16:29:56.050000000 Z content_type_id: image revision: 2 image: sys: id: 6johOxHojKY4EkOqEco6c6 created_at: !ruby/object:DateTime 2015-11-25 19:45:27.772000000 Z updated_at: !ruby/object:DateTime 2015-11-25 19:45:27.772000000 Z title: ETHSOD0030007 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6johOxHojKY4EkOqEco6c6/2640f76a5871320bf2ff03fefd8c37a7/ETHSOD0030007.jpg" caption: Engraved grids and geometric signs. Ambe Akirsa, Ethiopia. 2013,2034.16270 © <NAME>/TARA col_link: http://bit.ly/2iYklVo - sys: id: 5oDcrjBLqwk44WoQge2ECA created_at: !ruby/object:DateTime 2015-11-25 18:41:00.681000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:41:00.681000000 Z content_type_id: chapter revision: 1 title: Chronology title_internal: 'Ethiopia: country, chapter 9' body: As is the case with most African rock art, absolute dates for depictions based on radiocarbon techniques are scarce, and therefore most of the chronological framework of Ethiopian rock art has to rely on the analysis of figures, superimpositions, parallels with depictions of better known areas and other indirect dating methods. In Ethiopian rock art it is generally assumed that the oldest depictions could be dated to the mid-third millennium BC, according to parallels with other Saharan rock art. As aforementioned, the so-called Ethiopian-Arabian style shows an evolution from naturalism to schematism, with an older group (Sourré-Hanakiya) showing strong similarities with rock art in Egypt, Sudan and Libya. A second, progressively schematic group (Dahtami) would last until the end of the first millennium BC. This date is supported by the appearance of camels and humped cows (zebus), which were introduced in the region at the end of the second half of the 1st millennium BC. The last stages of Ethiopian rock art relating to camel, warriors and geometric depictions can be considered to belong to the historical period, in some cases reaching very near to the present day. - sys: id: 5znoN0ALBYKoEswqOIoUQ4 created_at: !ruby/object:DateTime 2015-11-25 19:42:45.233000000 Z updated_at: !ruby/object:DateTime 2017-01-10 16:31:49.133000000 Z content_type_id: image revision: 2 image: sys: id: 5Q738mIexa8sWUwqsai8Ai created_at: !ruby/object:DateTime 2015-11-25 19:45:35.501000000 Z updated_at: !ruby/object:DateTime 2015-11-25 19:45:35.501000000 Z title: ETHGOD0010011 description: url: "//images.ctfassets.net/xt8ne4gbbocd/5Q738mIexa8sWUwqsai8Ai/89f7045007c92e674ef5854118853c04/ETHGOD0010011.jpg" caption: ": Panel infilled with painted camels, unidentified quadrupeds and geometric signs. G<NAME>, Ethiopia. 2013,2034.16466 © <NAME>/TARA" col_link: http://bit.ly/2jztgzY citations: - sys: id: 6KRR3bOPjUYGU8m6eA4QkC created_at: !ruby/object:DateTime 2015-11-25 18:41:41.635000000 Z updated_at: !ruby/object:DateTime 2015-12-11 11:45:00.268000000 Z content_type_id: citation revision: 2 citation_line: | <NAME>. (1971): Rock paintings of Laga Oda (Ethiopia). *Paideuma*, 17: 121-136. <NAME>. (1954): T*he Prehistoric Cultures of the Horn of Africa*. Octagon Press, New York. <NAME>. (1990): Distribution of Rock Paintings and Engravings in Ethiopia. *Proceedings of the First National Conference of Ethiopian Studies, Addis Ababa*, 1990: 289-302. ---<file_sep>/_coll_country/mauritania/guilemsi.md --- breadcrumbs: - label: Countries url: "../../" - label: Mauritania url: "../" layout: featured_site contentful: sys: id: QsOItel9sWUGymKiQe8QC created_at: !ruby/object:DateTime 2015-11-25 16:34:24.351000000 Z updated_at: !ruby/object:DateTime 2015-12-08 14:43:50.662000000 Z content_type_id: featured_site revision: 4 title: Guilemsi, Mauritania slug: guilemsi chapters: - sys: id: 3PyEd6v57yqOQ4GyumkyG8 created_at: !ruby/object:DateTime 2015-11-25 16:28:56.057000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:28:56.057000000 Z content_type_id: chapter revision: 1 title_internal: 'Mauritania: featured site, chapter 1' body: A significant concentration of rock art in Mauritania is in the region of Guilemsi, an 11-km long ridge, about 70 m high at its highest point. Guilemsi is located in the desert, around 50 km north of the town of Tidjika, and about 200 km west of the renowned Neolithic sites at Dhar Tichitt. Guilemsi’s south face contains many ravines with rock shelters, and the rock painting sites scattered around the area are to be found in open shelters and ridges or boulders on the cliff faces, as well as on the stone banks of a dry river. These sites are notable both for the solely painted nature of the rock art, and the variety of its subject matter. - sys: id: 68H1B3nwreqsiWmGqa488G created_at: !ruby/object:DateTime 2015-11-25 16:21:40.277000000 Z updated_at: !ruby/object:DateTime 2018-08-23 14:31:27.636000000 Z content_type_id: image revision: 2 image: sys: id: 1uRo8OtMas0sE0uiOUSIok created_at: !ruby/object:DateTime 2015-11-25 16:19:58.328000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:19:58.328000000 Z title: '2013,2034.12416' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1uRo8OtMas0sE0uiOUSIok/71ebc908be14899de348803b21cddc31/2013_2034.12416.jpg" caption: Painted human figure on horseback. <NAME>, 2013,2034.12418 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3646307&partId=1&searchText=2013,2034.12418&page=1 - sys: id: 6MRt7S2BckWkaGcGW4iEMY created_at: !ruby/object:DateTime 2015-11-25 16:29:11.911000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:29:11.911000000 Z content_type_id: chapter revision: 1 title_internal: 'Mauritania: featured site, chapter 2' body: There are many stone constructions at Guilemsi that have been known to archaeologists for decades, although they have not received the academic attention that those further to the East in the Tichitt-Walata region had. The Dhars Tagant, Tichitt, Walata and Néma form an enormous crescent-shaped chain of sandstone escarpments, enclosing much of southern Mauritania and associated with a Neolithic ‘Tichitt Tradition’, which is based on the remains of over 400 apparent settlements along the escarpment ridges. This culture is thought to have existed between about 2,000 BC and 200 BC, based on pastoralism and the cultivation of millet, before declining due to the increasing aridity of the environment and possible incursion by other cultural groups from the North. - sys: id: 2uYbn8i2oQQEcu4gMYyKCQ created_at: !ruby/object:DateTime 2015-11-25 16:22:17.768000000 Z updated_at: !ruby/object:DateTime 2018-08-23 14:32:15.715000000 Z content_type_id: image revision: 3 image: sys: id: 5MkqJUXrj2o4e8SmweeoW2 created_at: !ruby/object:DateTime 2015-11-25 16:19:58.333000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:19:58.333000000 Z title: '2013,2034.12357' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5MkqJUXrj2o4e8SmweeoW2/92eeb35eb7e827596e213cd06cf9fe4a/2013_2034.12357.jpg" caption: View looking South from the West summit on the sandstone ridge of Guilemsi, Tagant, Mauritania. 2013,2034.12357 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3646542&partId=1&searchText=2013,2034.12357&page=1 - sys: id: 1CiJq8i5liqkImaM4mEWe created_at: !ruby/object:DateTime 2015-11-25 16:29:28.225000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:29:28.226000000 Z content_type_id: chapter revision: 1 title_internal: 'Mauritania: featured site, chapter 3' body: The Tichitt Tradition is characterised by dry stonewall remains, and these are found at Guilemsi, although the extent of the connection with the Tichitt culture to the East is unclear. The ridge at Guilemsi contains many apparent funerary monuments consisting of rectangular stone platforms, as well as apparent dwelling structures. Some of the funerary monuments appear to be associated with rock shelters, but any connection of the stone structures to the rock art remains unknown. - sys: id: 1blgrBPnEoSKqeCASmUgGI created_at: !ruby/object:DateTime 2015-11-25 16:22:58.090000000 Z updated_at: !ruby/object:DateTime 2018-08-23 14:32:49.841000000 Z content_type_id: image revision: 2 image: sys: id: 7yy2sbn6PCoeuqyQOAgcA8 created_at: !ruby/object:DateTime 2015-11-25 16:19:58.288000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:19:58.288000000 Z title: '2013,2034.12494' description: url: "//images.ctfassets.net/xt8ne4gbbocd/7yy2sbn6PCoeuqyQOAgcA8/0914de8f403684d18accff0284017210/2013_2034.12494.jpg" caption: Stonewall remains, Guilemsi, Tagant, Mauritania. 2013,2034. 12494 © David Coulson/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3646554&partId=1&searchText=2013,2034.12494&page=1 - sys: id: 2d8TB564qE4E6yw6I0MG2A created_at: !ruby/object:DateTime 2015-11-25 16:29:44.594000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:29:44.594000000 Z content_type_id: chapter revision: 1 title_internal: 'Mauritania: featured site, chapter 4' body: The rock art at Guilemsi appears to be all painted, which marks a contrast to Tichitt sites which more often feature engraved rock art. The only non-painted rock markings encountered at Guilemsi was several groups of cupules (round, man-made depressions in the rock) which were found in three rock shelters. Some of the paintings in the area are unusual in themselves- one of the most striking is a panel of handprints in red (Fig. 4.), as well as a couple of rare paintings appearing to be of big cats, and the heads and finely rendered horns of seven antelope, perhaps oryx (Fig. 5.). - sys: id: 1pP6kJroQ4C2CYAim6KGQy created_at: !ruby/object:DateTime 2015-11-25 16:23:33.025000000 Z updated_at: !ruby/object:DateTime 2018-08-23 14:33:17.453000000 Z content_type_id: image revision: 2 image: sys: id: 6uIYZ0iOROas4Uqo4u4UyW created_at: !ruby/object:DateTime 2015-11-25 16:19:51.669000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:19:51.669000000 Z title: '2013,2034.12382' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6uIYZ0iOROas4Uqo4u4UyW/3215c1e93f536598e0a14be6fcecfa82/2013_2034.12382.jpg" caption: Paint handprints on rock shelter wall, Guilemsi, Tagant, Mauritania. 2013,2034.12382 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3646167&partId=1&searchText=2013,2034.12382&page=1 - sys: id: 3exPT8hfMAQ2SUIeGqKgSU created_at: !ruby/object:DateTime 2015-11-25 16:24:09.355000000 Z updated_at: !ruby/object:DateTime 2018-08-23 14:34:51.120000000 Z content_type_id: image revision: 2 image: sys: id: 2QrzxNR1jq4w8EO2KEUUoE created_at: !ruby/object:DateTime 2015-11-25 16:19:58.317000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:19:58.317000000 Z title: '2013,2034.12421' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2QrzxNR1jq4w8EO2KEUUoE/10c62c938cb1ed9f9b6d25edf4d17205/2013_2034.12421.jpg" caption: Painted heads of seven antelope (oryx?), rock shelter wall, Guilemsi, Tagant, Mauritania. 2013,2034.12427 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3646352&partId=1&searchText=Painted+heads+of+seven+antelope+&page=1 - sys: id: 3Q3fT8FApyQooa8cikOkiU created_at: !ruby/object:DateTime 2015-11-25 16:30:05.118000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:30:05.118000000 Z content_type_id: chapter revision: 1 title_internal: 'Mauritania: featured site, chapter 5' body: 'Cattle, perhaps the most common animal subject in Mauritanian rock art, are also depicted here, notably in another singular scene: one of an otherwise naturalistic cow with dramatically elongated legs, next to an artificially inflated-looking human figure (Fig. 8). Domestic cattle were present in the area from at least the second Millennium BC, so these paintings must post-date this, although whether they are associated with Tichitt-Tradition pastoralists or later groups is not known. The fact that even the more normally-proportioned cattle representations at Guilemsi are depicted in a variety of styles (Figs. 6 & 7) while in the same vicinity may suggest successive (or perhaps even contemporary) painting by peoples with different stylistic traditions.' - sys: id: 2WJOpXkkG4C4sce8wkcE4U created_at: !ruby/object:DateTime 2015-11-25 16:24:46.144000000 Z updated_at: !ruby/object:DateTime 2018-08-23 15:03:22.300000000 Z content_type_id: image revision: 2 image: sys: id: 32ojd6nNewwy8qSU0kuYYk created_at: !ruby/object:DateTime 2015-11-25 16:20:01.824000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:20:01.824000000 Z title: '2013,2034.12381' description: url: "//images.ctfassets.net/xt8ne4gbbocd/32ojd6nNewwy8qSU0kuYYk/3328ca79a097f10fe9b125c43352c0a8/2013_2034.12381.jpg" caption: Painted bichrome cow, cave wall, Guilemsi, Tagant, Mauritania. 2013,2034.12381 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3646170&partId=1&searchText=2013,2034.12381+&page=1 - sys: id: Z2iJHm63qoW8e8wsAqCAK created_at: !ruby/object:DateTime 2015-11-25 16:25:17.499000000 Z updated_at: !ruby/object:DateTime 2018-08-23 15:04:00.340000000 Z content_type_id: image revision: 2 image: sys: id: 3Z70aGhdUsOCKyWyK6u8eE created_at: !ruby/object:DateTime 2015-11-25 16:19:51.681000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:19:51.681000000 Z title: '2013,2034.12449' description: url: "//images.ctfassets.net/xt8ne4gbbocd/3Z70aGhdUsOCKyWyK6u8eE/c818ef2eba7505c159c231e4aa35ad4a/2013_2034.12449.jpg" caption: Two schematic painted cattle, Guilemsi, Tagant, Mauritania. 2013,2034.12449 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3647071&partId=1&searchText=2013,2034.12449&page=1 - sys: id: 56Ia1KTWDKwuw0ekagww6K created_at: !ruby/object:DateTime 2015-11-25 16:30:23.129000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:30:23.129000000 Z content_type_id: chapter revision: 1 title_internal: 'Mauritania: featured site, chapter 6' body: 'Two of the most impressive panels of paintings from Guilemsi involve not cattle but another important domesticate: ridden horses. There is evidence of horses having reached the far West of North Africa by about 600 AD, but horses may have been used in the area much earlier, from the mid-1st Millennium BC, if not earlier. Although elsewhere in the Sahara the earliest horse images appear to show them used for draught purposes rather than riding, in Mauritania, almost all depictions of horses in rock art show them being ridden, often by apparently armed riders (eg. Fig. 11). At Guilemsi, there are several styles of paintings showing horses and riders: the ‘bi-triangular’ and stick-figure like styles (Figs. 10 & 11), which have been proposed to be associated with early Berber peoples, and another style, showing horses with elongated, stylised bodies and short necks (Fig. 9). These horse depictions appear to be of a form thus far unrecorded in the rock art of the area, and as such are an interesting addition to the known corpus, as Mauritanian rock art has not been as thoroughly studied as that of other Saharan countries.' - sys: id: 6mPD0Om12wAcaOmOiaumYk created_at: !ruby/object:DateTime 2015-11-25 16:25:53.929000000 Z updated_at: !ruby/object:DateTime 2018-08-23 15:04:24.323000000 Z content_type_id: image revision: 2 image: sys: id: 2CFj8amCm8aMkkmQ0emk0o created_at: !ruby/object:DateTime 2015-11-25 16:19:51.669000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:19:51.669000000 Z title: '2013,2034.12474' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2CFj8amCm8aMkkmQ0emk0o/c4ea95ada7f53b9ffb0c43bb6f412b8f/2013_2034.12474.jpg" caption: Painted figures of contorted cow and human figure, and regularly-proportioned cow, Guilemsi, Tagant, Mauritania. 2013,2034.12474 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3646484&partId=1&searchText=2013,2034.12474+&page=1 - sys: id: 2da6EUC7TC6wSWGAOwQaAO created_at: !ruby/object:DateTime 2015-11-25 16:26:22.515000000 Z updated_at: !ruby/object:DateTime 2018-08-23 15:04:47.280000000 Z content_type_id: image revision: 2 image: sys: id: 58CHInxW4wagKgwCAsWcqY created_at: !ruby/object:DateTime 2015-11-25 16:19:58.272000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:19:58.272000000 Z title: '2013,2034.12411' description: url: "//images.ctfassets.net/xt8ne4gbbocd/58CHInxW4wagKgwCAsWcqY/f1370f3f0700aaae60918abb3821cb22/2013_2034.12411.jpg" caption: Painted figures of mounted horses on cave wall, Guilemsi, Tagant, Mauritania. 2013,2034.12411 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3646326&partId=1&searchText=2013,2034.12411+&page=1 - sys: id: 4UfKI7DmWA4A4eqocC0iMG created_at: !ruby/object:DateTime 2015-11-25 16:26:54.429000000 Z updated_at: !ruby/object:DateTime 2018-08-23 15:05:23.813000000 Z content_type_id: image revision: 2 image: sys: id: 3nZtTK8uIEc2MqGAqQC8c6 created_at: !ruby/object:DateTime 2015-11-25 16:19:51.680000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:19:51.680000000 Z title: '2013,2034.12454' description: url: "//images.ctfassets.net/xt8ne4gbbocd/3nZtTK8uIEc2MqGAqQC8c6/c36ab38978b6ccdc3ff693edeeb20091/2013_2034.12454.jpg" caption: Three painted “bi-triangular” schematic horses and riders, with white geometric shape and several unidentified figures. Guilemsi, <NAME>. 2013,2034.12454 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3648285&partId=1&searchText=2013,2034.12454&page=1 - sys: id: 16gHbuP8Hqo4KwCQK0sWeI created_at: !ruby/object:DateTime 2015-11-25 16:30:45.101000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:30:45.101000000 Z content_type_id: chapter revision: 1 title_internal: 'Mauritania: featured site, chapter 7' body: Another very interesting tableau is that in Fig. 11, which is to the right of the panel in Fig. 9, but in executed in a very different style. It appears to depict a group of armed horsemen, and warriors on foot, vanquishing others who are unmounted, who lie, presumably dead, to the left of the horsemen, surrounded by spears. This is an unusually dynamic depiction of conflict, and it is not known whether it depicts an imagined or real confrontation, or, if real, whether it is the work of an artist from the culture of the horsemen or those opposing them. - sys: id: 60nybfnB4cmoOaIQq8sWkC created_at: !ruby/object:DateTime 2015-11-25 16:27:25.377000000 Z updated_at: !ruby/object:DateTime 2018-09-17 17:56:58.326000000 Z content_type_id: image revision: 2 image: sys: id: 1EGPJpRMnmuk6Y6c0Qigos created_at: !ruby/object:DateTime 2015-11-25 16:19:58.251000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:19:58.251000000 Z title: '2013,20134.12436' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1EGPJpRMnmuk6Y6c0Qigos/332e9d6c97776b73a42854cff4ea81b4/2013_20134.12436.jpg" caption: Painted figures of mounted horses with armed riders, two armed human figures on foot, several prone human figures, with possible mounted cow at lower right. Guilemsi, Tagant, Mauritania. 2013,20134.12424 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3646333&partId=1&searchText=Guilemsi,+Tagant&&page=2 - sys: id: 41eYfH850QI2GswScg6uE8 created_at: !ruby/object:DateTime 2015-11-25 16:31:05.524000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:31:05.524000000 Z content_type_id: chapter revision: 1 title_internal: 'Mauritania: featured site, chapter 8' body: |- It has been suggested that the painting of the horse scenes, in line with similar images from other rock art traditions, may be a cathartic spiritual exercise made, possibly by victims of raids, in response to violent intercultural contact. However as with the other images, without an accurate way of scientifically dating such paintings, it is hard to know exactly when they were painted and therefore difficult to propose of or by whom, much less ascribe motivations. Stone tools and the remains of iron smelting activity at Guilemsi suggest successive occupations, possibly over a long period. Stylistic links to other sites may be made, however: despite the fact that some of the iconography at Guilemsi appears quite unique, other elements, such as the bichrome cow in Fig. 6, and other square figures at Guilemsi of a man and giraffe, have similar looking counterparts in the Tichitt region, while the “bi-triangular” horses are found elsewhere in the Tagant and Adrar regions of Mauritania, and even as far away as Chad. Understanding of these links is still nascent, as is the interpretation of most Mauritanian rock art, but the variety present at Guilemsi is a valuable addition to the record, and more such sites may remain to be brought to the notice of scholars. citations: - sys: id: 1Y8dbSWSLaGs4Iyeq8COE created_at: !ruby/object:DateTime 2015-11-25 16:28:18.975000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:28:18.975000000 Z content_type_id: citation revision: 1 citation_line: |- <NAME>., <NAME>., <NAME>., & <NAME>., *Funerary Monuments and Horse Paintings: A Preliminary Report on the Archaeology of a Site in the Tagant Region of South East Mauritania- Near Dhar Tichitt*. The journal of North African Studies, Vol. 10, No. 3-4, pp. 459-470 <NAME>., <NAME>., <NAME>., & <NAME>. 2006, *Some Mauritanian Rock art Sites*. Sahara. Prehistory and History of the Sahara, Vol. 17, pp.143-148 background_images: - sys: id: 6uIYZ0iOROas4Uqo4u4UyW created_at: !ruby/object:DateTime 2015-11-25 16:19:51.669000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:19:51.669000000 Z title: '2013,2034.12382' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6uIYZ0iOROas4Uqo4u4UyW/3215c1e93f536598e0a14be6fcecfa82/2013_2034.12382.jpg" - sys: id: 7yy2sbn6PCoeuqyQOAgcA8 created_at: !ruby/object:DateTime 2015-11-25 16:19:58.288000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:19:58.288000000 Z title: '2013,2034.12494' description: url: "//images.ctfassets.net/xt8ne4gbbocd/7yy2sbn6PCoeuqyQOAgcA8/0914de8f403684d18accff0284017210/2013_2034.12494.jpg" ---<file_sep>/_coll_country/sudan/jebel-uweinat.md --- breadcrumbs: - label: Countries url: "../../" - label: Sudan url: "../" layout: featured_site contentful: sys: id: 5T1CxEt3MIkwM42YCMEcac created_at: !ruby/object:DateTime 2015-11-25 14:12:07.582000000 Z updated_at: !ruby/object:DateTime 2015-12-07 20:52:29.073000000 Z content_type_id: featured_site revision: 4 title: Jebel Uweinat, Sudan slug: jebel-uweinat chapters: - sys: id: 2Mj1hP5TQci0sCEuAKUQ8o created_at: !ruby/object:DateTime 2015-11-25 14:19:54.772000000 Z updated_at: !ruby/object:DateTime 2015-11-25 14:19:54.772000000 Z content_type_id: chapter revision: 1 title_internal: 'Sudan: featured site, chapter 1' body: At the nexus of Sudan, Libya and Egypt, where the borders meet at a point in the Eastern Sahara, a large rocky outcrop known as Jebel Uweinat peaks at an elevation of nearly 2,000 metres. The massif consists of a large, ring-shaped granite mass in the west, with sandstone plateaus in the east divided by deep valleys. Jebel Uweinat is so isolated that, until 1923, the proliferation of rock art around it had never been documented. - sys: id: 1Xgrdv52peoaGuSSayg20g created_at: !ruby/object:DateTime 2015-11-25 14:16:00.395000000 Z updated_at: !ruby/object:DateTime 2017-01-09 17:16:10.904000000 Z content_type_id: image revision: 2 image: sys: id: 1DXzN0USKMoCI4kywAKeEy created_at: !ruby/object:DateTime 2015-11-25 14:18:38.585000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:07:57.029000000 Z title: '2013,2034.6' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3577799&partId=1&searchText=2013,2034.6&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/1DXzN0USKMoCI4kywAKeEy/c1f12caa1933afa9134b18c5505d14b8/2013_2034.6.jpg" caption: Painted cattle and human figures on rock shelter roof. <NAME>, Jebel Uweinat. 2013,2034.6 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3577799&partId=1&searchText=2013,2034.6&page=1 - sys: id: 1HdRAmiEkIGCwsagKyAWgy created_at: !ruby/object:DateTime 2015-11-25 14:20:17.081000000 Z updated_at: !ruby/object:DateTime 2015-11-25 14:20:17.081000000 Z content_type_id: chapter revision: 1 title_internal: 'Sudan: featured site, chapter 2' body: This rock art comes in the form of paintings and engravings, commonly of animals and overwhelmingly of domestic cattle – 337 painted sites out of 414 that have been counted contain depictions of cattle and cattle herds, and there are many further engravings of them. There is a disparity in the spread of each artwork technique – the engravings are predominantly at lower levels than the paintings, near the base of the mountain and valley floors, with the paintings at greater altitude. The images shown here come from <NAME>, the largest of these valleys, which lies mostly in Sudan. - sys: id: 1ay8a3SCfmwOgsgwoIQigW created_at: !ruby/object:DateTime 2015-11-25 14:16:50.686000000 Z updated_at: !ruby/object:DateTime 2017-01-09 17:16:25.098000000 Z content_type_id: image revision: 2 image: sys: id: 70RmZtVt9Cy4Ameg0qOoCo created_at: !ruby/object:DateTime 2015-11-25 14:18:38.600000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:08:32.195000000 Z title: '2013,2034.258' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3583684&partId=1&searchText=2013,2034.258&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/70RmZtVt9Cy4Ameg0qOoCo/07832fd85c8ed2d2bbbb478c02bfddfc/2013_2034.258.jpg" caption: White-painted cattle. <NAME>, <NAME>. 2013,2034.258 © David Coulson/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3583684&partId=1&searchText=2013,2034.258&page=1 - sys: id: 6Vn3DoC1bOo4mwYwEeQMcq created_at: !ruby/object:DateTime 2015-11-25 14:20:38.415000000 Z updated_at: !ruby/object:DateTime 2015-11-25 14:20:38.415000000 Z content_type_id: chapter revision: 1 title_internal: 'Sudan: featured site, chapter 3' body: While cattle are ubiquitous, there are also frequent depictions of humans in various styles, as well as other domesticates, including goats and dogs. The herds of cattle clearly reflect a pastoralist existence for the artists, but there are also indications of hunting taking place, through engravings of wild antelope and dog figures, as well as many engravings of camels. - sys: id: 7ptm3SlsKQMOC4WsAsGyCm created_at: !ruby/object:DateTime 2015-11-25 14:17:47.704000000 Z updated_at: !ruby/object:DateTime 2017-01-09 17:16:39.272000000 Z content_type_id: image revision: 2 image: sys: id: 32GOdHizCwYKGAqO4sQ8oW created_at: !ruby/object:DateTime 2015-11-25 14:18:38.437000000 Z updated_at: !ruby/object:DateTime 2015-11-25 14:18:38.437000000 Z title: '2013,2034.335' description: url: "//images.ctfassets.net/xt8ne4gbbocd/32GOdHizCwYKGAqO4sQ8oW/d8a9b7309191ced7fff9c6db79174520/2013_2034.335.jpg" caption: Engraved camel figure. <NAME>, Jebel Uweinat 2013,2034.335 © David Coulson/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3586831&partId=1&searchText=2013,2034.335&page=1 - sys: id: 2OEaHI22BGKWWSWyyIQu6G created_at: !ruby/object:DateTime 2015-11-25 14:20:56.425000000 Z updated_at: !ruby/object:DateTime 2015-11-25 14:20:56.425000000 Z content_type_id: chapter revision: 1 title_internal: 'Sudan: featured site, chapter 4' body: This variety, and similarities to rock art sites elsewhere in the eastern Sahara, has led to conjecture and debate regarding the date and authorship of these depictions. Were the engravings and paintings made by the same people? Does the difference in drawing styles signify authorship by different cultures and at different times? The difficulties in objective dating of rock art make these questions difficult to answer, but it seems likely that there was a long tradition of painting and engraving here, with much of the ‘pastoralist’ rock art with cattle probably made between 5,000 and 7,000 years ago, some earlier styles possibly as much as 8,500 years ago, and other images such as camels made only about 2,000 years ago or less. - sys: id: 23kCbUF0EcEiGoYkkWWOGg created_at: !ruby/object:DateTime 2015-11-25 14:18:27.297000000 Z updated_at: !ruby/object:DateTime 2017-01-09 17:16:58.457000000 Z content_type_id: image revision: 2 image: sys: id: 3YBcXyxpbq6iKIegM66KgQ created_at: !ruby/object:DateTime 2015-11-25 14:18:38.604000000 Z updated_at: !ruby/object:DateTime 2015-11-25 14:18:38.604000000 Z title: '2013,2034.342' description: url: "//images.ctfassets.net/xt8ne4gbbocd/3YBcXyxpbq6iKIegM66KgQ/eb04e0be005fb0168817ddee5d4a742e/2013_2034.342.jpg" caption: Engraved animals (cattle?) and dogs. <NAME>, Jebel Uweinat 2013,2034.342 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3586930&partId=1&images=true&people=197356&museumno=2013,2034.342&page=1 - sys: id: 6XjTJyPnFuEkqeyWg2Mku created_at: !ruby/object:DateTime 2015-11-25 14:21:14.113000000 Z updated_at: !ruby/object:DateTime 2015-11-25 14:21:14.113000000 Z content_type_id: chapter revision: 1 title_internal: 'Sudan: featured site, chapter 5' body: Other than giraffes, the lack of large wild animals depicted (e.g. elephants) may indicate the climate to have been too dry for them, as during this time the area fluctuated in aridity, eventually becoming desert. There are, however, permanent springs at Jebel Uweinat and a more temperate microclimate here may have allowed pastoralists to subsist while the surrounding area became inhospitable. Indeed, despite its present remoteness, evidence suggests millennia of successive human presence, and as recently as the early 20th century, herders of the Toubou peoples were reported to be still living in the area. The camel engravings cannot be much older than 2,000 years, because camels were unknown in Africa before that, and the recent discovery of an ancient Egyptian hieroglyphic inscription from the Early Middle Kingdom serves to confirm that Jebel Uweinat has never really been ‘undiscovered’, despite having been unknown to Western geographers prior to the 20th century. - sys: id: erHhaJBDi0Mo4WYicGUAu created_at: !ruby/object:DateTime 2015-11-25 14:19:16.492000000 Z updated_at: !ruby/object:DateTime 2017-01-09 17:17:15.357000000 Z content_type_id: image revision: 2 image: sys: id: 4TbDKiBZ2wg8GaK6GqsMsa created_at: !ruby/object:DateTime 2015-11-25 14:18:38.589000000 Z updated_at: !ruby/object:DateTime 2015-11-25 14:18:38.589000000 Z title: '2013,2034.3918' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4TbDKiBZ2wg8GaK6GqsMsa/9354c9a992a51a4e896f67ac87fb4999/2013_2034.3918.jpg" caption: Engraved giraffes. <NAME>, Jebel Uweinat 2013,2034.3918 © David Coulson/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3586999&partId=1&images=true&people=197356&museumno=2013,2034.3918&page=1 background_images: - sys: id: 2FGW2NwJ2UOi0kMEcW6cc8 created_at: !ruby/object:DateTime 2015-12-07 20:09:20.521000000 Z updated_at: !ruby/object:DateTime 2015-12-07 20:09:20.521000000 Z title: '2013,2034.258' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2FGW2NwJ2UOi0kMEcW6cc8/b719e0e85ee7ecfce140d1db6b3581d0/2013_2034.258.jpg" - sys: id: 53gAYGjCEgYaksiuGkAkwc created_at: !ruby/object:DateTime 2015-12-07 20:09:20.503000000 Z updated_at: !ruby/object:DateTime 2015-12-07 20:09:20.503000000 Z title: '2013,2034.342' description: url: "//images.ctfassets.net/xt8ne4gbbocd/53gAYGjCEgYaksiuGkAkwc/1d799717cb2b19a599be9e95706e5e05/2013_2034.342.jpg" ---<file_sep>/_coll_country_information/chad-country-introduction.md --- contentful: sys: id: 9vW3Qgse2siOmgwqC80ia created_at: !ruby/object:DateTime 2015-11-26 15:14:49.211000000 Z updated_at: !ruby/object:DateTime 2015-12-07 13:40:13.544000000 Z content_type_id: country_information revision: 2 title: 'Chad: country introduction' chapters: - sys: id: 3mkFTqLZTO0WuMMQkIiAyy created_at: !ruby/object:DateTime 2015-11-26 15:05:47.745000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:05:47.745000000 Z content_type_id: chapter revision: 1 title: Introduction title_internal: 'Chad: country, chapter 1' body: 'Located in the centre of North Africa, landlocked Chad stretches from the Sahara Desert in the north to the savannah in the south. The country boasts thousands of rock engravings and paintings located in two main areas: the Ennedi Plateau and the Tibesti Mountains, both to the north. The depictions – the oldest of which date back to the fifth millennium BC – represent wild animals, cattle and human figures. Paintings of highly detailed riders on camels and horses are especially numerous, as are groups of people around huts. Chadian rock art is particularly well known for its variety of local styles, and it includes some of the richest examples of Saharan rock art.' - sys: id: 1BFShW54yQI6k6ksQcuYSE created_at: !ruby/object:DateTime 2015-11-26 14:55:32.628000000 Z updated_at: !ruby/object:DateTime 2015-11-26 14:55:32.628000000 Z content_type_id: image revision: 1 image: sys: id: 47ocQmZwI8iOE4Sskq8IeE created_at: !ruby/object:DateTime 2015-11-26 13:20:23.164000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:11:47.535000000 Z title: '2013,2034.6155' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3637041&partId=1&searchText=2013,2034.6155&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/47ocQmZwI8iOE4Sskq8IeE/8ce5836027971e7b02317274015177ac/2013_2034.6155.jpg" caption: Engravings of human figures from Niola Doa. Ennedi Plateau, Chad. 2013,2034.6155 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3637041&partId=1&people=197356&page=1 - sys: id: 6PPrV1eMH6u0scIwUiGGS2 created_at: !ruby/object:DateTime 2015-11-26 14:58:20.362000000 Z updated_at: !ruby/object:DateTime 2015-11-26 14:58:20.362000000 Z content_type_id: image revision: 1 image: sys: id: V66nfuesIoQGsMw2ugcwk created_at: !ruby/object:DateTime 2015-11-26 13:20:23.561000000 Z updated_at: !ruby/object:DateTime 2015-11-26 13:20:23.561000000 Z title: '2013,2034.6451' description: url: "//images.ctfassets.net/xt8ne4gbbocd/V66nfuesIoQGsMw2ugcwk/feb663001d1372a237275aa64bc471ed/2013_2034.6451.jpg" caption: Rider on a camel holding spear, dagger and shield. Camel Period, Ennedi Plateau, Chad. 2013,2034.6451 © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3641488&partId=1&searchText=2013,2034.6451&page=1 - sys: id: 7vX4pbFT3iCsEuQIqiq0gY created_at: !ruby/object:DateTime 2015-11-26 15:08:11.474000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:08:11.474000000 Z content_type_id: chapter revision: 1 title: Geography and rock art distribution title_internal: 'Chad: country, chapter 2' body: 'The north-south orientation of Chad''s elongated shape means it is divided into several different climatic zones: the northern part belongs to the Sahara Desert, while the central area is included in the Sahel border (the semi-arid region south of the Sahara). The southern third of the country is characterized by a more fertile savannah. The Ennedi Plateau and Tibesti mountains contain thousands of pieces of rock art, including some of the most famous examples in the Sahara. The Ennedi Plateau is located at the north-eastern corner of Chad, on the southern edge of the Sahara Desert. It is a sandstone massif carved by erosion in a series of superimposed terraces, alternating plains and ragged cliffs crossed by wadis (seasonal rivers). Unlike other areas in the Sahara with rock art engravings or paintings, the Ennedi Plateau receives rain regularly – if sparsely – during the summer, making it a more benign environment for human life than other areas with significant rock art to the north, such as the Messak plateau or the Tassili Mountains in Libya and Algeria.' - sys: id: h6vM4an4K42COIiQG8A6y created_at: !ruby/object:DateTime 2015-11-26 14:59:35.937000000 Z updated_at: !ruby/object:DateTime 2017-01-09 17:10:44.651000000 Z content_type_id: image revision: 2 image: sys: id: 401K6ww8asemkaCySqeci created_at: !ruby/object:DateTime 2015-11-26 13:20:23.173000000 Z updated_at: !ruby/object:DateTime 2015-11-26 13:20:23.173000000 Z title: '2013,2034.6322' description: url: "//images.ctfassets.net/xt8ne4gbbocd/401K6ww8asemkaCySqeci/9c64bd46729be1bcc2c4a0a8fdd61a1c/2013_2034.6322.jpg" caption: View of the semi-desert plain surrounding the Ennedi Plateau (seen in the background). 2013,2034.6770 © TARA/<NAME> col_link: http://bit.ly/2jvhIgV - sys: id: 31nXCnwZBC0EcoEAuUyOqG created_at: !ruby/object:DateTime 2015-11-26 15:08:48.316000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:08:48.316000000 Z content_type_id: chapter revision: 1 title_internal: 'Chad: country, chapter 3' body: 'The Tibesti Mountains are situated at the north-western corner of Chad, and partly extend into Libya. The central area of the Tibesti Mountains is volcanic in origin, with one third of the range covered by five volcanoes. This has resulted in vast plateaux as well as fumaroles, sulphur and natron deposits and other geological formations. The erosion has shaped large canyons where wadis flow irregularly, and where most of the rock art depictions are situated. Paintings and engravings are common in both regions: the former are more often found in the Ennedi Plateau; the latter are predominant in the Tibesti Mountains.' - sys: id: 5g8chby9ugKc6igkYYyW6q created_at: !ruby/object:DateTime 2015-11-26 15:00:20.104000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:00:20.104000000 Z content_type_id: image revision: 1 image: sys: id: 1AS5ngxVRGWeAaKemYyOyo created_at: !ruby/object:DateTime 2015-11-26 13:20:23.225000000 Z updated_at: !ruby/object:DateTime 2015-11-26 13:20:23.225000000 Z title: '2013,2034.7259' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1AS5ngxVRGWeAaKemYyOyo/ab561407686a2a37d59602f6b05978d3/2013_2034.7259.jpg" caption: View of the Tibesti Mountains. 2013,2034.7259 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3655202&partId=1&searchText=2013,2034.7259&page=1 - sys: id: 1YrTJ2zm4ow64uAMcWUI4c created_at: !ruby/object:DateTime 2015-11-26 15:10:44.568000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:10:44.568000000 Z content_type_id: chapter revision: 1 title: Research history title_internal: 'Chad: country, chapter 4' body: |- Different areas of Chad have been subject to varying trajectories of research. In the Tibesti Mountains, rock art was known to Europeans as early as 1869, although it was between the 1910s and 1930s that the first studies started to be carried out, by <NAME>. However, the main boost in research came in the 1950s and 1960s thanks to the work of <NAME>. Over the last 50 years, researchers have found thousands of depictions throughout the region, most of them engravings, although paintings are also well represented. In the case of the Ennedi Plateau, its isolated position far from the main trade routes made its rock art unknown outside the area until the 1930s. During this decade, Burthe d’Annelet brought attention to the art, and De Saint-Floris published the first paper on the subject. The main effort to document this rock art came in 1956-1957, when <NAME> recorded more than 500 sites in only a sixth of the plateau's entire area. - sys: id: 7jc13ulbagcQmq0YKUQqwu created_at: !ruby/object:DateTime 2015-11-26 15:11:09.168000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:11:09.168000000 Z content_type_id: chapter revision: 1 title: Themes title_internal: 'Chad: country, chapter 5' body: As in the rest of the Sahara, the main themes in Chadian rock art are directly linked to the chronology. The oldest depictions are of wild animals, but most common are later scenes with cattle, huts and people. As in other areas of the Sahara, the most recent depictions correspond to battle scenes of riders on horses and camels. Along with these main subjects, both areas have examples of very detailed scenes of daily life and human activities, including people playing music, visiting the sick or dancing. The rock art of both the Ennedi Plateau and the Tibesti regions is characterized by the existence of a variety of local styles, such as the so-called ‘Flying Gallop style’, sometimes simultaneous, sometimes successive. This variability means an enormous richness of techniques, themes and artistic conventions, with some of the most original styles in Saharan rock art. - sys: id: 5h4CpUNMty4WiYiK0uOu2g created_at: !ruby/object:DateTime 2015-11-26 15:00:58.853000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:00:58.853000000 Z content_type_id: image revision: 1 image: sys: id: Z50lrTE2EUM0egk4Mk482 created_at: !ruby/object:DateTime 2015-11-26 13:20:23.161000000 Z updated_at: !ruby/object:DateTime 2015-11-26 13:20:23.161000000 Z title: '2013,2034.6732' description: url: "//images.ctfassets.net/xt8ne4gbbocd/Z50lrTE2EUM0egk4Mk482/ddfe4ed0c368ef757168f583aac8bb4b/2013_2034.6732.jpg" caption: Village scene showing people, cattle and huts or tents. To the right, three women are seated around a fourth (possibly sick) woman lying on a blanket or mattress. Ennedi Plateau. 2013,2034.6732 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3639846&partId=1&searchText=2013,2034.6732&page=1 - sys: id: 4mRjWNwKj6myyi8GGG06uC created_at: !ruby/object:DateTime 2015-11-26 15:01:28.260000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:01:28.260000000 Z content_type_id: image revision: 1 image: sys: id: 6uYaJrzaMgAwK42CSgwcMW created_at: !ruby/object:DateTime 2015-11-26 13:20:23.253000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:12:19.070000000 Z title: '2013,2034.6595' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3640375&partId=1&searchText=2013,2034.6595&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/6uYaJrzaMgAwK42CSgwcMW/b71fe481a99fa36b16f32265828a440e/2013_2034.6595.jpg" caption: Raiding scene with horses in the so-called ‘Flying gallop’ style. Camel Period. 2013,2034.6595 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3640375&partId=1&searchText=2013,2034.6595&page=1 - sys: id: 1KHUsTtlL64uMK48KsySek created_at: !ruby/object:DateTime 2015-11-26 15:11:36.258000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:11:36.258000000 Z content_type_id: chapter revision: 1 title: Chronology title_internal: 'Chad: country, chapter 6' body: |- The oldest engravings in Chad are more recent than those to the north, having started to appear in the 5th to 4th millennia BC, and can be broadly divided into three main periods: The oldest is the so-called Archaic Period, characterized by wild animals in the Ennedi Plateau and Round Head-style figures in the Tibesti Mountains, similar to those found in the Central Sahara. The second phase is named the Bovine or Pastoral Period, when domestic cattle are the predominant animals, and a third, late period named the Dromedary or Camel Period. Unlike other areas in the Sahara, horse and camel depictions appear to be from roughly the same period (although horses were introduced to the Sahara first), so they are included in a generic Camel Period. The end of the rock art tradition in both areas is difficult to establish, but it seems to have lasted at least until the seventeenth century in the Ennedi Plateau, much longer than in other areas of the Sahara. - sys: id: gzoaZ2DMHegIuqy4e84cO created_at: !ruby/object:DateTime 2015-11-26 15:01:55.122000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:01:55.122000000 Z content_type_id: image revision: 1 image: sys: id: 4tdnKRONuECgKUm66woS2M created_at: !ruby/object:DateTime 2015-11-26 13:20:23.585000000 Z updated_at: !ruby/object:DateTime 2015-11-26 13:20:23.585000000 Z title: '2013,2034.6807' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4tdnKRONuECgKUm66woS2M/07c3ea3b18caacafd79db6f2ea6c2c88/2013_2034.6807.jpg" caption: Depiction of human figures infilled with dots. Another human figure infilled in white and facing forwards is depicted at the top right of the tableau. Archaic Period, Ennedi Plateau. 2013,2034.6807 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3642807&partId=1&searchText=2013,2034.6807&page=1 - sys: id: Pgpnd2dYiqqS2yQkookMm created_at: !ruby/object:DateTime 2015-11-26 15:02:31.184000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:02:31.184000000 Z content_type_id: image revision: 1 image: sys: id: 5PmKmAsIH6OO8eyuOYgUa2 created_at: !ruby/object:DateTime 2015-11-26 13:20:27.673000000 Z updated_at: !ruby/object:DateTime 2015-11-26 13:20:27.673000000 Z title: '2013,2034.7610' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5PmKmAsIH6OO8eyuOYgUa2/650f01d3f303f5f062321384b36c9943/2013_2034.7610.jpg" caption: Frieze of engraved cattle. Tibesti Mountains, Pastoral Period. 2013,2034.7610 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3654657&partId=1&searchText=2013,2034.7610&page=1 - sys: id: 7MvpMnChjiKIwgSC0kgiEW created_at: !ruby/object:DateTime 2015-11-26 15:03:01.760000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:03:01.760000000 Z content_type_id: image revision: 1 image: sys: id: 6weCWSE3EkyIcyWW4S8QAc created_at: !ruby/object:DateTime 2015-11-26 13:20:23.260000000 Z updated_at: !ruby/object:DateTime 2015-11-26 13:20:23.260000000 Z title: '2013,2034.6373' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6weCWSE3EkyIcyWW4S8QAc/a469e0c984f2824f23cefa7773ffc075/2013_2034.6373.jpg" caption: White rider on a horse from the latest period of the Ennedi Plateau rock art. The figure is superimposed on several red cows of the previous Pastoral Period. Ennedi Plateau. 2013,2034.6373 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3639421&partId=1&searchText=2013,2034.6373&page=1 citations: - sys: id: 4I9BcFZSWsesgIMUwwoQ2k created_at: !ruby/object:DateTime 2015-11-26 13:21:04.168000000 Z updated_at: !ruby/object:DateTime 2015-11-26 13:21:04.168000000 Z content_type_id: citation revision: 1 citation_line: |- <NAME> (1997). *Art rupestre en Ennedi. Looking for rock paintings and engravings in the Ennedi Hills* Sépia, Saint-Maur <NAME>., <NAME>. and <NAME>. (1994). *Niola Doa, ‘il luogo delle fanciulle’ (Ennedi, Ciad)* Sahara 6: pp.51-63 ---<file_sep>/_coll_country/tanzania/kolo.md --- breadcrumbs: - label: Countries url: "../../" - label: 'Tanzania ' url: "../" layout: featured_site contentful: sys: id: 1MRBSR83yUwGoo8s4AKICk created_at: !ruby/object:DateTime 2016-07-27 07:45:12.791000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:45:12.791000000 Z content_type_id: featured_site revision: 1 title: Kolo, Tanzania slug: kolo chapters: - sys: id: 1NISbAVcjSMI4SEWE8WgAm created_at: !ruby/object:DateTime 2016-07-27 07:45:19.053000000 Z updated_at: !ruby/object:DateTime 2016-07-27 14:24:34.308000000 Z content_type_id: chapter revision: 2 title: '' title_internal: Kolo Chapter 1 body: The Kondoa rock art sites are located on the eastern slopes of the Maasai escarpment, which borders the western side of the Great Rift Valley in central Tanzania, covering an area of over 2,336 km². Stretching for around 18 km along the escarpment, the exact number of rock art sites in the Kondoa area is unknown but is estimated to be up to 450, the oldest of which are thought be more than 2,000 years old. The extensive and spectacular collection of rock paintings are attributable to both hunter-gatherer and pastoralist communities and the images are testament to the changing socio-economic environment in the region. The hunter-gatherer rock paintings of Kondoa are dominated by human figures and animals. While a dark reddish brown predominates, other colours include yellow, orange, red and white. Some of the shelters are still considered to have cultural associations with the people who live nearby, reflecting their beliefs, rituals and cosmological traditions. In 2006, Kondoa was nominated and listed as one of UNESCO’s World Heritage rock art sites in Africa. - sys: id: 2e0bNc68UUM0YKaM40Sm4C created_at: !ruby/object:DateTime 2016-07-27 07:45:11.871000000 Z updated_at: !ruby/object:DateTime 2017-01-24 15:57:32.216000000 Z content_type_id: image revision: 2 image: sys: id: 4qqgpg1KTmKwEA8kQsg8Qe created_at: !ruby/object:DateTime 2016-07-27 07:46:35.056000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:35.056000000 Z title: TANKON0030027 jpeg edited-1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/4qqgpg1KTmKwEA8kQsg8Qe/1d8fb417f4142acaf65be18c6c6b8ea0/TANKON0030027_jpeg_edited-1.jpg" caption: View looking out over Kondoa landscape. 2013,2034.16829 © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3709780&partId=1&searchText=2013,2034.16829&page=1 - sys: id: 5WqTYb2ohiCaseea44yMWg created_at: !ruby/object:DateTime 2016-07-27 07:45:19.050000000 Z updated_at: !ruby/object:DateTime 2016-07-27 14:22:52.499000000 Z content_type_id: chapter revision: 2 title: '' title_internal: 'Kolo Chapter 2 ' body: "The sites at Kolo are the most famous of the Kondoa paintings. Kolo comprises three rock art sites, known as Kolo 1, 2 and 3. The main site, Kolo 1 (known locally as Mongomi wa Kolo) is a large, imposing rock shelter that is only accessible by following a winding path at the end of a dirt road. This site contains many fine-line red paintings, some of which are very faded; but the site is still used by the local community for secret rituals. Kolo 2 is located south of the main site and includes human and animal figures, while Kolo 3 is north of Kolo1 and is characterised by human, animal and geometric figures. The renowned palaeontologist <NAME> surveyed and documented many of the paintings at Kolo in the 1950s. \ The examples we see here are thought to have been made by early hunter-gatherer groups, ancestors of the modern Sandawe, one of the first cultural groups to inhabit Kondoa. \n\n" - sys: id: 5JuWPWO5Z6w8aeeWMqQ8oK created_at: !ruby/object:DateTime 2016-07-27 07:45:11.850000000 Z updated_at: !ruby/object:DateTime 2017-01-24 15:58:56.845000000 Z content_type_id: image revision: 2 image: sys: id: 6hDS1W5bdSYICYEse20Wuw created_at: !ruby/object:DateTime 2016-07-27 07:46:35.991000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:35.991000000 Z title: TANKON0030032 jpeg edited-1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6hDS1W5bdSYICYEse20Wuw/48e981adce78ac63fc6ec12701fa5145/TANKON0030032_jpeg_edited-1.jpg" caption: Three slender figures with elongated bodies wearing elaborate curved feather-like headdresses. Kolo 1, Kondoa, Tanzania. 2013,2034.16832 © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3709777&partId=1&searchText=2013,2034.16832&page=1 - sys: id: 1o3g8TuJuc8MiGyQ6g6g42 created_at: !ruby/object:DateTime 2016-07-27 07:45:18.949000000 Z updated_at: !ruby/object:DateTime 2016-07-27 14:23:12.269000000 Z content_type_id: chapter revision: 2 title: '' title_internal: Kolo Chapter 3 body: "__Art__\n\nAmong the animals depicted are elephants, giraffes, antelopes, eland, rhinoceros and wildebeest; while human figures are represented as slender and elongated, often with elaborate hairstyles or headdresses, holding bows and arrows. Groups of figures are also shown bent at the waist, with some appearing to take on animal characteristics. These paintings have been associated with Sandawe cultural beliefs. \n\nThe Sandawe communicate with the spirits by taking on the power of an animal and some features at Mongomi wa Kolo can be understood by reference to the Sandawe traditional practice known as simbó (Ten Raa 1971, 1974). Developing Ten Raa’s observations, Lewis-Williams (1986) proposed that simbó is the ritual of being a lion, and that simbó dancers are believed to turn into lions. Lim (1992, 1996) adopted a site-specific approach to the rock art and has suggested that the importance of place is as important as the images themselves. According to Lim the potency of a place is produced through ritual activities, so that meaning resides in the process of painting in a particular location, rather than in the painted image itself. \n" - sys: id: 2H6WyW8gaISq2KgkCGa2k0 created_at: !ruby/object:DateTime 2016-07-27 07:45:18.861000000 Z updated_at: !ruby/object:DateTime 2017-01-24 16:05:45.603000000 Z content_type_id: chapter revision: 5 title_internal: Kolo chapter 4 body: |+ Ritual Practices Ritual sites are generally located near fig and baobab trees, and springs. However, about 3 m south of the main Kolo shelter, a cavity underneath a huge boulder is used, even today, by local diviners, healers and rainmakers to invoke visions and communicate with the spirits. Oral traditions indicate that Mongomi wa Kolo is considered more powerful than other ritual places in Kondoa, and its unusual location may contribute to its efficacy. The other two shelters of Kolo 2 and 3 are also used for ritual ceremonies. - sys: id: 5gBuZ4nsoo4M2QOoCOs8Cs created_at: !ruby/object:DateTime 2016-07-27 07:45:14.737000000 Z updated_at: !ruby/object:DateTime 2017-01-24 16:06:33.160000000 Z content_type_id: image revision: 3 image: sys: id: 6HJM4veidyg8KAO6WsaOcc created_at: !ruby/object:DateTime 2016-07-27 07:46:35.269000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:35.269000000 Z title: TANKON0030008 jpeg edited-1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6HJM4veidyg8KAO6WsaOcc/85bf74728415037376fb5eca97f3f527/TANKON0030008_jpeg_edited-1.jpg" caption: Group of five figures, one with animal-like head and grazing antelope on the left. Kolo 1, Kondoa, Tanzania. 2013,2034.16820 © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3709705&partId=1&searchText=2013,2034.20311+&images=true&people=197356&museumno=2013,2034.16819&page=1 - sys: id: 4dRHbbM4IU0MQog4kuOCGY created_at: !ruby/object:DateTime 2016-07-27 07:45:18.820000000 Z updated_at: !ruby/object:DateTime 2016-07-27 14:23:50.727000000 Z content_type_id: chapter revision: 2 title: '' title_internal: Kolo chapter 5 body: |- __Conservation__ When <NAME> was surveying the Kondoa rock paintings in 1983 she predicted that if serious preservation and conservation measures were not put in place the paintings would be destroyed by 2020. Although inscribed onto the UNESCO World Heritage List in 2006, it has been noted paintings are being destroyed by the dust from the ground and in some cases rainwater is causing the paintings to deteriorate. - sys: id: 5SJRvFQ6NasOKwWYogwWqM created_at: !ruby/object:DateTime 2016-07-27 07:45:11.820000000 Z updated_at: !ruby/object:DateTime 2017-01-24 16:07:01.378000000 Z content_type_id: image revision: 2 image: sys: id: 27ttIF1VA4e8ekcAcea4G6 created_at: !ruby/object:DateTime 2016-07-27 07:46:35.042000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:35.042000000 Z title: TANKON0030014 jpeg edited-1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/27ttIF1VA4e8ekcAcea4G6/d705e5dbf518d996376eed7193eb1ae2/TANKON0030014_jpeg_edited-1.jpg" caption: Panel of slender red figures with elongated bodies, showing large figure bent at waist. Kolo 1, Kondoa, Tanzania. 2013,2034.16824 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3709771&partId=1&searchText=2013,2034.16824&page=1 - sys: id: 2O7PwT55ZmSSgsWkeEAQsq created_at: !ruby/object:DateTime 2016-07-27 07:45:18.796000000 Z updated_at: !ruby/object:DateTime 2016-07-27 09:51:08.628000000 Z content_type_id: chapter revision: 3 title: '' title_internal: Kolo Chapter 6 body: |+ Moreover, the documentation of paintings at Kondoa is incomplete, and some areas have not been surveyed at all. Bwasiri (2008) advocates an urgent need to collate all existing information in this region and implement a sites and monuments record that also takes into account living heritage values. - sys: id: 4xFpVDUn2EA8c0k2WWGaaK created_at: !ruby/object:DateTime 2016-07-27 07:45:11.820000000 Z updated_at: !ruby/object:DateTime 2017-01-24 16:07:17.252000000 Z content_type_id: image revision: 2 image: sys: id: 4eWYwHYojCu0EIYyoQGgMI created_at: !ruby/object:DateTime 2016-07-27 07:46:37.039000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:37.039000000 Z title: TANKON0030085 jpeg description: url: "//images.ctfassets.net/xt8ne4gbbocd/4eWYwHYojCu0EIYyoQGgMI/4b39bad47efe37b9e6d0ab830c823649/TANKON0030085_jpeg.jpg" caption: Painted panel damaged by water seepage. Kolo 1, Kondoa, Tanzania. 2013,2034.16876 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3709830&partId=1&searchText=2013,2034.16876&page=1 citations: - sys: id: 4khc2F5ABWm0kyKoUooa80 created_at: !ruby/object:DateTime 2016-07-27 07:45:18.097000000 Z updated_at: !ruby/object:DateTime 2016-07-27 09:56:15.212000000 Z content_type_id: citation revision: 3 citation_line: "Bwasiri, E.J 2008. 'The Management of Indigenous Heritage: A Case Study of Mongomi wa Kolo Rock Shelter, Central Tanzania'. MA Dissertation, University of the\nWitwatersrand \n\nLeakey, M. 1983. *Africa’s Vanishing Art – The Rock Paintings of Tanzania.* London, Hamish Hamilton Ltd.\n\nLewis-Williams, J.D. 1986. ‘Beyond Style and Portrait: A Comparison of Tanzanian\nand Southern African Rock Art’. *Contemporary Studies on Khoisan 2*. Hamburg, Helmut Buske Verlag\n\nLim, I.L. 1992. ‘A Site-Oriented Approach to Rock Art: a Study from Usandawe, Central Tanzania’. PhD Thesis, University of Michigan\n\nTen Raa, E. 1971. ‘Dead Art and Living Society: A Study of Rock paintings in a Social Context’. *Mankind* 8:42-58\n\nTen Raa, E. 1974. ‘A record of some prehistoric and some recent Sandawe rock paintings’. *Tanzania Notes and Records* 75:9-27\n" background_images: - sys: id: 6cqE0uH6mswkKcOkWA6waC created_at: !ruby/object:DateTime 2016-07-27 07:46:32.004000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:32.004000000 Z title: TANKON0030029 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6cqE0uH6mswkKcOkWA6waC/7e3e2d492733456ba58f56ccbf8e5bac/TANKON0030029.jpg" - sys: id: DiswAHlgIgmsgEMUiQYm4 created_at: !ruby/object:DateTime 2016-07-27 07:46:32.111000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:32.111000000 Z title: TANKON0030077 description: url: "//images.ctfassets.net/xt8ne4gbbocd/DiswAHlgIgmsgEMUiQYm4/a68c86b9a0f96c2c658570a581af71f3/TANKON0030077.jpg" ---<file_sep>/_pages/thematic.md --- layout: thematic_index permalink: /thematic/ title: Themes collection: coll_thematic ---<file_sep>/_coll_country/libya.md --- contentful: sys: id: 5s1jlhJi6W0U0QcE4moqs4 created_at: !ruby/object:DateTime 2015-11-26 18:51:28.567000000 Z updated_at: !ruby/object:DateTime 2018-05-17 16:51:13.201000000 Z content_type_id: country revision: 12 name: Libya slug: libya col_url: http://www.britishmuseum.org/research/collection_online/search.aspx?people=197356&place=37611 map_progress: true intro_progress: true image_carousel: - sys: id: 5WH8hIWyZOI0QWe0SyAkC8 created_at: !ruby/object:DateTime 2015-11-25 15:23:42.337000000 Z updated_at: !ruby/object:DateTime 2017-12-15 14:08:22.574000000 Z title: '2013,2034.2756' description: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3584749 url: "//images.ctfassets.net/xt8ne4gbbocd/5WH8hIWyZOI0QWe0SyAkC8/69ac9764bc2af640ff92531ee90422a4/2013_2034.2756.jpg" - sys: id: 16a6qAimaaWYqcwqUqMKIm created_at: !ruby/object:DateTime 2015-11-26 12:25:03.860000000 Z updated_at: !ruby/object:DateTime 2017-12-15 14:15:08.336000000 Z title: '2013,2034.420' description: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3580676 url: "//images.ctfassets.net/xt8ne4gbbocd/16a6qAimaaWYqcwqUqMKIm/35056fde196c5ae13894c78ed1b5fe17/2013_2034.420.jpg" - sys: id: 4eOnyF3wVymkGMgOkmQsYm created_at: !ruby/object:DateTime 2015-11-26 12:25:07.169000000 Z updated_at: !ruby/object:DateTime 2017-12-15 14:28:23.158000000 Z title: '2013,2034.3106' description: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3586141 url: "//images.ctfassets.net/xt8ne4gbbocd/4eOnyF3wVymkGMgOkmQsYm/ef9fa1bb02dc7c8ddb0ced9c9fcaa85e/2013_2034.3106.jpg" - sys: id: xe9mLFNrG0Ga6yUIoQycG created_at: !ruby/object:DateTime 2015-11-25 15:23:42.433000000 Z updated_at: !ruby/object:DateTime 2017-12-15 14:29:10.261000000 Z title: '2013,2034.2761' description: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3584758 url: "//images.ctfassets.net/xt8ne4gbbocd/xe9mLFNrG0Ga6yUIoQycG/de7f087f96da7f9814d89ce25c7c4b44/2013_2034.2761.jpg" featured_site: sys: id: 5tEidWPQmAyy22u8wGEwC4 created_at: !ruby/object:DateTime 2015-11-25 15:32:46.632000000 Z updated_at: !ruby/object:DateTime 2015-12-07 20:53:06.792000000 Z content_type_id: featured_site revision: 3 title: Fighting cats, Libya slug: fighting-cats chapters: - sys: id: 1Bkxdxu3Pay6SEYMy8s08e created_at: !ruby/object:DateTime 2015-11-25 15:27:52.971000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:27:52.971000000 Z content_type_id: chapter revision: 1 title_internal: 'Libya: featured site, chapter 1' body: Running from the Red Sea to the Atlantic Ocean, the Sahara is by far the world's largest hot desert. It covers over 3,500,000 square miles (9,000,000 sq. km), a tenth of the whole African Continent. Yet we know it was not always so. Archaeological and geological research has shown that the Sahara has undergone major climatic changes since the end of the last Ice Age (c. 10,000 BC). During this period, rain was far more abundant, and vast areas of the current desert were a savannah. By around 4,200 BC, changes in the rainfall and seasonal patterns led to a gradual desertification of the Sahara into an arid expanse. The analysis of archaeological sites, animal bones and preserved vegetal remains tell us of a greener world, where some of the earliest attempts at domestication of animals and rudimentary farming took place. - sys: id: 1bjII0uFguycUGI0skGqS2 created_at: !ruby/object:DateTime 2015-11-25 15:24:17.896000000 Z updated_at: !ruby/object:DateTime 2017-01-09 14:44:36.006000000 Z content_type_id: image revision: 2 image: sys: id: 23Sckf5aOU4E8WOkg8yoIG created_at: !ruby/object:DateTime 2015-11-25 15:23:42.352000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:23:42.352000000 Z title: '2013,2034.2555' description: url: "//images.ctfassets.net/xt8ne4gbbocd/23Sckf5aOU4E8WOkg8yoIG/5ad5ab2517694ac7ebacdd58be96b254/2013_2034.2555.jpg" caption: 'View of the now dried-up riverbed at Wadi Mathendous, Messak Settafet, Libya. 2013,2034.2555 © <NAME>/TARA ' col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?assetId=1494150&objectId=3579237&partId=1 - sys: id: 4eUSc4QsRW2Mey02S8a2IM created_at: !ruby/object:DateTime 2015-11-25 15:28:11.936000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:28:11.936000000 Z content_type_id: chapter revision: 1 title_internal: 'Libya: featured site, chapter 2' body: |- Little is known about the people who lived in the Sahara thousands of years ago; however, through rock art, we can discern who they may have been and what images were important to them. Throughout the desert, rock art engravings and paintings depict an earlier story of the Sahara: the wild animals that lived there; the cattle herds that provided food and labour; their daily activities and beliefs are all displayed in caves and cliffs, valleys or plateaus. The Messak Settafet is one of these places. Situated in the Sahara, it is a large plateau running southwest to northeast through the Libyan province of Fezzan, near the borders of Algeria and Niger. Both plateaus are crossed by numerous wadis (dry riverbeds) that run to the east, flanked by cliffs filled with tens of thousands of rock art depictions, including some of the oldest engravings in the Sahara. Rich with depictions of the savannah, the rock art shows buffaloes, crocodiles, ostriches or hippopotami, all of which tells us of a wetter Sahara thousands of years ago. It is difficult to determine the motives of the people that created these images. There are many theories about why these people created rock art, what exactly is depicted and what the images meant to that group. One area of particular research interest is the depiction of mythical beings, therianthropic figures (part human part animal) and anthropomorphic animals (the personification of animals in human forms). Were these religious images? Cultural folklore? Or simply images pleasing to a group or culture? - sys: id: 6ggzCnM132qAMoMao64uG4 created_at: !ruby/object:DateTime 2015-11-25 15:25:04.359000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:25:04.359000000 Z content_type_id: image revision: 1 image: sys: id: xe9mLFNrG0Ga6yUIoQycG created_at: !ruby/object:DateTime 2015-11-25 15:23:42.433000000 Z updated_at: !ruby/object:DateTime 2017-12-15 14:29:10.261000000 Z title: '2013,2034.2761' description: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3584758 url: "//images.ctfassets.net/xt8ne4gbbocd/xe9mLFNrG0Ga6yUIoQycG/de7f087f96da7f9814d89ce25c7c4b44/2013_2034.2761.jpg" caption: Frontal view of the Fighting Cats. Wadi Mathendous, Messak Settafet, Libya. 2013,2034.2761 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3584758&partId=1&museumno=2013,2034.2761&page=1 - sys: id: DcfkeeG0wKKEIAMACYiOY created_at: !ruby/object:DateTime 2015-11-25 15:28:29.814000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:28:29.814000000 Z content_type_id: chapter revision: 1 title_internal: 'Libya: featured site, chapter 3' body: 'Deep in the Messak Settafet is a site that has intrigued researchers for decades: the image known as ‘Fighting Cats’. This iconic engraving shows two confronted, long-tailed figures standing on their hindquarters, with legs and arms partially outstretched against each other, as if fighting. The engravings are placed on an outcrop, as if they were looking down across the rest of the wadi, with several other engravings acting as milestones leading up to them. They are in an imposing position overlooking the valley.' - sys: id: 5OhCYs4J4Q0cWSgwEWUSSU created_at: !ruby/object:DateTime 2015-11-25 15:25:43.199000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:25:43.199000000 Z content_type_id: image revision: 1 image: sys: id: 3UCMJpOah2ayA8keMYsGkU created_at: !ruby/object:DateTime 2015-11-25 15:23:42.353000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:23:42.353000000 Z title: '2013,2034.2740' description: url: "//images.ctfassets.net/xt8ne4gbbocd/3UCMJpOah2ayA8keMYsGkU/eb104c365e0f4a5e3b5f792bde70cb3d/2013_2034.2740.jpg" caption: Sandstone cliffs, with the Fighting Cats faintly visible at the top. <NAME>, <NAME>, Libya. 2013,2034.2740 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3584701&partId=1&museumno=2013,2034.2740&page=1 - sys: id: 3aWDA5PA5is0yS4uQSKweS created_at: !ruby/object:DateTime 2015-11-25 15:28:48.305000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:29:09.496000000 Z content_type_id: chapter revision: 2 title_internal: 'Libya: featured site, chapter 4' body: The technical quality of the engravings is exceptional, with deeply outlined and carefully polished bodies and carved cupules within their heads to depict eyes. Claws were also marked, maybe to reinforce the idea of fighting. The specific type of animal depicted is subject to debate among scholars. Some have described them as monkeys or mythological blends of monkeys and men. Their pointed ears could also identify them as cat-like figures, although most probably they were the representation of mythical beings, considering their prominence above all other figures in this area. A polished line comes out from the waist of both figures to join four small ostriches, depicted between them, which often accompany rock art in this region. - sys: id: 2hR3so8KWQKAWS0oqWiGKm created_at: !ruby/object:DateTime 2015-11-25 15:26:11.459000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:26:11.459000000 Z content_type_id: image revision: 1 image: sys: id: 5WH8hIWyZOI0QWe0SyAkC8 created_at: !ruby/object:DateTime 2015-11-25 15:23:42.337000000 Z updated_at: !ruby/object:DateTime 2017-12-15 14:08:22.574000000 Z title: '2013,2034.2756' description: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3584749 url: "//images.ctfassets.net/xt8ne4gbbocd/5WH8hIWyZOI0QWe0SyAkC8/69ac9764bc2af640ff92531ee90422a4/2013_2034.2756.jpg" caption: General view of the Fighting Cats showing nearby engravings. <NAME>, <NAME>, Libya. 2013,2034.2756 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3584749&partId=1&museumno=2013,2034.2756&page=1 - sys: id: smcYmLtACOMwSYasYoYI0 created_at: !ruby/object:DateTime 2015-11-25 15:29:29.887000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:29:29.887000000 Z content_type_id: chapter revision: 1 title: title_internal: 'Libya: featured site, chapter 5' body: Several other engravings are found throughout the wadi. In its lower part to the right, another cat-like or monkey figure has been depicted, although in this case it has only been outlined. A small, unidentified quadruped has been represented to the left of its head. At the right side of the boulder, a fourth figure has been depicted, almost identical to those of the main scene, but with part of its arms unpolished, as if left unfinished. - sys: id: 6oRVe3BTckeksmGWA8gwyq created_at: !ruby/object:DateTime 2015-11-25 15:26:47.347000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:26:47.347000000 Z content_type_id: image revision: 1 image: sys: id: 1xfjGHyp6wMGQuKQikCeMo created_at: !ruby/object:DateTime 2015-11-25 15:23:42.353000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:23:42.353000000 Z title: '2013,2034.2768' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1xfjGHyp6wMGQuKQikCeMo/46389e1547a0da49bc8ed43c897e1f8a/2013_2034.2768.jpg" caption: Detail of engraved woman inside cat to the right. <NAME>, <NAME>, Libya. 2013,2034.2768 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3584772&partId=1&museumno=2013,2034.2768&page=1 - sys: id: 2T0VuynIPK2CYgyck6uSK8 created_at: !ruby/object:DateTime 2015-11-25 15:29:50.338000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:29:50.338000000 Z content_type_id: chapter revision: 1 title_internal: 'Libya: featured site, chapter 6' body: Besides its impressive position in the landscape, their expressivity and complex interpretation, the Fighting Cats keep a secret within. On the polished body of the figure to the left a small, delicate figure of a woman was shallowly engraved. Hair, fingers and breasts were carefully depicted, as well as an unidentified symbol placed at the bottom of the figure, which could have a fertility-related meaning. The difference in style and technique may point to the woman as a later addition to the panel, taking advantage of the polished surface, but respecting the main scene. - sys: id: 3aPHfOC1lSUW68GuUkOAQK created_at: !ruby/object:DateTime 2015-11-25 15:27:21.916000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:27:21.916000000 Z content_type_id: image revision: 1 image: sys: id: 1kO0IImYVGOk0oeQg6sqWm created_at: !ruby/object:DateTime 2015-11-25 15:23:42.352000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:23:42.352000000 Z title: '2013,2034.2769' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1kO0IImYVGOk0oeQg6sqWm/631f5025d103fadbbcd966634cddc15f/2013_2034.2769.jpg" caption: Second pair of fighting cats. Wadi Mathendous, Messak Settafet, Libya. 2013,2034.2769 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3584770&partId=1&museumno=2013,2034.2769&page=1 - sys: id: 6GXWm1a2LSU0qg0iQEIeGw created_at: !ruby/object:DateTime 2015-11-25 15:30:37.290000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:30:37.290000000 Z content_type_id: chapter revision: 1 title_internal: 'Libya: featured site, chapter 7' body: |- Another example of fighting cats has been found nearby, although it is neither so carefully made nor in such a prominent place. The similarity is, however, astonishing, and we may wonder if this second pair of beings could be a copy of the first pair, thus reflecting its symbolic importance in the people’s collective imagination. As is often the case with rock art, the interpretation of these images remains up for discussion. Given the care taken to engrave the images, their technical quality and their dominant position in the landscape, we can gather that these images potentially had deep meaning for the people who created them thousands of years ago, and were possibly meant to be a symbolic as well as a physical landmark for travellers and local people alike. Although the original purpose and meaning have long since been lost, the expressive power of the engravings still remains, allowing us to gain a small view into the world of the people that lived in the Sahara thousands of years ago, when it was a sprawling green savannah. background_images: - sys: id: 5WH8hIWyZOI0QWe0SyAkC8 created_at: !ruby/object:DateTime 2015-11-25 15:23:42.337000000 Z updated_at: !ruby/object:DateTime 2017-12-15 14:08:22.574000000 Z title: '2013,2034.2756' description: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3584749 url: "//images.ctfassets.net/xt8ne4gbbocd/5WH8hIWyZOI0QWe0SyAkC8/69ac9764bc2af640ff92531ee90422a4/2013_2034.2756.jpg" - sys: id: 23Sckf5aOU4E8WOkg8yoIG created_at: !ruby/object:DateTime 2015-11-25 15:23:42.352000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:23:42.352000000 Z title: '2013,2034.2555' description: url: "//images.ctfassets.net/xt8ne4gbbocd/23Sckf5aOU4E8WOkg8yoIG/5ad5ab2517694ac7ebacdd58be96b254/2013_2034.2555.jpg" key_facts: sys: id: 3edAINBxMk2qYSWCOCisMg created_at: !ruby/object:DateTime 2015-11-26 11:24:38.459000000 Z updated_at: !ruby/object:DateTime 2015-11-26 11:24:38.459000000 Z content_type_id: country_key_facts revision: 1 title_internal: 'Libya: key facts' image_count: 3,899 images date_range: Mostly 10,000 BC to AD 100 main_areas: Acacus Mountains, Messak plateau main_themes: Hunting, daily life, pastoralism, dancing, wild/domesticated animals, prehistoric buffalo thematic_articles: - sys: id: R61tF3euwCmWCUiIgi42q created_at: !ruby/object:DateTime 2015-11-26 17:46:43.669000000 Z updated_at: !ruby/object:DateTime 2018-05-16 17:44:43.683000000 Z content_type_id: thematic revision: 5 title: Hairdressing in the Acacus slug: hairdressing-in-the-acacus lead_image: sys: id: 2PRW2sBJWgiEwA40U2GSiC created_at: !ruby/object:DateTime 2015-11-26 17:38:04.460000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:38:04.460000000 Z title: '2013,2034.477' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2PRW2sBJWgiEwA40U2GSiC/10eed798251d37d988ca686b32c6f42d/2013_2034.477.jpg" chapters: - sys: id: 6eJZLBozwQuAI08GMkwSi6 created_at: !ruby/object:DateTime 2015-11-26 17:42:35.115000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:42:35.115000000 Z content_type_id: chapter revision: 1 title_internal: 'Thematic: hairdressing, chapter 1' body: Hair is a global form of social communication. Among numerous social groups throughout Africa, hairstyling and hairdressing hold great cultural and aesthetic significance. Coiffures have been regarded as indicative of ethnic origin, gender and stages of life development – as well as simply fashion – and have been related to power, age, religion and politics. The transitory yet highly visible nature of hair ensures its suitability as a medium for personal and social expression. And it is not just the domain of women; elaborate hair-styling for men can be an equally important indicator of their place in society. - sys: id: 3w7Qbm8FOw2oqQsm6WsI0W created_at: !ruby/object:DateTime 2015-11-26 17:38:46.614000000 Z updated_at: !ruby/object:DateTime 2018-05-16 15:27:05.950000000 Z content_type_id: image revision: 2 image: sys: id: 5vt4IZCBSEmAQESGiGIS6Q created_at: !ruby/object:DateTime 2015-11-26 17:38:08.444000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:38:08.444000000 Z title: '2013,2034.479' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5vt4IZCBSEmAQESGiGIS6Q/8ea72bce196d2281a0a80d2c2a3b5b5b/2013_2034.479.jpg" caption: Seated figure showing elaborate coiffure. <NAME>, Acacus Mountains, Fezzan District, Libya. 2013,2034.479 © TARA/<NAME>. col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3581661&partId=1&page=1 - sys: id: 6x5pF6pyus2WomGOkkGweC created_at: !ruby/object:DateTime 2015-11-26 17:42:59.906000000 Z updated_at: !ruby/object:DateTime 2018-05-16 15:29:46.989000000 Z content_type_id: chapter revision: 2 title_internal: 'Thematic: hairdressing, chapter 2' body: |- A particularly interesting set of images from Uan Amil in the Acacus Mountains, south-western Libya, reflect the cultural significance of hair in African societies. The scenes depict groups of people engaged in a variety of communal social practices wearing elaborate coiffures, together with some very discrete moments of personal hairdressing. The image below, which is part of a larger panel, shows an intimate moment between two persons, an individual with an ornate coiffure washing or attending to the hair of another. In some African societies, a person’s choice of hairdresser is dictated by their relationship to them. It is most often the work of friends or family to whom you entrust your hair. In the hands of a stranger or adversary hair can be used as an ingredient in the production a powerful substance that could afflict its owner - such is the potency of hair. This image conveys such intimacy. - sys: id: 1XeQI6NL3qeuiosIEoiESE created_at: !ruby/object:DateTime 2015-11-26 17:39:31.382000000 Z updated_at: !ruby/object:DateTime 2018-05-16 15:38:40.565000000 Z content_type_id: image revision: 2 image: sys: id: 2PRW2sBJWgiEwA40U2GSiC created_at: !ruby/object:DateTime 2015-11-26 17:38:04.460000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:38:04.460000000 Z title: '2013,2034.477' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2PRW2sBJWgiEwA40U2GSiC/10eed798251d37d988ca686b32c6f42d/2013_2034.477.jpg" caption: Figure on the left wears an ornate hairstyle and attends to the washing or preparation of another’s hair. 2013,2034.477 © TARA/<NAME>. col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3581665&partId=1&people=197356&museumno=+2013,2034.477&page=1 - sys: id: 2GniIJcZiUSuYWQYYeQmOS created_at: !ruby/object:DateTime 2015-11-26 17:43:22.643000000 Z updated_at: !ruby/object:DateTime 2018-05-16 15:40:09.594000000 Z content_type_id: chapter revision: 2 title_internal: 'Thematic: hairdressing, chapter 3' body: 'The rock shelter of Uan Amil was discovered in 1957 by the Italian-Libyan Joint Archaeological Mission surveying in the Acacus and Messak regions of Libya. Excavations have indicated the shelter was in use over a long period, with at least three main occupational phases between the 8th and 4th millennium BP. Italian archaeologist <NAME> has dated these paintings to 6,000 years ago, while <NAME> has been more cautious and has suggested that the presence of a metal blade on the arrow head seen at the bottom of this image may indicate a more recent age. Notwithstanding the problems associated with the dating of rock art, the subject matter is intriguing. It has been suggested that today’s Wodaabe nomads of Niger resemble the people on these rock paintings: ‘the cattle look the same, as do the campsites with their calf-ropes, and the women’s hairstyles with the special bun on the forehead. The female hair bun is big and round like a globe.’(Bovin, 2001:12).' - sys: id: 5Vp0rW88lqs6UcgaSm6egI created_at: !ruby/object:DateTime 2015-11-26 17:39:56.320000000 Z updated_at: !ruby/object:DateTime 2018-05-16 15:38:59.901000000 Z content_type_id: image revision: 2 image: sys: id: 1KUdkb6fbmW8KOsKWEcu02 created_at: !ruby/object:DateTime 2015-11-26 17:38:12.261000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:38:12.261000000 Z title: '2013,2034.473' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1KUdkb6fbmW8KOsKWEcu02/06c41b36730e0cbf81b105dd400c52ef/2013_2034.473.jpg" caption: This scene has been variously interpreted as showing preparations for a wedding. Note the hairwashing scene top right. 2013,2034.473 © TARA/David Coulson. col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3581674&partId=1&people=197356&museumno=2013,2034.473&page=1 - sys: id: 59XlSp8P7O0ms8UI0auQCw created_at: !ruby/object:DateTime 2015-11-26 17:43:42.266000000 Z updated_at: !ruby/object:DateTime 2018-05-16 16:33:15.417000000 Z content_type_id: chapter revision: 3 title_internal: 'Thematic: hairdressing, chapter 4' body: |- The Wodaabe number around 125,000. As pastoral nomads they migrate often and over large geographical areas, keeping mahogany-coloured Zebu cattle which have a hump on their back and long horns, shaped like a lyre. As a cultural group they have attracted much anthropological attention because of their traditional values of beauty (in particular the male beauty pageant) which pervades their everyday lives and practices. Wodaabe seldom wash their entire bodies mainly because of the scarcity of water. Water from wells is mainly used for drinking by humans and animals. Washing the body and clothes is less of a priority; and hair is hardly ever washed. When Wodaabe put rancid butter on their hair it is to make it soft and shiny and cleanse it of dust and lice. To them rancid butter gives a nice sweet smell (Bovin, 2001:56). In the above image ([2013,2034.473](http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3581674&partId=1&searchText=2013,2034.473&page=1)) at the top right, a vessel sits between the two individuals that may have served to hold rancid butter used in the preparation of the hair. In fact, treating the hair with butter is a widespread practice in African societies. In addition, Wodaabe never cut their hair. Men and women alike desire to have their hair as long as possible. The ideal girl should have long, thick black hair, enough to make a huge round bun on her forehead, while the ideal young male should have long, thick black hair to make braids to the shoulders. - sys: id: 5mnMqJRcbuQqk0ucEOAGCw created_at: !ruby/object:DateTime 2015-11-26 17:40:22.244000000 Z updated_at: !ruby/object:DateTime 2018-05-16 15:48:54.315000000 Z content_type_id: image revision: 2 image: sys: id: 2blaCOYdgYsqqCGakGIwoA created_at: !ruby/object:DateTime 2015-11-26 17:38:04.452000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:38:04.452000000 Z title: '2013,2034.453' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2blaCOYdgYsqqCGakGIwoA/5267369f7e2901448a0f0b0af93ca2a4/2013_2034.453.jpg" caption: Two herders wearing feathers in their hair. <NAME>, Acacus Mountains, Fezzan District, Libya. 2013,2034.453 © TARA/<NAME>. col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3581631&partId=1&people=197356&museumno=2013,2034.453&page=1 - sys: id: qhIjVs2Vxe4muMCWawu0k created_at: !ruby/object:DateTime 2015-11-26 17:44:06.559000000 Z updated_at: !ruby/object:DateTime 2018-05-16 16:32:51.163000000 Z content_type_id: chapter revision: 3 title_internal: 'Thematic: hairdressing, chapter 5' body: |- A long, narrow face is also admired and this is enhanced by shaping the hair on top of the head, and also using an ostrich feather to elongate the face (Bovin,2001:26). The painting above, from <NAME>, characterises this. Interestingly, the coiffures in the images here are light in colour and do not conform to the black ideal as indicated above. It has been suggested that this represents Caucasians with blonde hair. However, it may also be a visual strategy to emphasise the aesthetics of the coiffure. Hairstyles in African sculpture are often shown conceptually, rather than mimetically; idealising rather than copying exactly from contemporary hairdressing practices. In this respect representation follows artistic traditions as much as, or more than, it responds to ephemeral shifts in fashion. - sys: id: 6aPxu2uKyci0Kee8G4gQcm created_at: !ruby/object:DateTime 2015-11-26 17:40:47.827000000 Z updated_at: !ruby/object:DateTime 2018-05-16 15:54:21.695000000 Z content_type_id: image revision: 2 image: sys: id: 4gAFUKBZEsGKMie4cMomwS created_at: !ruby/object:DateTime 2015-11-26 17:38:04.460000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:38:04.461000000 Z title: '2013,2034.466' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4gAFUKBZEsGKMie4cMomwS/0770077ecb7b113ef266b26bfe368bb4/2013_2034.466.jpg" caption: Central figure ‘washing’ their hair while other social practices are taking place. Uan Amil, Libya. 2013,2034.466 © TARA/<NAME>. col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3581646&partId=1&people=197356&museumno=2013,2034.466&page=1 - sys: id: 74IrMM3qGkksSuA4yWU464 created_at: !ruby/object:DateTime 2015-11-26 17:44:28.703000000 Z updated_at: !ruby/object:DateTime 2018-05-16 15:59:10.344000000 Z content_type_id: chapter revision: 2 title_internal: 'Thematic: hairdressing, chapter 6' body: The cultural importance of hair is evident where depictions of hair-washing, hairstyling or hair preparation are an active element within more complex social and cultural activities, such as preparations for a wedding or a scene of supplication. In addition, the C-shaped feature in the image above has been suggested to be a coiled snake, and the figure sits between the head and tail. It may seem incongruous to have hair preparation scenes represented within a tableau representing a wedding or ceremonial meeting, but may say something more about the nature of representation. In each case, these may represent a conceptual depiction of time and space. These activities are not ones that occur concurrently temporally and spatially, but rather represent an assemblage of discrete moments that contribute to each ceremony in its entirety. - sys: id: tvHqAC4aqc2QQWIS8WA26 created_at: !ruby/object:DateTime 2015-11-26 17:42:04.601000000 Z updated_at: !ruby/object:DateTime 2018-05-16 16:31:22.408000000 Z content_type_id: image revision: 2 image: sys: id: 1a8FFEsdsuQeYggMCAasii created_at: !ruby/object:DateTime 2015-11-26 17:38:04.449000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:38:04.449000000 Z title: '2013,2034.465' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1a8FFEsdsuQeYggMCAasii/9c5d70e5961bc74dc11f2170d2ae6b1c/2013_2034.465.jpg" caption: Larger panel from Uan Amil of a figure ‘washing’ their hair. This scene has been interpreted as a possible scene of supplication with people visiting a man in a curved shelter. 2013,2034.465 © TARA/<NAME>son. col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3581647&partId=1&people=197356&museumno=2013,2034.465&page=1 - sys: id: 5qMQLHHz7Uqg460WGO6AW0 created_at: !ruby/object:DateTime 2015-11-26 17:44:46.392000000 Z updated_at: !ruby/object:DateTime 2018-05-16 16:32:18.314000000 Z content_type_id: chapter revision: 2 title_internal: 'Thematic: hairdressing, chapter 7' body: The Wodaabe invest vast amounts of time and resources in their outward appearance and the need to beautify and refine. ‘Art’ is not just something that is aesthetically pleasing - it is a necessity of life, a necessity that must be exhibited. While there are likely to be a variety of complex social, economic and cultural motivations, that necessity is possibly additionally driven or fuelled by a seemingly desolate, unadorned, irregular landscape. The importance lies in distinguishing oneself as a cultural being rather than the ‘uncultured other’, such as an animal; and hair is an apposite medium by which to make this nature/culture distinction. Hair care in African societies is unmistakably aesthetic in its aspirations as it gets transferred into other artistic mediums, and the divide between nature and culture is thoroughly and intentionally in play. To transform hair is to transform nature, and is truly an artistic discipline. citations: - sys: id: 5Sk9I9j7lm0wuUs2m4Qqw4 created_at: !ruby/object:DateTime 2018-05-16 16:34:37.564000000 Z updated_at: !ruby/object:DateTime 2018-05-16 16:34:37.564000000 Z content_type_id: citation revision: 1 citation_line: '<NAME>. 2001. Nomads Who Cultivate Beauty. Uppsala: Nordiska Afrikainstitutet' background_images: - sys: id: 1uxzHwxp9GEUy2miq0C0mM created_at: !ruby/object:DateTime 2015-12-07 18:44:13.394000000 Z updated_at: !ruby/object:DateTime 2015-12-07 18:44:13.394000000 Z title: '01567916 001' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1uxzHwxp9GEUy2miq0C0mM/9c706cad52d044e1d459bba0166ec2fb/01567916_001.jpg" - sys: id: 3drvdVaCYoMs04ew2sIE8Y created_at: !ruby/object:DateTime 2015-12-07 18:43:47.560000000 Z updated_at: !ruby/object:DateTime 2015-12-07 18:43:47.560000000 Z title: 2013,2034.466 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3drvdVaCYoMs04ew2sIE8Y/78d8f39af68d603fbc8a46c745148f0e/2013_2034.466_1.jpg" - sys: id: 72UN6TbsDmocqeki00gS4I created_at: !ruby/object:DateTime 2015-11-26 17:35:22.951000000 Z updated_at: !ruby/object:DateTime 2015-12-07 20:47:35.130000000 Z content_type_id: thematic revision: 4 title: Chariots in the Sahara slug: chariots-in-the-sahara lead_image: sys: id: 2Ed8OkQdX2YIYAIEQwiY8W created_at: !ruby/object:DateTime 2015-11-26 17:17:39.181000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:17:39.181000000 Z title: '2013,2034.999' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2Ed8OkQdX2YIYAIEQwiY8W/9873a75ad2995b1b7a86923eca583f31/2013_2034.999.jpg" chapters: - sys: id: 3pSkk40LWUWs28e0A2ocI2 created_at: !ruby/object:DateTime 2015-11-26 17:27:59.282000000 Z updated_at: !ruby/object:DateTime 2018-05-16 16:42:36.356000000 Z content_type_id: chapter revision: 2 title_internal: 'Thematic: chariots, chapter 1' body: A number of sites from this Collection are located in the Libyan Desert, notably the Fezzan region, and include paintings of chariots in a variety of forms dating to the Horse Period, from up to 3,000 years ago. This has stimulated some interesting questions about the use of chariots in what appears to be such a seemingly inappropriate environment for a wheeled vehicle, as well as the nature of representation. Why were chariots used in the desert and why were they represented in such different ways? - sys: id: 2Hjql4WXLOsmCogY4EAWSq created_at: !ruby/object:DateTime 2015-11-26 17:18:19.534000000 Z updated_at: !ruby/object:DateTime 2018-05-16 16:43:36.197000000 Z content_type_id: image revision: 2 image: sys: id: 2Ed8OkQdX2YIYAIEQwiY8W created_at: !ruby/object:DateTime 2015-11-26 17:17:39.181000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:17:39.181000000 Z title: '2013,2034.999' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2Ed8OkQdX2YIYAIEQwiY8W/9873a75ad2995b1b7a86923eca583f31/2013_2034.999.jpg" caption: Two-wheeled chariot in profile view. Tihenagdal, Acacus Mountains, Libya. 2013,2034.999 © TARA / <NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3588528&partId=1&people=197356&museumno=2013,2034.999&page=1 - sys: id: 3TiPUtUxgAQUe0UGoQUqO0 created_at: !ruby/object:DateTime 2015-11-26 17:28:18.968000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:28:18.968000000 Z content_type_id: chapter revision: 1 title_internal: 'Thematic: chariots, chapter 2' body: The chariot has been one of the great empowering innovations of history. It likely originated in Mesopotamia about 3000 BC due to advances in metallurgy during the Bronze Age, and has served as a primary means of transport until quite recently in the historical period across Africa, Eurasia and Europe. Chariots provided rapid and efficient transport, and were ideal for the battlefield as the design provided a raised firing platform for archers . As a result the chariot became the principal war machine from the Egyptians through to the Romans; and the Chinese, who owned an army of 10,000 chariots. Indeed, our use of the word car is a derivative of the Latin word carrus, meaning ‘a chariot of war or of triumph’. - sys: id: 5ZxcAksrFSKEGacE2iwQuk created_at: !ruby/object:DateTime 2015-11-26 17:19:58.050000000 Z updated_at: !ruby/object:DateTime 2018-05-16 16:44:46.340000000 Z content_type_id: image revision: 2 image: sys: id: 5neJpIDOpyUQAWC8q0mCIK created_at: !ruby/object:DateTime 2015-11-26 17:17:39.141000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:17:39.141000000 Z title: '124534' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5neJpIDOpyUQAWC8q0mCIK/d8ee0111089adb2b565b48919f21dfbe/124534.jpg" caption: Neo-Assyrian Gypsum wall panel relief showing Ashurnasirpal II hunting lions, 865BC – 860 BC. © Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=367027&partId=1&people=197356&museumno=124534&page=1 - sys: id: 2Grf0McSJ2Uq4SUaUQAMwU created_at: !ruby/object:DateTime 2015-11-26 17:28:46.851000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:28:46.851000000 Z content_type_id: chapter revision: 1 title_internal: 'Thematic: chariots, chapter 3' body: The chariot in the Sahara was probably introduced by the Garamantes, a cultural group thought to be descended from Berbers and Saharan pastoralists. There is little textual information about the Garamantes, documentation comes mainly from Greek and Roman sources. Herodotus described them as ‘a very great nation’. Recent archaeological research has shown that the Garamantes established about eight major towns as well as numerous other settlements, and were ‘brilliant farmers, resourceful engineers, and enterprising merchants’. The success of the Garamantes was based on their subterranean water-extraction system, a network of underground tunnels, allowing the Garamantian culture to flourish in an increasingly arid environment, resulting in population expansion, urbanisation, and conquest. - sys: id: 6fOKcyIgKcyMi8uC4WW6sG created_at: !ruby/object:DateTime 2015-11-26 17:20:33.572000000 Z updated_at: !ruby/object:DateTime 2018-05-16 16:45:32.605000000 Z content_type_id: image revision: 2 image: sys: id: 4DBpxlJqeAS4O0eYeCO2Ms created_at: !ruby/object:DateTime 2015-11-26 17:17:39.152000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:17:39.152000000 Z title: '2013,2034.407' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4DBpxlJqeAS4O0eYeCO2Ms/18e67077bdaa437ac82e85ba48cdb0da/2013_2034.407.jpg" caption: A so-called ‘Flying gallop’ chariot. Wadi Teshuinat, Acacus Mountains, Libya. 2013,2034.407 © TARA / <NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3580186&partId=1&people=197356&museumno=2013,2034.407&page=1 - sys: id: CAQ4O5QWhaCeOQAMmgGSo created_at: !ruby/object:DateTime 2015-11-26 17:29:06.521000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:29:06.521000000 Z content_type_id: chapter revision: 1 title_internal: 'Thematic: chariots, chapter 4' body: On average there are about 500 drawings of chariots across the Sahara, from the Fezzan in Libya through the Aïr of Niger into northern Mali and then westward to the Atlantic coast; but not all were produced by the Garamantes. It is still not certain that chariots were driven along the routes where their depictions occur; remains of chariots have never been found west of the Fezzan. However, the Fezzan states were thriving trade routes and chariots are likely to have been used to transport salt, cloth, beads and metal goods in exchange for gold, ivory and slaves. The widespread occurrence of chariot imagery on Saharan rock outcrops has led to the proposition of ‘chariot routes’ linking North and West Africa. However, these vehicles were not suited for long-distance transport across desert terrain; more localised use is probable, conducted through middlemen who were aware of the trade routes through the desert landscape. Additionally, the horse at this time was a prestige animal and it is unlikely that they facilitated transport across the Saharan trade routes, with travellers rather utilising donkeys or oxen. - sys: id: 5cgk0mmvKwC0IGsCyIsewG created_at: !ruby/object:DateTime 2015-11-26 17:20:59.281000000 Z updated_at: !ruby/object:DateTime 2018-05-16 16:46:44.461000000 Z content_type_id: image revision: 2 image: sys: id: 4XYASoQz6UQggUGI8gqkgq created_at: !ruby/object:DateTime 2015-11-26 17:17:39.148000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:17:39.148000000 Z title: '2013,2034.389' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4XYASoQz6UQggUGI8gqkgq/d167c56220dfd17c399b02086fe9ebc3/2013_2034.389.jpg" caption: This two wheeled chariot is being drawn by a cow with upturned horns. Awis Valley, Acacus Mountains, Libya. 2013,2034.389 © TARA / <NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3579985&partId=1&people=197356&museumno=2013,2034.389&page=1 - sys: id: 5pKuD1vPdmcs2o8eQeumM4 created_at: !ruby/object:DateTime 2015-11-26 17:29:23.611000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:29:23.611000000 Z content_type_id: chapter revision: 1 title_internal: 'Thematic: chariots, chapter 5' body: The absence of archaeological evidence for chariots has led to the suggestion that some representations of chariots may have been the result of cultural diffusion, transmitted orally by nomadic peoples traversing the region. Artists may never have actually seen the vehicles themselves. If this is the case, chariot symbols may have acquired some special meaning above their function as modes of transport. It may also explain why some representations of chariots do not seem to conform to more conventional styles of representations and account for the different ways in which they were depicted. - sys: id: wckVt1SCpqs0IYeaAsWeS created_at: !ruby/object:DateTime 2015-11-26 17:21:42.421000000 Z updated_at: !ruby/object:DateTime 2018-05-16 16:48:40.965000000 Z content_type_id: image revision: 3 image: sys: id: 279BaN9Z4QeOYAWCMSkyeQ created_at: !ruby/object:DateTime 2015-11-26 17:17:46.288000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:17:46.288000000 Z title: '2013,2034.392' description: url: "//images.ctfassets.net/xt8ne4gbbocd/279BaN9Z4QeOYAWCMSkyeQ/7606d86492a167b9ec4b105a7eb57d74/2013_2034.392.jpg" caption: These two images (above and below) depicts chariots as if ‘flattened out’, with the horses represented back to back. Awis Valley, Acacus Mountains, Libya. 2013,2034.392 © TARA / <NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3579981&partId=1&people=197356&museumno=2013,2034.392&page=1 - sys: id: 7fKfpmISPYs04YOi8G0kAm created_at: !ruby/object:DateTime 2015-11-26 17:23:05.317000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:23:05.317000000 Z content_type_id: image revision: 1 image: sys: id: 28JPIQ4mYQCMYQmMQ0Oke8 created_at: !ruby/object:DateTime 2015-11-26 17:17:45.941000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:17:45.941000000 Z title: '2013,2034.393' description: url: "//images.ctfassets.net/xt8ne4gbbocd/28JPIQ4mYQCMYQmMQ0Oke8/665bea9aafec58dfe3487ee665b3a9ec/2013_2034.393.jpg" caption: 2013,2034.393 © TARA / <NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3579980&partId=1&people=197356&museumno=2013,2034.393&page=1 - sys: id: 3xUchEu4sECWq4mAoEYYM4 created_at: !ruby/object:DateTime 2015-11-26 17:23:33.472000000 Z updated_at: !ruby/object:DateTime 2018-05-16 17:20:52.618000000 Z content_type_id: image revision: 2 image: sys: id: 697LgKlm3SWSQOu8CqSuIO created_at: !ruby/object:DateTime 2015-11-26 17:17:45.956000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:17:45.956000000 Z title: '2013,2034.370' description: url: "//images.ctfassets.net/xt8ne4gbbocd/697LgKlm3SWSQOu8CqSuIO/c8afe8c1724289dee3c1116fd4ba9280/2013_2034.370.jpg" caption: Possible chariot feature in top left of image. Acacus Mountains, Libya. 2013,2034.370 © TARA / <NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3579291&partId=1&people=197356&museumno=2013,2034.370&page=1 - sys: id: 6bQzinrqXmYESoWqyYYyuI created_at: !ruby/object:DateTime 2015-11-26 17:24:01.069000000 Z updated_at: !ruby/object:DateTime 2018-05-16 17:21:25.227000000 Z content_type_id: image revision: 2 image: sys: id: 5RKPaYinvOW6yyCGYcIsmK created_at: !ruby/object:DateTime 2015-11-26 17:17:45.952000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:17:45.952000000 Z title: '2013,2034.371' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5RKPaYinvOW6yyCGYcIsmK/a0328f912ac8f6fe017ce99d8e673421/2013_2034.371.jpg" caption: Possible chariots with two wheels. Acacus Mountains, Fezzan District, Libya. 2013,2034.371 © TARA / <NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3579290&partId=1&people=197356&museumno=2013,2034.371&page=1 - sys: id: 5qthr4HJaEoIe2sOOqiU4K created_at: !ruby/object:DateTime 2015-11-26 17:29:40.388000000 Z updated_at: !ruby/object:DateTime 2018-05-16 17:31:17.884000000 Z content_type_id: chapter revision: 2 title_internal: 'Thematic: chariots, chapter 6' body: |- The two images may or may not depict chariots. The rectangular shapes are potentially abstracted forms of the chariot similar to the ‘flattened out’ depictions discussed previously. These potentially abstracted representations often sit alongside distinguishing figures, such as geometric bi-triangular figures, spears or lances, women wearing long dresses, and animals drawn in a fairly naturalistic style, of the Horse Period when the chariots were being used. Beside the schematic and simply depicted chariots, there is also a group which has been termed the ‘flying gallop chariots’. Their distribution includes the whole Tassili region, although there are fewer in the Acacus Mountains. They resemble the classical two-wheeled antique chariots, generally drawn by two horses, but sometimes three, or even four. The driver is usually alone, and is depicted in a typical style with a stick head. The majority are shown at full speed, with the driver holding a whip standing on a small platform, sometimes straining forward. - sys: id: 2NEHx4J06IMSceEyC4w0CA created_at: !ruby/object:DateTime 2015-11-26 17:24:30.605000000 Z updated_at: !ruby/object:DateTime 2018-05-16 17:31:46.413000000 Z content_type_id: image revision: 2 image: sys: id: 74j3IOLwLS8IocMCACY2W created_at: !ruby/object:DateTime 2015-11-26 17:17:45.949000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:17:45.949000000 Z title: '2013,2034.523' description: url: "//images.ctfassets.net/xt8ne4gbbocd/74j3IOLwLS8IocMCACY2W/5495e8c245e10db13caf5cb0f36905c4/2013_2034.523.jpg" caption: "'Flying gallop’ chariot, <NAME>, Acacus Mountains, Fezzan District, Libya. 2013,2034.523 © TARA / <NAME>" col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3583068&partId=1&people=197356&museumno=2013,2034.523&page=1 - sys: id: 1YKtISfrKAQ6M4mMawIOYK created_at: !ruby/object:DateTime 2015-11-26 17:30:08.834000000 Z updated_at: !ruby/object:DateTime 2018-05-16 17:33:37.308000000 Z content_type_id: chapter revision: 2 title_internal: 'Thematic: chariots, chapter 7' body: |- In a similar manner to the schematic chariots, the 'Flying Gallop' depictions display the entire platform and both wheels of the chariot. In addition, more than one horse is depicted as a single horse in profile with numerous legs indicating multiple horses; an artistic technique first seen during the Upper Palaeolithic in Europe. Interestingly, in the Libyan rock art of the Acacus Mountains it seemed that animals could be conceived of in profile and in movement, but chariots were conceived of differently, and are represented in plain view, seen from above or in three-quarters perspective. Why are chariots depicted in a variety of ways, and what can we say about the nature of representation in relation to chariots? It is clear that chariots are able to be depicted in profile view, yet there are variations that digress from this perspective. In relation to the few examples we have come across so far in the Acacus Mountains in south-western Libya, one observation we might make is that the ways in which chariots have been represented may be indicative of the ways in which they have been observed by the artists representing them; as a rule from above. The rock shelters in the Acacus are often some height above the now dried up wadis, and so the ways in which they conceived of representing the chariot itself , whether as a flying gallop chariot, a chariot drawn by a bovid or as an abstraction, may have become a particular representational convention. The ways in which animals were represented conformed also to a convention, one that had a longer tradition, but chariots were an innovation and may have been represented as they were observed; from higher up in the rockshelters; thus chariots were conceived of as a whole and from an aerial perspective. The ways in which environments affect our perceptions of dimension, space and colour are now well-established, initially through cross-cultural anthropological studies in the 1960s, and becoming better understood through more recent research concerning the brain. Of course, this is speculation, and further research would be needed to consider all the possibilities. But for now, we can start to see some intriguing lines of enquiry and research areas that these images have stimulated. - sys: id: 4nHApyWfWowgG0qASeKEwk created_at: !ruby/object:DateTime 2015-11-26 17:25:19.180000000 Z updated_at: !ruby/object:DateTime 2018-05-16 17:34:17.369000000 Z content_type_id: image revision: 2 image: sys: id: 4Mn54dTjEQ80ssSOK0q0Mq created_at: !ruby/object:DateTime 2015-11-26 17:17:39.129000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:17:39.129000000 Z title: '135568' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4Mn54dTjEQ80ssSOK0q0Mq/c1bca8c151b882c16adaf7bc449e1850/135568.jpg" caption: Model of chariot, Middle Bronze Age – Early Bronze Age, 2000BC, Eastern Anatolia Region. 1971,0406.1 © Trustees of the British Museum. The design of this chariot is very similar to the representation in Fig. 4. col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=369521&partId=1&people=197356&museumno=135568&page=1 - sys: id: 5dtoX8DJv2UkguMM24uWwK created_at: !ruby/object:DateTime 2015-11-26 17:26:17.455000000 Z updated_at: !ruby/object:DateTime 2018-05-16 17:34:59.909000000 Z content_type_id: image revision: 2 image: sys: id: 7zQLgo270Am82CG0Qa6gaE created_at: !ruby/object:DateTime 2015-11-26 17:17:45.956000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:17:45.956000000 Z title: '894,1030.1' description: url: "//images.ctfassets.net/xt8ne4gbbocd/7zQLgo270Am82CG0Qa6gaE/80aa63978217874eaaa0960a6e0847d6/894_1030.1.jpg" caption: Bronze model of a two-horse racing chariot. Roman, 1st century – 2nd century, Latium, Tiber River. 1894,1030.1 © Trustees of the British Museum. col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=399770&partId=1&people=197356&museumno=1894,1030.1&page=1 - sys: id: 74fcVRriowwOQeWua2uMMY created_at: !ruby/object:DateTime 2015-11-26 17:30:27.301000000 Z updated_at: !ruby/object:DateTime 2018-05-16 17:35:36.578000000 Z content_type_id: chapter revision: 2 title_internal: 'Thematic: chariots, chapter 8' body: Vast trading networks across the Sahara Desert not only facilitated the spread of goods, but the routes served as a conduit for cultural diffusion through the spread of knowledge, ideas and technologies. Chariots were both functional and symbolic. As a mode of transport, as a weapon of war, as a means of trade and exchange and as a symbol of power, the chariot has been a cultural artefact for 4,000 years. Its temporal and spatial reach is evident not only in the rock art, but through the British Museum collections, which reveal comparisons between 2D rock art and 3D artefacts. Similarities and adjacencies occur not only in the structure and design of the chariots themselves but in their symbolic and pragmatic nature. - sys: id: 266zWxwbfC86gaKyG8myCU created_at: !ruby/object:DateTime 2015-11-26 17:26:53.266000000 Z updated_at: !ruby/object:DateTime 2018-05-16 17:43:56.525000000 Z content_type_id: image revision: 2 image: sys: id: 4rwQF960rueIOACosUMwoa created_at: !ruby/object:DateTime 2015-11-26 17:17:39.145000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:17:39.145000000 Z title: EA 37982 description: url: "//images.ctfassets.net/xt8ne4gbbocd/4rwQF960rueIOACosUMwoa/b5b41cda0efd36989292d004f039bace/EA_37982.jpg" caption: Fragment of a limestone tomb-painting representing the assessment of crops, c. 1350BC, Tomb of Nebamun, Thebes, Egypt. British Museum EA37982 ©Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=117388&partId=1&people=197356&museumno=37982&page=1 - sys: id: 2mTEgMGc5iiM00MOE4WSqU created_at: !ruby/object:DateTime 2015-11-26 17:27:28.284000000 Z updated_at: !ruby/object:DateTime 2018-05-16 17:44:28.029000000 Z content_type_id: image revision: 2 image: sys: id: 70cjifYtVeeqIOoOCouaGS created_at: !ruby/object:DateTime 2015-11-26 17:17:46.009000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:17:46.009000000 Z title: '1867,0101.870' description: url: "//images.ctfassets.net/xt8ne4gbbocd/70cjifYtVeeqIOoOCouaGS/066bc072069ab814687828a61e1ff1aa/1867_0101.870.jpg" caption: Gold coin of Diocletian, obverse side showing chariot. British Museum 1867,0101.870 ©Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=1189587&partId=1&people=197356&museumno=1867,0101.870&page=1 - sys: id: 5Z6SQu2oLuG40IIWEqKgWE created_at: !ruby/object:DateTime 2015-11-26 17:30:47.583000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:30:47.583000000 Z content_type_id: chapter revision: 1 title_internal: 'Thematic: chariots, chapter 9' body: A hoard of 100,000 Roman coins from the Diocletian period (not the above) were unearthed near Misurata, Libya, probably used to pay both regular Roman and local troops. Such finds demonstrate the symbolic power of the chariot and the diffusion of the imagery. citations: - sys: id: vVxzecw1jwam6aCcEA8cY created_at: !ruby/object:DateTime 2015-11-26 17:31:32.248000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:31:32.248000000 Z content_type_id: citation revision: 1 citation_line: <NAME>. ‘Kingdom of the Sands', in *Current Archaeology*, Vol. 57 No 2, March/April 2004 background_images: - sys: id: 3Cv9FvodyoQIQS2UaCo4KU created_at: !ruby/object:DateTime 2015-12-07 18:43:47.568000000 Z updated_at: !ruby/object:DateTime 2015-12-07 18:43:47.568000000 Z title: '01495388 001' description: url: "//images.ctfassets.net/xt8ne4gbbocd/3Cv9FvodyoQIQS2UaCo4KU/f243937c551a4a12f07c1063d13edaaa/01495388_001.jpg" - sys: id: 2yTKrZUOY00UsmcQ8sC0w4 created_at: !ruby/object:DateTime 2015-12-07 18:44:42.716000000 Z updated_at: !ruby/object:DateTime 2015-12-07 18:44:42.716000000 Z title: '01495139 001' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2yTKrZUOY00UsmcQ8sC0w4/8e527c421d837b3993026107d0a0acbb/01495139_001.jpg" - sys: id: 1hw0sVC0XOUA4AsiG4AA0q created_at: !ruby/object:DateTime 2017-11-23 11:49:41.362000000 Z updated_at: !ruby/object:DateTime 2017-11-23 11:49:41.362000000 Z content_type_id: thematic revision: 1 title: 'Introduction to rock art in northern Africa ' slug: rock-art-in-northern-africa lead_image: sys: id: 1fzfpavYuGaOKaAM2ko6es created_at: !ruby/object:DateTime 2015-11-26 15:53:30.004000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:53:30.004000000 Z title: '2013,2034.3840' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1fzfpavYuGaOKaAM2ko6es/f1e27e311dca40ce58657e5e88cb8526/2013_2034.3840.jpg" chapters: - sys: id: axu12ftQUoS04AQkcSWYI created_at: !ruby/object:DateTime 2015-11-26 15:58:10.885000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:58:10.885000000 Z content_type_id: chapter revision: 1 title: title_internal: 'North Africa: regional, chapter 1' body: 'The Sahara is the largest non-polar desert in the world, covering almost 8,600,000 km² and comprising most of northern Africa, from the Red Sea to the Atlantic Ocean. Although it is considered a distinct entity, it is composed of a variety of geographical regions and environments, including sand seas, hammadas (stone deserts), seasonal watercourses, oases, mountain ranges and rocky plains. Rock art is found throughout this area, principally in the desert mountain and hill ranges, where stone ''canvas'' is abundant: the highlands of Adrar in Mauritania and Adrar des Ifoghas in Mali, the Atlas Mountains of Morocco and Algeria, the Tassili n’Ajjer and Ahaggar Mountains in Algeria, the mountainous areas of Tadrart Acacus and Messak in Libya, the Aïr Mountains of Nigeria, the Ennedi Plateau and Tibesti Mountains in Chad, the Gilf Kebir plateau of Egypt and Sudan, as well as the length of the Nile Valley.' - sys: id: 4DelCmwI7mQ4MC2WcuAskq created_at: !ruby/object:DateTime 2015-11-26 15:54:19.234000000 Z updated_at: !ruby/object:DateTime 2016-12-22 10:12:21.657000000 Z content_type_id: image revision: 2 image: sys: id: 1fzfpavYuGaOKaAM2ko6es created_at: !ruby/object:DateTime 2015-11-26 15:53:30.004000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:53:30.004000000 Z title: '2013,2034.3840' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1fzfpavYuGaOKaAM2ko6es/f1e27e311dca40ce58657e5e88cb8526/2013_2034.3840.jpg" caption: Bubalus Period engraving. Pelorovis Antiquus, Wadi Mathendous, Libya. 2013,2034.3840 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3593438&partId=1&images=true&people=197356&museumno=2013,2034.3840&page=1 - sys: id: 2XmfdPdXW0Y4cy6k4O4caO created_at: !ruby/object:DateTime 2015-11-26 15:58:31.891000000 Z updated_at: !ruby/object:DateTime 2016-10-17 13:40:03.509000000 Z content_type_id: chapter revision: 3 title: Types of rock art and distribution title_internal: 'North Africa: regional, chapter 2' body: |+ Although the styles and subjects of north African rock art vary, there are commonalities: images are most often figurative and frequently depict animals, both wild and domestic. There are also many images of human figures, sometimes with accessories such as recognisable weaponry or clothing. These may be painted or engraved, with frequent occurrences of both, at times in the same context. Engravings are generally more common, although this may simply be a preservation bias due to their greater durability. The physical context of rock art sites varies depending on geographical and topographical factors – for example, Moroccan rock engravings are often found on open rocky outcrops, while Tunisia’s Djebibina rock art sites have all been found in rock shelters. Rock art in the vast and harsh environments of the Sahara is often inaccessible and hard to find, and there is probably a great deal of rock art that is yet to be seen by archaeologists; what is known has mostly been documented within the last century. - sys: id: 2HqgiB8BAkqGi4uwao68Ci created_at: !ruby/object:DateTime 2016-10-17 13:41:30.844000000 Z updated_at: !ruby/object:DateTime 2016-10-17 13:41:30.844000000 Z content_type_id: chapter revision: 1 title: History of research title_internal: 'North Africa: regional chapter 2.5' body: Although the existence of rock art throughout the Sahara was known to local communities, it was not until the nineteenth century that it became known to Europeans, thanks to explorers such as <NAME>, who crossed the Messak Plateau in Libya in 1850, first noting the existence of engravings. Further explorations in the early twentieth century by celebrated travellers, ethnographers and archaeologists such as <NAME>, <NAME>, <NAME>, <NAME> and <NAME> brought the rock art of Sahara, and northern Africa in general, to the awareness of a European public. - sys: id: 5I9fUCNjB668UygkSQcCeK created_at: !ruby/object:DateTime 2015-11-26 15:54:54.847000000 Z updated_at: !ruby/object:DateTime 2016-12-22 10:13:53.921000000 Z content_type_id: image revision: 2 image: sys: id: 2N4uhoeNLOceqqIsEM6iCC created_at: !ruby/object:DateTime 2015-11-26 15:53:37.250000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:53:37.250000000 Z title: '2013,2034.1424' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2N4uhoeNLOceqqIsEM6iCC/240a45012afba4ff5508633fcaea3462/2013_2034.1424.jpg" caption: Pastoral Period painting, cattle and human figure. <NAME>, Acacus Mountains, Libya. 2013,2034.1424 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3592663 - sys: id: 5OkqapzKtqEcomSucG0EoQ created_at: !ruby/object:DateTime 2015-11-26 15:58:52.432000000 Z updated_at: !ruby/object:DateTime 2016-10-17 13:45:37.885000000 Z content_type_id: chapter revision: 4 title: Attribution and dating title_internal: 'North Africa: regional, chapter 3' body: 'The investigations of these researchers and those who have followed them have sought to date and attribute these artworks, with varying measures of success. Rock art may be associated with certain cultures through known parallels with the imagery in other artefacts, such as Naqada Period designs in Egyptian rock art that mirror those on dateable pottery. Authorship may be also guessed at through corroborating evidence: for example, due to knowledge of their chariot use, and the location of rock art depicting chariots in the central Sahara, it has been suggested that it was produced by – or at the same time as – the height of the Garamantes culture, a historical ethnic group who formed a local power around what is now southern Libya from 500 BC–700 AD. However, opportunities to anchor rock art imagery in this way to known ancient cultures are few and far between, and rock art is generally ascribed to anonymous hunter-gatherers, nomadic peoples, or pastoralists, with occasional imagery-based comparisons made with contemporary groups, such as the Fulani peoples.' - sys: id: 2KmaZb90L6qoEAK46o46uK created_at: !ruby/object:DateTime 2015-11-26 15:55:22.104000000 Z updated_at: !ruby/object:DateTime 2016-12-22 10:16:53.318000000 Z content_type_id: image revision: 2 image: sys: id: 5A1AwRfu9yM8mQ8EeOeI2I created_at: !ruby/object:DateTime 2015-11-26 15:53:37.288000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:53:37.288000000 Z title: '2013,2034.1152' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5A1AwRfu9yM8mQ8EeOeI2I/cac0592abfe1b31d7cf7f589355a216e/2013_2034.1152.jpg" caption: Round Head Period painting, human figures. Wadi Tafak, Acacus Mountains, Libya. 2013,2034.1152 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3592099&partId=1&images=true&people=197356&page=1 - sys: id: 27ticyFfocuOIGwioIWWYA created_at: !ruby/object:DateTime 2015-11-26 15:59:26.852000000 Z updated_at: !ruby/object:DateTime 2016-10-17 15:18:29.234000000 Z content_type_id: chapter revision: 2 title_internal: 'North Africa: regional, chapter 4' body: |- Occasionally, association with writing in the form of, for example, Libyan-Berber or Arabic graffiti can give a known dating margin, but in general, lack of contemporary writing and written sources (Herodotus wrote about the Garamantes) leaves much open to conjecture. Other forms of (rare) circumstantial evidence, such as rock art covered by a dateable stratigraphic layer, and (more common) stylistic image-based dating have been used instead to form a chronology of Saharan rock art periods that is widely agreed upon, although dates are contested. The first stage, known as the Early Hunter, Wild Fauna or Bubalus Period, is posited at about 12,000–6,000 years ago, and is typified by naturalistic engravings of wild animals, in particular an extinct form of buffalo identifiable by its long horns. - sys: id: q472iFYzIsWgqWG2esg28 created_at: !ruby/object:DateTime 2015-11-26 15:55:58.985000000 Z updated_at: !ruby/object:DateTime 2016-12-22 10:19:11.991000000 Z content_type_id: image revision: 2 image: sys: id: 1YAVmJPnZ2QQiguCQsgOUi created_at: !ruby/object:DateTime 2015-11-26 15:53:29.989000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:53:29.989000000 Z title: '2013,2034.4570' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1YAVmJPnZ2QQiguCQsgOUi/4080b87891cb255e12a17216d7e71286/2013_2034.4570.jpg" caption: Horse Period painting, charioteer and standing horses. <NAME>, <NAME>. 2013,2034.4570 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3603794 - sys: id: 7tsWGNvkQgACuKEMmC0uwG created_at: !ruby/object:DateTime 2015-11-26 15:59:47.880000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:59:47.880000000 Z content_type_id: chapter revision: 1 title_internal: 'North Africa: regional, chapter 5' body: A possibly concurrent phase is known as the Round Head Period (about 10,000 to 8,000 years ago) due to the large discoid heads of the painted human figures. Following this is the most widespread style, the Pastoral Period (around 7,500 to 4,000 years ago), which is characterised by numerous paintings and engravings of cows, as well as occasional hunting scenes. The Horse Period (around 3,000 to 2,000 years ago) features recognisable horses and chariots and the final Camel Period (around 2,000 years ago to present) features domestic dromedary camels, which we know to have been widely used across the Sahara from that time. - sys: id: 13V2nQ2cVoaGiGaUwWiQAC created_at: !ruby/object:DateTime 2015-11-26 15:56:25.598000000 Z updated_at: !ruby/object:DateTime 2016-12-22 10:39:22.861000000 Z content_type_id: image revision: 2 image: sys: id: 6MOI9r5tV6Gkae0CEiQ2oQ created_at: !ruby/object:DateTime 2015-11-26 15:53:29.964000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:53:29.964000000 Z title: 2013,2034.1424 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6MOI9r5tV6Gkae0CEiQ2oQ/bad4ec8dd7c6ae553d623e4238641561/2013_2034.1424_1.jpg" caption: Camel engraving. <NAME>, Jebel Uweinat, Sudan. 2013,2034.335 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3586831 - sys: id: 3A64bY4VeMGkKCsGCGwu4a created_at: !ruby/object:DateTime 2015-11-26 16:00:04.267000000 Z updated_at: !ruby/object:DateTime 2016-10-17 15:30:04.896000000 Z content_type_id: chapter revision: 2 title_internal: 'North Africa: regional, chapter 6' body: "While this chronology serves as a useful framework, it must be remembered that the area – and the time period in which rock art was produced – is extensive and there is significant temporal and spatial variability within and across sites. There are some commonalities in rock art styles and themes across the Sahara, but there are also regional variations and idiosyncrasies, and a lack of evidence that any of these were directly, or even indirectly, related. The engravings of weaponry motifs from Morocco and the painted ‘swimming’ figures of the Gilf Kebir Plateau in Egypt and Sudan are not only completely different, but unique to their areas. Being thousands of kilometres apart and so different in style and composition, they serve to illustrate the limitations inherent in examining northern African rock art as a unit. The contemporary political and environmental challenges to accessing rock art sites in countries across the Sahara serves as another limiting factor in their study, but as dating techniques improve and further discoveries are made, this is a field with the potential to help illuminate much of the prehistory of northern Africa.\n\n" citations: - sys: id: 4AWHcnuAVOAkkW0GcaK6We created_at: !ruby/object:DateTime 2016-10-17 15:15:38.284000000 Z updated_at: !ruby/object:DateTime 2016-10-17 15:15:38.284000000 Z content_type_id: citation revision: 1 citation_line: | <NAME>. 1998. Art rupestre et préhistoire du Sahara: le Messak Libyen. Paris: Payot & Rivages <NAME>. 1995. Les images rupestres du Sahara. — Toulouse (author’s ed.), p. 447 <NAME>. 2001. Saharan Africa in (ed) <NAME>. Whitley, Handbook of Rock Art Research, pp 605-636. AltaMira Press, Walnut Creek <NAME>. 2013. Dating the rock art of Wadi Sura, in Wadi Sura – The Cave of Beasts, Kuper, R. (ed). Africa Praehistorica 26 – Köln: Heinrich-Barth-Institut, pp. 38-39 <NAME>. 1999. L'art rupestre du Haut Atlas Marocain. Paris, L'Harmattan <NAME>. 2012. Round Heads: The Earliest Rock Paintings in the Sahara. Newcastle upon Tyne: Cambridge Scholars Publishing <NAME>. 1993. Préhistoire de la Mauritanie. Centre Culturel Français A. de Saint Exupéry-Sépia, Nouakchott background_images: - sys: id: 3ZTCdLVejemGiCIWMqa8i created_at: !ruby/object:DateTime 2015-12-07 19:41:46.025000000 Z updated_at: !ruby/object:DateTime 2015-12-07 19:41:46.025000000 Z title: EAF135068 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3ZTCdLVejemGiCIWMqa8i/5a0d13fdd2150f0ff81a63afadd4258e/EAF135068.jpg" - sys: id: 2jvgN3MMfqoAW6GgO8wGWo created_at: !ruby/object:DateTime 2015-12-07 19:41:50.029000000 Z updated_at: !ruby/object:DateTime 2015-12-07 19:41:50.029000000 Z title: EAF131007 description: url: "//images.ctfassets.net/xt8ne4gbbocd/2jvgN3MMfqoAW6GgO8wGWo/393c91068f4dc0ca540c35a79b965288/EAF131007.jpg" country_introduction: sys: id: 5v13g3YNLUGuGwMgSI0e6s created_at: !ruby/object:DateTime 2015-11-26 12:35:54.777000000 Z updated_at: !ruby/object:DateTime 2015-12-07 13:42:46.961000000 Z content_type_id: country_information revision: 2 title: 'Libya: country introduction' chapters: - sys: id: 4WfnZcehd66ieoiASe6Ya2 created_at: !ruby/object:DateTime 2015-11-26 12:29:44.896000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:29:44.896000000 Z content_type_id: chapter revision: 1 title: Introduction title_internal: 'Libya: country, chapter 1' body: 'Rock art occurs in two main areas in Libya: the Tadrart Acacus and the Messak Plateau. The oldest works of rock art, from the Acacus Mountains, are engravings of mammals from the Wild Fauna Period (Early Hunter Period) and could be up to 12,000 years old. Thousands of paintings dating from up to 8,000-9,000 years ago show a diversity of imagery and include scenes of hunting, pastoralism, daily life, dancing and a variety of wild and domesticated animals. The Messak Plateau is home to tens of thousands of engravings, and only a few paintings have been located in this region to date. The area is best known for larger-than-life-size engravings of animals such as elephants, rhino and bubalus (a now extinct buffalo), and some of the most iconic depictions in Saharan rock art, such as the ‘Fighting Cats’ scene.' - sys: id: 4VNJEMI25aagoiEuoUckqg created_at: !ruby/object:DateTime 2015-11-26 12:26:30.631000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:26:30.631000000 Z content_type_id: image revision: 1 image: sys: id: 16a6qAimaaWYqcwqUqMKIm created_at: !ruby/object:DateTime 2015-11-26 12:25:03.860000000 Z updated_at: !ruby/object:DateTime 2017-12-15 14:15:08.336000000 Z title: '2013,2034.420' description: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3580676 url: "//images.ctfassets.net/xt8ne4gbbocd/16a6qAimaaWYqcwqUqMKIm/35056fde196c5ae13894c78ed1b5fe17/2013_2034.420.jpg" caption: Painted rock art with figures and animals from the Acacus Mountains, Fezzan District, Libya. 2013,2034.420 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3580676&partId=1&images=true&people=197356&museumno=2013,2034.420&page=1 - sys: id: 6vqAmqiuY0AIEyUGOcAyQC created_at: !ruby/object:DateTime 2015-11-26 12:30:08.049000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:30:08.049000000 Z content_type_id: chapter revision: 1 title: Geography title_internal: 'Libya: country, chapter 2' body: The fourth largest country in Africa, Libya is located in the Maghreb region of North Africa, bordered on the west by Tunisia and Algeria, Egypt to the east, and the Mediterranean Sea to the north. Except for the narrow strip along the coast, where 80% of the population resides, Libya lies entirely within the Sahara Desert. The main areas of rock art lie in the south-western corner of the country, with the Tadrart Acacus continuing into south-eastern Algeria, where they are simply known as the Tadrart. The Acacus in Libya and the Tadrart in Algeria are now listed and combined as a trans-frontier World Heritage Site by UNESCO, linking these two geographically divided sites into a cultural whole. - sys: id: 1icEVGCcP2Um64EkAs0OAg created_at: !ruby/object:DateTime 2015-11-26 12:27:03.984000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:27:03.984000000 Z content_type_id: image revision: 1 image: sys: id: YbgSaS84Eu0gE8yKEcI48 created_at: !ruby/object:DateTime 2015-11-26 12:25:07.208000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:25:07.208000000 Z title: '2013,2034.1012' description: url: "//images.ctfassets.net/xt8ne4gbbocd/YbgSaS84Eu0gE8yKEcI48/c3cf27b1581df5b3cfed28e53439b4f8/2013_2034.1012.jpg" caption: Tadrart Acacus, Libya. 2013,2034.1012 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3588542&partId=1&images=true&people=197356&museumno=2013,2034.1012&page=1 - sys: id: 2HfBZlyHUA4MCEuqma8QeC created_at: !ruby/object:DateTime 2015-11-26 12:30:46.023000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:30:46.023000000 Z content_type_id: chapter revision: 1 title: Research history title_internal: 'Libya: country, chapter 3' body: The Messak rock art has been known to Europeans since <NAME>’s expedition in 1850, although it was not until 1932 that the engravings were methodically studied by <NAME>. Some initial interpretative hypotheses about the rock art in the Acacus were formulated in the late 1930s by Italian archaeologist Paolo Graziosi. Subsequently, the region became the subject of systematic investigation by <NAME>, another Italian archaeologist, who also published the first scientific papers on Libyan rock art in the 1960s. Since then, consistent surveying has continued in this region and stratigraphic excavations of archaeological deposits have established a cultural sequence dating back to the Holocene Period. - sys: id: 5LSSbrA6FqIKi86kuWC0w0 created_at: !ruby/object:DateTime 2015-11-26 12:31:13.353000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:31:13.353000000 Z content_type_id: chapter revision: 1 title: Chronology and early rock art title_internal: 'Libya: country, chapter 4' body: |- Rock art chronology in North Africa is based largely on the combination of stylistic features, superimposition, subject matter and the degree of weathering or patina. While not an exact science, chronological periods are recognisable in the depictions, which generally correspond to climatic and environmental phases. Some of the oldest images are found on the Messak plateau and represent a Sahara that was significantly wetter and more fertile than today, exemplified by representations of large mammals – some of which are aquatic species – incised into the rock faces. The chronology of the Tadrart Acacus during the Holocene has been established more firmly through the excavation and dating of archaeological sites. Based on this evidence, these earliest images may coincide with the first Holocene occupation of the area by specialised hunter-gatherers – known as the 'Early Acacus' Period – which some researchers date to around 11,000 years ago. - sys: id: 3UZhGFp3eosaOSOaUGwEOs created_at: !ruby/object:DateTime 2015-11-26 12:27:31.261000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:27:31.261000000 Z content_type_id: image revision: 1 image: sys: id: 4eOnyF3wVymkGMgOkmQsYm created_at: !ruby/object:DateTime 2015-11-26 12:25:07.169000000 Z updated_at: !ruby/object:DateTime 2017-12-15 14:28:23.158000000 Z title: '2013,2034.3106' description: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3586141 url: "//images.ctfassets.net/xt8ne4gbbocd/4eOnyF3wVymkGMgOkmQsYm/ef9fa1bb02dc7c8ddb0ced9c9fcaa85e/2013_2034.3106.jpg" caption: Engraved image of a crocodile, <NAME>, <NAME>tafet. 2013,2034.3106 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3586141&partId=1&images=true&people=197356&museumno=2013,2034.3106&page=1 - sys: id: 4FFgcDY7xucWsKmsiUQa8E created_at: !ruby/object:DateTime 2015-11-26 12:31:36.221000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:31:36.221000000 Z content_type_id: chapter revision: 1 title: Round Head Period title_internal: 'Libya: country, chapter 5' body: From around 9,000 years ago, the archaeological record in the Acacus changes; sites are larger, featuring more formalised stone structures with heavy grinding equipment and large pots. Subsistence strategies based on hunting and gathering remain, but archaeological evidence suggests the presence of corralling Barbary sheep and the storage of wild cereals. Fragments of grinding stones with traces of colour from the Takarkori rock shelter, dating from between 6,800–5,400 BC, may have been used as palettes for rock or body painting, and have been connected chronologically to the Round Head Period. A large proportion of paintings in this period portray very large figures with round, featureless heads and can often be depicted in ‘floating’ positions; women often have their hands raised, interpreted as postures of supplication. - sys: id: 5zzGfyoQUw00yqkeuYuQ4M created_at: !ruby/object:DateTime 2015-11-26 12:28:01.442000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:28:01.442000000 Z content_type_id: image revision: 1 image: sys: id: 2diYKwS63u0MYs8eC4aesU created_at: !ruby/object:DateTime 2015-11-26 12:25:07.217000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:25:07.217000000 Z title: '2013,2034.899' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2diYKwS63u0MYs8eC4aesU/699e9277d3628340b4719c18a1f57ec4/2013_2034.899.jpg" caption: Round Head Period painting radiocarbon-dated to 8590±390 BP. Uan Tamuat, Acacus Mountains. 2013,2034.899 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3587474&partId=1&images=true&people=197356&museumno=2013,2034.899&page=1 - sys: id: 1UNszL8ap2g6CqEi60aUGC created_at: !ruby/object:DateTime 2015-11-26 12:32:06.214000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:32:06.214000000 Z content_type_id: chapter revision: 1 title: Pastoral Period title_internal: 'Libya: country, chapter 6' body: The introduction of domesticates into the region has been identified archaeologically at around 8,000 years ago, although full exploitation of cattle for dairying is much later at around 6,000 years ago. The development to full pastoral systems in the region is complex and prolonged, so it is challenging to track any changes from the rock art itself, but the painting of large herds must be connected to a full pastoral society. - sys: id: 65IyLhOxpecyEUyiQOaSe4 created_at: !ruby/object:DateTime 2015-11-26 12:28:36.906000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:28:36.906000000 Z content_type_id: image revision: 1 image: sys: id: 3EDRZDxlckISY0Gc0c44QK created_at: !ruby/object:DateTime 2015-11-26 12:25:03.853000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:25:03.853000000 Z title: '2013,2034.734' description: url: "//images.ctfassets.net/xt8ne4gbbocd/3EDRZDxlckISY0Gc0c44QK/9d3d834b088da6e1d5b97a8d01254d82/2013_2034.734.jpg" caption: Herders and cattle, <NAME>, Acacus Mountains. 2013,2034.734 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3586048&partId=1&images=true&people=197356&museumno=2013,2034.734&page=1 - sys: id: 1qfXWyJGO0SAIM40qw4aa4 created_at: !ruby/object:DateTime 2015-11-26 12:32:47.033000000 Z updated_at: !ruby/object:DateTime 2017-01-09 14:42:33.634000000 Z content_type_id: chapter revision: 2 title: Horse and Camel Periods title_internal: 'Libya: country, chapter 7' body: |- Historical records have tended to date the introduction of both the horse and the camel in northern Africa rather than the archaeological record. Yet, in terms of rock art research in this region, less attention has been given to these styles; the reason for this may be that the earliest rock art attracted more scholarly consideration than the later depictions. However, their representation certainly demonstrates the changing natural and cultural environment and associated human responses and adaptations. The rock art of Libya is a visual testament to the changing fortunes of this part of the Sahara and the cultural groups who have occupied and navigated the area over thousands of years. The engravings and paintings act as a legacy, tracing the environmental effects of climate change, how people have adapted to that change and the cultural worlds they have created. - sys: id: 33lGJfCTG0iWmcaMS8Miqy created_at: !ruby/object:DateTime 2015-11-26 12:29:09.712000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:29:09.712000000 Z content_type_id: image revision: 1 image: sys: id: 4ShhlHTP4A08k6Ck0WmCme created_at: !ruby/object:DateTime 2015-11-26 12:25:03.861000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:25:03.861000000 Z title: '2013,2034.1450' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4ShhlHTP4A08k6Ck0WmCme/c88441d7390ce9362b6ef2ab371070e9/2013_2034.1450.jpg" caption: Engraved figures on horseback. Awis, Acacus Mountains. 2013,2034.1450 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3592680&partId=1&images=true&people=197356&museumno=2013,2034.1450&page=1 citations: - sys: id: 51iLulV0KkWce0SIkgewo created_at: !ruby/object:DateTime 2015-11-26 12:25:53.864000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:25:53.864000000 Z content_type_id: citation revision: 1 citation_line: |- <NAME>., <NAME>, <NAME>, <NAME>, M.Legrand, <NAME> and <NAME>. 2005. *The Climate-Environment-Society Nexus in the Sahara from Prehistoric Times to the Present Day*. The Journal of North African Studies, Vol. 10, No 3-4, pp. 253-292 <NAME>. and <NAME>. 2001. *African Rock Art*. New York: H<NAME> di Lernia, S. 2012. Thoughts on the rock art of the Tadrart Acacus Mts., SW Libya. Adoranten pp. 19-37 Jelínek, J. 2004. *Sahara: Histoire de l’art rupestre libyen*. Grenoble: <NAME> <NAME>, J. 1998. *Art rupestre et préhistoire du Sahara: le Messak Libyen*. Paris: Payot & Rivages background_images: - sys: id: YbgSaS84Eu0gE8yKEcI48 created_at: !ruby/object:DateTime 2015-11-26 12:25:07.208000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:25:07.208000000 Z title: '2013,2034.1012' description: url: "//images.ctfassets.net/xt8ne4gbbocd/YbgSaS84Eu0gE8yKEcI48/c3cf27b1581df5b3cfed28e53439b4f8/2013_2034.1012.jpg" - sys: id: 4ShhlHTP4A08k6Ck0WmCme created_at: !ruby/object:DateTime 2015-11-26 12:25:03.861000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:25:03.861000000 Z title: '2013,2034.1450' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4ShhlHTP4A08k6Ck0WmCme/c88441d7390ce9362b6ef2ab371070e9/2013_2034.1450.jpg" - sys: id: 2diYKwS63u0MYs8eC4aesU created_at: !ruby/object:DateTime 2015-11-26 12:25:07.217000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:25:07.217000000 Z title: '2013,2034.899' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2diYKwS63u0MYs8eC4aesU/699e9277d3628340b4719c18a1f57ec4/2013_2034.899.jpg" region: Northern / Saharan Africa ---<file_sep>/_coll_country/algeria/crying-cows.md --- breadcrumbs: - label: Countries url: "../../" - label: Algeria url: "../" layout: featured_site contentful: sys: id: 47IFi4eXxuIaQ2Kkikkm4y created_at: !ruby/object:DateTime 2015-11-25 14:54:23.245000000 Z updated_at: !ruby/object:DateTime 2015-12-07 20:53:29.640000000 Z content_type_id: featured_site revision: 3 title: Crying cows, Algeria slug: crying-cows chapters: - sys: id: 3vWqlaPPKouEaiKsKIkAGm created_at: !ruby/object:DateTime 2015-11-25 14:52:16.750000000 Z updated_at: !ruby/object:DateTime 2015-11-25 14:52:16.750000000 Z content_type_id: chapter revision: 1 title_internal: 'Algeria: featured site, chapter 1' body: At the base of an inselberg at Tegharghart, south of Djanet, is a site that has come to be known as ‘Crying Cows’, because of the way teardrops appear to roll down the faces of the animals. - sys: id: 2CX1X82zg0Wm8OCikiCM2a created_at: !ruby/object:DateTime 2015-11-25 14:50:47.548000000 Z updated_at: !ruby/object:DateTime 2017-01-06 15:42:29.513000000 Z content_type_id: image revision: 2 image: sys: id: 6eeWLekeOI6MC2OO8SkAEk created_at: !ruby/object:DateTime 2015-11-25 14:49:37.233000000 Z updated_at: !ruby/object:DateTime 2015-11-25 14:49:37.233000000 Z title: '2013,2034.4323' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6eeWLekeOI6MC2OO8SkAEk/2ce480e7c388db97e2619927c84ca059/2013_2034.4323.jpg" caption: Polished cattle engravings belonging to the Early Hunter Period. Tegharghart, south of Djanet, Tassili n'Ajjer, Algeria. 2013,2034.4323 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3601754&partId=1&images=true&people=197356&museumno=2013,2034.4323&page=1 - sys: id: 4iofe61DXWSWEe2iIkmoQC created_at: !ruby/object:DateTime 2015-11-25 14:52:40.114000000 Z updated_at: !ruby/object:DateTime 2015-11-25 14:52:40.115000000 Z content_type_id: chapter revision: 1 title_internal: 'Algeria: featured site, chapter 2' body: |- These skilfully engraved images depict long-horned cattle with their heads bowed. Thought to date between 7,000 and 8,000 years ago, today these images stand alone in a vast wilderness of sand and rock. However, this environment was once wetter and more fertile, and this site may have been close to a local watering hole where animals regularly drank and bathed. Indeed, even today during the rains, the depression in the sand at the base of the inselberg fills up with water, which gives the appearance that the cows are bending their heads to drink. These engravings are incorporated in a local myth that tells of a shepherd who engraved the crying cows after travelling night and day with his herd to a spring he thought would quench their thirst. Finding it dry, he captured in stone his cattle’s grief as he watched them die one by one. Climatic data has shown a number of significant cooling events in the North Atlantic, one of which – dating to around eight thousand years ago – resulted in a period of aridity lasting a number of centuries across the Sahara, and may coincide with these engravings and of the associated myth. - sys: id: 1Amw4cfI1K6G6guu4aQQey created_at: !ruby/object:DateTime 2015-11-25 14:51:44.418000000 Z updated_at: !ruby/object:DateTime 2017-01-06 15:43:21.104000000 Z content_type_id: image revision: 2 image: sys: id: 4BNQt2lt84WMoouGQgc6G0 created_at: !ruby/object:DateTime 2015-11-25 14:49:37.249000000 Z updated_at: !ruby/object:DateTime 2015-11-25 14:49:37.249000000 Z title: '2013,2034.4328' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4BNQt2lt84WMoouGQgc6G0/96d40531dacc2538ad5c32de06190654/2013_2034.4328.jpg" caption: Close-up of polished cattle engravings. 2013,2034.4328 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3601772&partId=1&images=true&people=197356&museumno=2013,2034.4328&page=1 - sys: id: 6zymCcOSMo8AAimOWw0IuK created_at: !ruby/object:DateTime 2015-11-25 14:53:00.226000000 Z updated_at: !ruby/object:DateTime 2015-11-25 14:53:00.226000000 Z content_type_id: chapter revision: 1 title_internal: 'Algeria: featured site, chapter 3' body: In artistic terms, the execution of this panel of engraved cows is extremely accomplished and testifies to someone who was not only a skilful carver but who we might even regard as a sculptor in the modern sense, who understood both materials and the interplay of light and shade in the reductive process of carving. But even more than this, the artist understood the environmental conditions in which he was working. It has been observed that the depth and thickness of the engraved lines has been carefully calculated to ensure that as the sun travels across them during the day, they appear to move. This sense of movement is made most acute as the evening shadows, falling into each groove, give the cattle a sense of mass and movement. Other artistic devices, such as double lines with recessed areas and internal polishing, evoke a perception of depth and density. The interplay of light and shade is consummately adept and dynamic, and the sculptural quality of the image sensorially evocative. This is the work of a practised craftsman, who demonstrates a deep of understanding of materials, techniques and the natural environment. background_images: - sys: id: 3bwDgmmud2wssS4kAi0YMe created_at: !ruby/object:DateTime 2015-12-07 20:09:47.529000000 Z updated_at: !ruby/object:DateTime 2015-12-07 20:09:47.529000000 Z title: ALGDJA0010009 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3bwDgmmud2wssS4kAi0YMe/e6733b7060e67b2e94eecf1e08563a1b/ALGDJA0010009.jpg" - sys: id: 7vsU1HA1s44SaSkK2mGiAU created_at: !ruby/object:DateTime 2015-12-07 20:09:47.502000000 Z updated_at: !ruby/object:DateTime 2015-12-07 20:09:47.502000000 Z title: ALGTDR0140002 description: url: "//images.ctfassets.net/xt8ne4gbbocd/7vsU1HA1s44SaSkK2mGiAU/cfa5804c371b2239e6d843593c6297fd/ALGTDR0140002.jpg" ---<file_sep>/_coll_country_information/angola-country-introduction.md --- contentful: sys: id: 3FI9toCf966mwqGkewwm62 created_at: !ruby/object:DateTime 2016-07-27 07:44:28.009000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:44:28.009000000 Z content_type_id: country_information revision: 1 title: 'Angola: country introduction' chapters: - sys: id: 4c7LrgmhRm6oEIsmKMyICO created_at: !ruby/object:DateTime 2016-07-27 07:45:13.048000000 Z updated_at: !ruby/object:DateTime 2016-07-27 09:10:43.664000000 Z content_type_id: chapter revision: 2 title: Introduction title_internal: 'Angola: country, chapter 1' body: 'Angola is a country located in the south-west of Africa, stretching from the Atlantic Ocean to the centre of the continent. Angolan rock art consists both of engravings and paintings, and is mostly located relatively near to the coast, although some sites have also been documented in the easternmost part of the country, near the border with Zambia. Depictions are very varied, representing animals, human figures and geometric signs, in many cases grouped in hunting or war scenes. In some cases, firearms appear represented, showing the period of contact with Europeans from the 1500s onwards. ' - sys: id: 6d4OdBQujeqc8gYMAUaQ8 created_at: !ruby/object:DateTime 2016-07-27 07:45:16.855000000 Z updated_at: !ruby/object:DateTime 2017-01-24 16:43:02.760000000 Z content_type_id: image revision: 3 image: sys: id: 3fc97FP7N6Q4qaYY82yMee created_at: !ruby/object:DateTime 2016-07-27 07:48:02.366000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:48:02.366000000 Z title: ANGTCH0010008 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3fc97FP7N6Q4qaYY82yMee/f28490284dadb197c3aafc749fd9de88/ANGTCH0010008.jpg" caption: "Painted group of white, red and dark red geometric signs. Tchitundu-Hulu Mucai, Angola. 2013,2034.21211\t© TARA/<NAME>" col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3744321&partId=1 - sys: id: 1LCP4wqQiYI4wSiSqsagwK created_at: !ruby/object:DateTime 2016-07-27 07:45:12.894000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:45:12.894000000 Z content_type_id: chapter revision: 1 title: Geography and rock art distribution title_internal: 'Angola: country, chapter 2' body: Angola has a variety of climates. The flat coastal plain ranges between 25 and 150 km in width, and is a semiarid region covered by scrub, turning into sand dunes to the south, near Namibia. The coastal region abruptly gives way to a series of mountains and escarpments divided by the Cuanza River. The northern part has an average height of 500 m, but the southern region is far higher, with the peaks occasionally exceeding 2,300 m. This mountainous region is in fact a transitional area between the coastal plain and the great central plateau of Africa. This plateau dominates Angola’s geography with an altitude from 1,200 to 1,800 m, and consists of a region of plains and low hills with a tropical climate. The climate becomes drier to the south and wetter to the north, where a wide region of the country can be defined as rainforest. - sys: id: 4hwTXZMXe00gwO6uoyKY0Y created_at: !ruby/object:DateTime 2016-07-27 07:45:16.770000000 Z updated_at: !ruby/object:DateTime 2017-01-24 16:43:30.163000000 Z content_type_id: image revision: 3 image: sys: id: 2EhlaF5U6Qui8SueE66KUO created_at: !ruby/object:DateTime 2016-07-27 07:48:02.353000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:48:02.353000000 Z title: ANGTCH0010001 description: url: "//images.ctfassets.net/xt8ne4gbbocd/2EhlaF5U6Qui8SueE66KUO/0329cbdac83a8bc3b9bbaff953025630/ANGTCH0010001.jpg" caption: Aerial view of landscape showing a valley and a plateau in south-western Angola. Namibe Province, Angola. 2013,2034.21204 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3744306&partId=1 - sys: id: 6oDRzpZCTe0cioMMk0WmGs created_at: !ruby/object:DateTime 2016-07-27 07:45:12.825000000 Z updated_at: !ruby/object:DateTime 2016-07-27 10:00:25.820000000 Z content_type_id: chapter revision: 2 title: '' title_internal: 'Angola: country, chapter 3' body: 'Rock art in Angola is primarily located in the coastal region, from north to south, with a clear concentration in its central area. However some rock art sites have also been discovered in the interior of the country, especially in its east-central region, and therefore this concentration in the coast could be explained by different research priorities in the past. Although both paintings and engravings are present in Angolan rock art, the latter seem to be predominant near the coast, while paintings are more common in the interior and to the south. ' - sys: id: 48podTUsCQm2Aai0M2CkqY created_at: !ruby/object:DateTime 2016-07-27 07:45:12.824000000 Z updated_at: !ruby/object:DateTime 2016-10-17 15:35:38.140000000 Z content_type_id: chapter revision: 2 title: Research history title_internal: 'Angola: country, chapter 4' body: 'Although there are some references in Portuguese chronicles from the 1500s and 1600s which could correspond to rock art paintings, the first clear mention of a rock art site was made in 1816 with research only starting in 1939, when <NAME> published the first news about engravings of Angola. Since then, research was intermittent until the 1950s, when the important site of Tchitundu-Hulu was studied and published. The relevance of Tchitundu-Hulu attracted the attention of important scholars such as <NAME> and the <NAME>, who along with Portuguese researchers contextualized Angolan rock art within the continent. Research increased significantly over the next two decades, but during the 1980s political instability gave way to a period of stagnation until the 1990s, when new researchers began comprehensive surveys and organised the available rock art information. ' - sys: id: 19eEn5GF9e0Yqk4yYmoqKg created_at: !ruby/object:DateTime 2016-07-27 07:45:12.784000000 Z updated_at: !ruby/object:DateTime 2018-05-09 16:25:10.620000000 Z content_type_id: chapter revision: 3 title: 'Themes ' title_internal: 'Angola: country, chapter 5' body: 'The rock art in Angola has a wide variety of styles and themes, depending on the region and the chronology. The oldest images are painted or engraved geometric symbols and anthropomorphic figures. More recent depictions include axes, spears and firearms. The latest period of the Angolan rock art includes complex scenes of war and hunting, and in a number of cases human figures are carried on a palanquin-like structure. Although schematic figures are widespread throughout the country, they are predominant in the south-west where most of the sites have been compared to those in the Central Africa Schematic Art zone, with parallels in Malawi and Mozambique. In the west-central area of Angola, in addition to the schematic symbols and animals, images of men holding weapons, fighting and hunting are common, including warriors holding firearms which make reference to the first contact with Europeans by the 16th century. Near the north-west coast, some of the paintings and engravings have been related to objects used in religious ceremonies – wooden statuettes or decorated pot lids. In particular, a close association has been established between rock art depictions and the so-called Cabinda pot lids, which have different carved symbols—animals, objects, human figures—acting as a shared visual language. ' - sys: id: avBmltKXBKIac040I4im4 created_at: !ruby/object:DateTime 2016-07-27 07:45:16.027000000 Z updated_at: !ruby/object:DateTime 2016-07-27 09:13:04.815000000 Z content_type_id: image revision: 2 image: sys: id: 6JWgcpb6JUq0yCegs4MsGc created_at: !ruby/object:DateTime 2016-07-27 07:46:36.335000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:36.335000000 Z title: ANGTCH0010006 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6JWgcpb6JUq0yCegs4MsGc/6f9bad737cd113899538299e444e8007/ANGTCH0010006.jpg" caption: Paintings showing geometric signs, an unidentified quadruped and a bird (?) infilled with red and white lines. Tchitundu-Hulu Mucai, Angola. 2013,2034.21209 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3744323&partId=1 - sys: id: 2I6ljlCWZyAmqm8Gq402IE created_at: !ruby/object:DateTime 2016-07-27 07:45:12.760000000 Z updated_at: !ruby/object:DateTime 2016-07-27 09:16:27.004000000 Z content_type_id: chapter revision: 2 title: " Chronology" title_internal: 'Angola: country, chapter 6' body: 'As is so often the case with rock art, the dating of images is complex due to the absence of direct correlations between rock art depictions and well contextualised archaeological remains. Some of the sites with rock art have been excavated showing dates of the 7th millennium BC, but the relationship with the rock art is unclear. In the Tchitundu-Hulu Mulume site, the excavation at the cave provided a 1st millennium BC date, and the only radiocarbon date taken from the pigments at this site provided a date of the 1st century AD, which corresponds with other dates of the same style in Central Africa. The second tool for assigning a chronology is the analysis of the subject matter represented in the rock art depictions: the presence of metal objects, for example, would imply a date of the 1st millennium AD onwards, when this material was introduced. Whereas, depictions featuring images of firearms would date from the 16th century onwards. The end of the rock art tradition has been associated with the presence of Europeans but was probably progressive as the control of the region by the Portuguese grew during the 17th and 18th centuries. ' - sys: id: 1oBOeAZi0QEmAsekMIgq88 created_at: !ruby/object:DateTime 2016-07-27 07:45:15.908000000 Z updated_at: !ruby/object:DateTime 2018-05-09 16:27:56.903000000 Z content_type_id: image revision: 3 image: sys: id: 40lIKwvi8gwo4ckmuKguYk created_at: !ruby/object:DateTime 2016-07-27 07:47:54.905000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:47:54.905000000 Z title: ANGTCH0010022` description: url: "//images.ctfassets.net/xt8ne4gbbocd/40lIKwvi8gwo4ckmuKguYk/074e930f8099bbfdf9dd872f874c3a32/ANGTCH0010022.jpg" caption: Pecked concentric circles. Tchitundu-Hulu Mulume, Angola. 2013,2034.21225 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3744347&partId=1 citations: - sys: id: 6qVsC6snf24G0ImyC6yGY8 created_at: !ruby/object:DateTime 2016-07-27 07:45:30.575000000 Z updated_at: !ruby/object:DateTime 2016-07-27 10:00:54.672000000 Z content_type_id: citation revision: 2 citation_line: "<NAME>. Desmond & <NAME>. van, 1963. *Prehistoric cultures of northeast Angola and their significance in tropical Africa*. Companhia de Diamantes de Angola, Lisboa, Servicos Culturais \n\nGutierrez, M. 1996. *L'art parietal de l'Angola*. L’Harmattan, Paris \n\nGutierrez, M. 2009. 'Rock Art and Religion: the site of <NAME>, Angola'. *The South African Archaeological Bulletin 64 (189)* pp. 51-60\n" ---<file_sep>/_coll_country/zimbabwe/matobo.md --- breadcrumbs: - label: Countries url: "../../" - label: Zimbabwe url: "../" layout: featured_site contentful: sys: id: 196SFAKyP2Ec0gqcWAkawG created_at: !ruby/object:DateTime 2016-09-12 11:55:26.290000000 Z updated_at: !ruby/object:DateTime 2016-09-13 13:33:48.421000000 Z content_type_id: featured_site revision: 4 title: Matobo Hills, Zimbabwe slug: matobo chapters: - sys: id: dcn9MCXYc02mqO620qoe8 created_at: !ruby/object:DateTime 2016-09-12 11:53:51.731000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:53:51.731000000 Z content_type_id: chapter revision: 1 title_internal: 'Zimbabwe: featured site, chapter 1' body: 'The Matobo Hills (also spelled as Matopo or Matopos Hills) are located to the south-west of Zimbabwe, in Matabeleland, one of the two main rock art regions in the country. It is a large region, more than 2000 sq. km, characterized by granite hills separated by nearly parallel valleys where the vegetation consists of scattered woodlands and areas covered by grass with an abundance of wild fruits. The region was occupied since at least the Middle Stone Age, but the human presence increased in the last millennia BC. The region holds an incredible amount of rock art; as many as 3,000 sites have been estimated based on the better surveyed areas. Paintings constitute the vast majority of depictions, although occasional engravings have also been reported. Paintings are usually found in rock shelters and associated with archaeological remains, which show an occupation of the area since the Early Stone Age. ' - sys: id: N3RjMUjWecQWss48koUyG created_at: !ruby/object:DateTime 2016-09-12 11:56:26.939000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:56:26.939000000 Z content_type_id: image revision: 1 image: sys: id: Jy8edAwMCGiAywQIyi0KI created_at: !ruby/object:DateTime 2016-09-12 11:56:31.534000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:56:31.534000000 Z title: ZIMMTB0100001 description: url: "//images.ctfassets.net/xt8ne4gbbocd/Jy8edAwMCGiAywQIyi0KI/4d9692d057fadcc525259a3eb75c00ba/ZIMMTB0100001.jpg" caption: Ladscape of the Matobo Hills, Zimbabwe (2013,2034.23586). ©TARA/David Coulson - sys: id: 7Mivw9c0Q8osQi802O6gwO created_at: !ruby/object:DateTime 2016-09-12 11:53:51.437000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:53:51.437000000 Z content_type_id: chapter revision: 1 title_internal: 'Zimbabwe: featured site, chapter 2' body: 'The rock art of the Matobo Hills is as varied as that of the rest of Zimbabwe, mainly consisting of depictions of animals and human figures often grouped in complex scenes, clustered or represented in rows. Human figures are predominant, with males being more numerous than women and children very rare. They are usually depicted in a slender style, facing left or right but with the upper part of the body facing front, and often carrying bows, arrows or other objects. Regarding the animals, mammals dominate, with the kudu antelope being especially numerous although this animal is not commonly found in the Matobo Hills. A wide range of animals such as smaller antelopes, giraffes, zebras, ostriches, monkeys, eland antelope, rhinoceros and to a lesser extent carnivores are also depicted. The animals are represented in very different attitudes and may be depicted standing still, running or lying. Humans and animals are often related in hunting scenes. Along with animals and human figures, a fair number of geometric symbols are present, including a very characteristic type of motif made of a series of narrow oval-like shapes (formlings) usually depicted vertically, and sometimes interpreted as beehives. ' - sys: id: 1ueCDk3QMc40WGC6gk0qsE created_at: !ruby/object:DateTime 2016-09-12 11:56:47.135000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:56:47.135000000 Z content_type_id: image revision: 1 image: sys: id: 4JrH9kFufCQkEwgGqycIQG created_at: !ruby/object:DateTime 2016-09-12 11:56:43.328000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:56:43.328000000 Z title: ZIMMTB0020005 description: url: "//images.ctfassets.net/xt8ne4gbbocd/4JrH9kFufCQkEwgGqycIQG/da276b8b7efba382dc16df58e2c43bef/ZIMMTB0020005.jpg" caption: View of a complex panel including hundreds of human figures, animals, formlings and other unidentified shapes. <NAME>, Matabeleland, Zimbabwe (2013,2034.23350). ©TARA/<NAME> - sys: id: 2Kp0Cep9RmeI4gyMAMMaCy created_at: !ruby/object:DateTime 2016-09-12 11:53:51.486000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:53:51.486000000 Z content_type_id: chapter revision: 1 title_internal: 'Zimbabwe: featured site, chapter 3' body: 'One of the characteristics of the Matobo Hills rock art is the incredible variety of colours used, which includes a wide range of reds, purples, oranges, browns and yellows, as well as black, white and grey tones. Colours are often combined, and in some cases particular colours seem to have been chosen for specific animals. A common feature in some types of animals as giraffes and antelopes is the outline of the figure in red or white, with the body infilled in a different colour. ' - sys: id: 3dGEtOvk6k6i6wQSUsu2I created_at: !ruby/object:DateTime 2016-09-12 11:56:54.742000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:56:54.742000000 Z content_type_id: image revision: 1 image: sys: id: 3ZbDDzdXZuKCEEWWm2WUoE created_at: !ruby/object:DateTime 2016-09-12 11:56:59.400000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:56:59.400000000 Z title: ZIMMTB0020022 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3ZbDDzdXZuKCEEWWm2WUoE/67d4eba9ebb89aaf8394676637773ba5/ZIMMTB0020022.jpg" caption: Detail of a bichrome giraffe surrounded by other animals and human figures. In<NAME>, Matabeleland, Zimbabwe (2013,2034.23367). ©TARA/<NAME> - sys: id: 7zD4PqA2mQyY0yCYUYS6wk created_at: !ruby/object:DateTime 2016-09-12 11:53:51.426000000 Z updated_at: !ruby/object:DateTime 2016-09-13 13:33:12.839000000 Z content_type_id: chapter revision: 5 title_internal: 'Zimbabwe: featured site, chapter 4' body: "Many of the depictions in the Matobo Hills are associated with hunter-gatherers, providing a great amount of information about the social, economic and spiritual life of these groups. Depictions of daily objects (bows, vessels, digging sticks, cloaks) appear depicted in the rock art, and humans are shown hunting animals, fighting other groups and dancing in what seem to be ritual scenes. In fact, many of the scenes show strong similarities to those found in the Drakensberg (South Africa), and part of the iconography in the Zimbabwean paintings – ‘therianthropes’ (part-human, part-animal figures), elongated figures, rain animals, geometric figures – can be easily related to trance or rain-making activities similar to those seen in South Africa. These paintings have been interpreted as representing the trance experiences of shamans (the term ‘shaman’ is derived from Siberian concepts of Shamanism and its applicability to San&#124;Bushman¹ cultures has been questioned, but it is utilised here on the understanding that it sufficiently represents trancers in this academic context, where it is the most frequently used term to describe them). However, unlike in South Africa, the Matobo Hills rock art is not recent and researchers lack the key ethnographic records that help us to interpret the paintings. Therefore, interpretations cannot be directly extrapolated from the South African paintings to those of the Matobo Hills, and researchers such as <NAME> have broadened the interpretative framework of this art to include social issues in addition to the religious. \n\n" - sys: id: 5njv3ZB8WWG0e2MkM4wuIw created_at: !ruby/object:DateTime 2016-09-12 11:57:11.432000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:57:11.432000000 Z content_type_id: image revision: 1 image: sys: id: 1vZtYjldh2UmCICQEIC8UG created_at: !ruby/object:DateTime 2016-09-12 11:57:17.337000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:57:17.337000000 Z title: ZIMMTB0010007 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1vZtYjldh2UmCICQEIC8UG/18487324c77eb308393d900eb5f4a3c4/ZIMMTB0010007.jpg" caption: Human figures running or seated over a wavy, yellow line outlined in red and infilled in yellow. Maholoholo cave, Matabeleland, Zimbabwe (2013,2034.23327). ©TARA/<NAME> - sys: id: 2MAT92oDegwysmWWecW8go created_at: !ruby/object:DateTime 2016-09-12 11:53:51.570000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:53:51.570000000 Z content_type_id: chapter revision: 1 title_internal: 'Zimbabwe: featured site, chapter 5' body: 'Not all the paintings in the Matobo Hills can be ascribed to groups of hunter gatherers, though. Although fewer, there are some paintings that correspond to a later period which were made by Iron Age farmers. Unlike in South Africa, rock art does not show evidence of interaction between these two groups, and it is probable that the hunter-gatherers that inhabited the area were either displaced or absorbed by these new farmer communities. However, some of the later paintings show some links with the previous hunter-gatherers traditions. This later art consists mainly of schematic figures (usually animals, including domestic ones such as goats and cows) and geometric symbols, mostly depicted in white but also red or black and smeared with the hand or the fingers. ' - sys: id: 1U1ln6bdtSIGYYiKu0M68M created_at: !ruby/object:DateTime 2016-09-12 11:57:35.126000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:57:35.126000000 Z content_type_id: image revision: 1 image: sys: id: 1iRymPGEvYW4YUwsWCuw66 created_at: !ruby/object:DateTime 2016-09-12 11:57:30.948000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:57:30.948000000 Z title: ZIMMTB0070009 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1iRymPGEvYW4YUwsWCuw66/6d6a5a4e658e2c74a771bdf36a8052a8/ZIMMTB0070009.jpg" caption: Iron age white paintings. Zimbabwe (2013,2034.23487). ©TARA/<NAME> - sys: id: 5MtdMVT44MIamC44CmcMog created_at: !ruby/object:DateTime 2016-09-12 11:53:51.463000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:53:51.463000000 Z content_type_id: chapter revision: 1 title_internal: 'Zimbabwe: featured site, chapter 6' body: 'The Matobo Hills constitute a perfect example of how nature and human presence can become imbricated, to create a living landscape in which every hill is recognized individually and many of them are still venerated by the communities living in the area. Undoubtedly, rock art played a significant role in this process of progressive sacralisation of the landscape. The importance of the thousands of sites scattered throughout the hills is an invaluable testimony of the strong spirituality of hunter-gatherers that created it, and their deep relation to the land in which they lived. ' - sys: id: 1Y6kzmIX4AimYGC4AYQM4 created_at: !ruby/object:DateTime 2016-09-12 11:57:43.734000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:57:43.734000000 Z content_type_id: image revision: 1 image: sys: id: AlCcF5GAcC44Q268AUsuq created_at: !ruby/object:DateTime 2016-09-12 11:57:48.037000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:57:48.037000000 Z title: ZIMMTB0100024 description: url: "//images.ctfassets.net/xt8ne4gbbocd/AlCcF5GAcC44Q268AUsuq/1a776553071d70cc070382226c7dc5ab/ZIMMTB0100024.jpg" caption: Antelopes and human figures. Bambata cave, Matabeleland, Zimbabwe (2013,2034.23609). ©TARA/<NAME> - sys: id: 4cN05gyK9aWYwscgeMuA4E created_at: !ruby/object:DateTime 2016-09-13 13:33:44.736000000 Z updated_at: !ruby/object:DateTime 2016-09-13 13:33:44.736000000 Z content_type_id: chapter revision: 1 title_internal: Matobo Chapter 7 body: "¹ San&#124;Bushmen is a collective term used to describe the many different hunter-gatherer-fisher groups living in southern Africa who have related languages and cultural traditions. Both 'San' and 'Bushmen' are considered offensive terms by some members of these groups, although others have positively adopted them." citations: - sys: id: nZhwDQUvyCcK8kYqoWWK2 created_at: !ruby/object:DateTime 2016-09-12 11:54:06.690000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:54:06.690000000 Z content_type_id: citation revision: 1 citation_line: "<NAME>. (2012): The Rock Art of the Matobo Hills, Zimbabwe. Adoranten: 38-59\n\nParry, Elspeth (2012): Guide to the Rock Art of the Matopo Hills, Zimbabwe. Bulawayo, AmaBooks Publishers. \n" background_images: - sys: id: Jy8edAwMCGiAywQIyi0KI created_at: !ruby/object:DateTime 2016-09-12 11:56:31.534000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:56:31.534000000 Z title: ZIMMTB0100001 description: url: "//images.ctfassets.net/xt8ne4gbbocd/Jy8edAwMCGiAywQIyi0KI/4d9692d057fadcc525259a3eb75c00ba/ZIMMTB0100001.jpg" - sys: id: 1iRymPGEvYW4YUwsWCuw66 created_at: !ruby/object:DateTime 2016-09-12 11:57:30.948000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:57:30.948000000 Z title: ZIMMTB0070009 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1iRymPGEvYW4YUwsWCuw66/6d6a5a4e658e2c74a771bdf36a8052a8/ZIMMTB0070009.jpg" ---<file_sep>/_coll_country/botswana.md --- contentful: sys: id: 1QI5QPfF6UcwcCK0m4c4aK created_at: !ruby/object:DateTime 2015-12-08 11:21:19.798000000 Z updated_at: !ruby/object:DateTime 2018-05-15 13:39:16.998000000 Z content_type_id: country revision: 13 name: Botswana slug: botswana col_url: 'http://www.britishmuseum.org/research/collection_online/search.aspx?people=197356&place=19305|108608|108619|108618|108610|108613|108574|108572|108562|108568|108571|108570|108557|108558|14789|108560 ' map_progress: true intro_progress: true image_carousel: - sys: id: 3y9Kyv4t440uAwuYqSiwmc created_at: !ruby/object:DateTime 2016-09-12 11:09:15.644000000 Z updated_at: !ruby/object:DateTime 2019-02-12 02:12:34.714000000 Z title: '2013,2034.20653' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3757916&partId=1&searchText=BOTTSD0040008&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/3y9Kyv4t440uAwuYqSiwmc/be7de353c85797e38b480c1000c63690/BOTTSD0040008_jpeg.jpg" - sys: id: 6pHrsUcc2kaeKqeEcO0WmW created_at: !ruby/object:DateTime 2016-09-12 11:09:24.045000000 Z updated_at: !ruby/object:DateTime 2019-02-12 02:13:24.351000000 Z title: '2013,2034.21107' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3762101&partId=1&searchText=BOTTSD1170002&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/6pHrsUcc2kaeKqeEcO0WmW/c92b5e947430fcfbf28de83322cb1241/BOTTSD1170002_jpeg.jpg" - sys: id: 2vlf46R3veEcs28C8MuCMK created_at: !ruby/object:DateTime 2016-09-12 11:09:35.337000000 Z updated_at: !ruby/object:DateTime 2019-02-12 02:15:16.580000000 Z title: '2013,2034.21147' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3762173&partId=1&searchText=BOTTSDNAS0010002&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/2vlf46R3veEcs28C8MuCMK/31642ccafef62968c186cc3608d1ea53/BOTTSDNAS0010002_jpeg.jpg" featured_site: sys: id: 4LLcZZwsVO2SOacCKoc2Ku created_at: !ruby/object:DateTime 2016-09-12 11:02:35.091000000 Z updated_at: !ruby/object:DateTime 2016-09-13 13:32:13.193000000 Z content_type_id: featured_site revision: 7 title: Tsodilo Hills, Botswana slug: tsodilo chapters: - sys: id: 28cyW9T0iUqYugWyq8cmWc created_at: !ruby/object:DateTime 2016-09-12 11:30:29.590000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:30:29.590000000 Z content_type_id: chapter revision: 1 title: Introduction title_internal: 'Botswana: featured site, chapter 1' body: '<NAME>, located in north-west Botswana, contains around 400 rock art sites with more than 4,000 individual paintings, and has been termed the “The Louvre of the Desert”. Designated a World Heritage Site by UNESCO in 2001, Tsodilo comprises four main hill: Male Hill, Female Hill, Child Hill and North Hill with paintings occurring on all four. This region shows human occupation going back 100,000 years. At sunset the western cliffs of the Hills radiate a glowing light that can be seen for miles around, for which the local Juc’hoansi call them the “Copper Bracelet of the Evening”.' - sys: id: BUqVZ44T2Cw0oguCqa0Ui created_at: !ruby/object:DateTime 2016-09-12 11:31:14.266000000 Z updated_at: !ruby/object:DateTime 2018-05-11 16:05:40.114000000 Z content_type_id: image revision: 2 image: sys: id: 1sR7vldVp2WgiY8MUyWI8E created_at: !ruby/object:DateTime 2016-09-12 11:40:46.655000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:40:46.655000000 Z title: BOTTSDNAS0010008 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1sR7vldVp2WgiY8MUyWI8E/3ee38dc4339bc8831fbc27c32789652b/BOTTSDNAS0010008_jpeg.jpg" caption: The evening light falls on the cliffs of Female Hill causing them to glow like burnished copper, and giving the Hills the name 'Copper Bracelet of the Evening'. 2013,2034.21153 © TARA/ <NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3762166&partId=1&searchText=2013,2034.21153&page=1 - sys: id: Yer3GOpD8siKgO0iwcaSo created_at: !ruby/object:DateTime 2016-09-12 11:30:29.644000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:30:29.644000000 Z content_type_id: chapter revision: 1 title: Rock Art title_internal: 'Botswana: featured site, chapter 2' body: The paintings at Tsodilo are unique in comparison to other San&#124;Bushmen rock art in both techniques and subject matter. San&#124;Bushmen paintings are well-known throughout southern Africa for their fine-line detail because they were brush painted, but those at Tsodilo are finger painted. In addition, 160 depictions of cattle are portrayed in the same style as wild animals, and more geometric designs appear here than anywhere else. Tsodilo animal drawings are larger and the geometric designs simpler than those found elsewhere. In comparison to human figures elsewhere in southern Africa, those at Tsodilo appear without bows and arrows, clothing or any forms of personal ornamentation. In addition, numerous cupules and grooves are incised and ground into rock surfaces, sometimes close to painted rock art sites and some on their own. For the residents of Tsodilo, the hills are a sacred place inhabited by spirits of the ancestors. - sys: id: 43rtUm8qI8KmCcYYMSOgmq created_at: !ruby/object:DateTime 2016-09-12 11:30:29.677000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:30:29.677000000 Z content_type_id: chapter revision: 1 title: The Red Paintings title_internal: 'Botswana: featured site, chapter 3' body: 'The subject matter of red finger-painted depictions can be divided into animals, human figures and geometric designs. Unusually, animals, mainly large mammals and cattle have been depicted in twisted perspective with two horns and two or four legs displayed in silhouette. ' - sys: id: 3ImTBIKi2I6UKK0kOU6QuI created_at: !ruby/object:DateTime 2016-09-12 11:31:54.679000000 Z updated_at: !ruby/object:DateTime 2018-05-11 16:06:23.440000000 Z content_type_id: image revision: 2 image: sys: id: 1ciquTlk7CuacgoUmGW4ko created_at: !ruby/object:DateTime 2016-09-12 11:40:59.662000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:40:59.662000000 Z title: BOTTSD0100011 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1ciquTlk7CuacgoUmGW4ko/e1c26a2555f8949c83f4f3075453266f/BOTTSD0100011_jpeg.jpg" caption: An eland with a calf. Gubekho Gorge, Tsodilo Hills 2013,2034.20700. © TARA/ <NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3758016&partId=1&searchText=2013,2034.20700&page=1 - sys: id: 4erJYWZNlCKAQwwmIGCMMK created_at: !ruby/object:DateTime 2016-09-12 11:30:29.705000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:30:29.705000000 Z content_type_id: chapter revision: 1 title_internal: 'Botswana: featured site, chapter 4' body: 'Human figures are schematic and depicted by two intersecting lines, a vertical line which thickens at the middle to indicate hips and buttocks, and the other a horizontal shorter line joined at the middle to represent a penis. Female figures are depicted with two legs and show two projections near the top indicating breasts. ' - sys: id: 3z6hr5zWeA8uiwQuIOU4Me created_at: !ruby/object:DateTime 2016-09-12 11:32:03.882000000 Z updated_at: !ruby/object:DateTime 2018-05-11 16:07:16.062000000 Z content_type_id: image revision: 2 image: sys: id: 3o0or3SkLeYGGUoAY0eesW created_at: !ruby/object:DateTime 2016-09-12 11:41:14.546000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:41:14.546000000 Z title: BOTTSD0350003 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3o0or3SkLeYGGUoAY0eesW/76825491efe27f5d7281812cf374f201/BOTTSD0350003_jpeg.jpg" caption: This panel of figures shows men with penises and women with breasts appearing to perform a ceremony with a domestic cow. Female Hill, Tsodilo Hills. 2013,2034.20891 © TARA/ <NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3761502&partId=1&searchText=2013,2034.20891&page=1 - sys: id: 2sRPLGg0x20QMQWwoSgKAa created_at: !ruby/object:DateTime 2016-09-12 11:30:29.552000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:30:29.552000000 Z content_type_id: chapter revision: 1 title_internal: 'Botswana: featured site, chapter 5' body: 'Geometric designs include circles and ovals with internal grid patterns, rectilinear motifs termed “shields”, some handprints and rows of finger impressions. In addition, there are a number of rectangular motifs that have been called “stretched skins”. Similar designs have been found in Zambia, Angola, Namibia, northern South Africa and Malawi. ' - sys: id: 2hIErx8hcciSyMwOKKSqiY created_at: !ruby/object:DateTime 2016-09-12 11:32:11.837000000 Z updated_at: !ruby/object:DateTime 2018-05-11 16:11:48.100000000 Z content_type_id: image revision: 2 image: sys: id: 6vCru3T4QwO8kSOSSUwOsG created_at: !ruby/object:DateTime 2016-09-12 11:41:29.254000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:41:29.254000000 Z title: BOTTSD0100003 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6vCru3T4QwO8kSOSSUwOsG/9fa827f96116559169a415bb2abe204f/BOTTSD0100003_jpeg.jpg" caption: Rectangular motif known as a “stretched skin”. <NAME>, Tsodilo Hills. 2013,2034.20692 © TARA/ <NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3758002&partId=1&searchText=2013,2034.20692&page=1 - sys: id: 28VhGOdi2A2sKIG20Wcsua created_at: !ruby/object:DateTime 2016-09-12 11:30:29.799000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:30:29.799000000 Z content_type_id: chapter revision: 1 title_internal: 'Botswana: featured site, chapter 6' body: While most of the images in the Tsodilo Hills seem to be discrete depictions, some sites show figures. Some of these figures are with cattle as well as women standing in rows in connection with animal groups, possibly showing some relationship with each other. Additionally, some of the rock art in the Tsodilo Hills shows superimposition, but this occurs infrequently. In some cases red geometric designs superimpose animals, but geometric designs and animals never superimpose human figures, nor do images of cattle ever superimpose other images – which may suggest some kind of relationship or hierarchy. - sys: id: 2W4qNU8IVWQAyuuoaaaYCE created_at: !ruby/object:DateTime 2016-09-12 11:30:29.588000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:30:29.588000000 Z content_type_id: chapter revision: 1 title: Late White Paintings title_internal: 'Botswana: featured site, chapter 7' body: White finger-painted images appear more crudely executed and are made from a powdery or greasy white pigment. More than 200 paintings at 20 different sites show paintings in this style, half of these depictions occur in White Paintings Shelter alone. Subject matter includes people facing forwards with their hands on hips, figures riding horses, a possible wagon wheel and a figure standing on a wagon, as well as an elephant, rhino, giraffe, eland, cows, antelope, snakes, unidentified animals and geometric designs, particularly “m” shapes. White paintings occur at sites with red paintings and often superimpose them. - sys: id: 3szVgL4Drqs2eicWcmKIaI created_at: !ruby/object:DateTime 2016-09-12 11:32:18.860000000 Z updated_at: !ruby/object:DateTime 2018-05-11 16:12:37.841000000 Z content_type_id: image revision: 2 image: sys: id: k0cOVVuRnUmcWEYUQsuiG created_at: !ruby/object:DateTime 2016-09-12 11:41:41.851000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:41:41.851000000 Z title: BOTTSD0590001 description: url: "//images.ctfassets.net/xt8ne4gbbocd/k0cOVVuRnUmcWEYUQsuiG/98eaf4781fbe7a6b0a4a7a395808f618/BOTTSD0590001_jpeg.jpg" caption: Painted white geometric designs on a protected rock face. Female Hill, Tsodilo Hills. © TARA/ <NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3761865&partId=1&searchText=2013,2034.20999&page=1 - sys: id: 6zm0EQehBCyEiWKIW8QkmC created_at: !ruby/object:DateTime 2016-09-12 11:30:30.484000000 Z updated_at: !ruby/object:DateTime 2018-05-15 12:43:48.178000000 Z content_type_id: chapter revision: 3 title: Cupules/Grooves title_internal: 'Botswana: featured site, chapter 8' body: There are no engravings at Tsodilo representing animals or human figures, but more than 25 sites show evidence of small round depressions ground into the rock, known as cupules, as well as various shaped grooves that have been chipped and ground into the rock. The majority of sites are found on Female Hill, with four on Male Hill and one site on Child Hill. Cupules tend to measure about 5cm or more wide and less than a 1cm deep, although larger examples occur. They can occur at painted rock art sites but also on their own. For the most part they are found in groups ranging from 5 to 100 and in three cases, considerably more. For example, in Rhino Cave there are 346 carved into a vertical wall and nearly 1,100 at Depression Shelter. The purpose or meaning of cupules is unknown; they may have denoted a special place or the number of times a site had been visited. However, we have no dates for any of the cupules and even if they are adjacent to a rock art site, they are not necessarily contemporaneous. From their patina and general wear it has been proposed that some cupules may date back tens of thousands of years to the Middle Stone Age. If paintings also existed at this time they have long since disappeared. - sys: id: 5xeXEU1FpS26IC0kg6SoIa created_at: !ruby/object:DateTime 2016-09-12 11:32:30.877000000 Z updated_at: !ruby/object:DateTime 2018-05-15 12:44:51.891000000 Z content_type_id: image revision: 2 image: sys: id: 65NOs0Iic0kGmCKyEQqSSO created_at: !ruby/object:DateTime 2016-09-12 11:41:57.790000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:41:57.790000000 Z title: BOTTSD0970003 description: url: "//images.ctfassets.net/xt8ne4gbbocd/65NOs0Iic0kGmCKyEQqSSO/b729ac2af7dfc16ba9355cd9c7578b29/BOTTSD0970003_jpeg.jpg" caption: Engraved boulder with numerous ground cupules. <NAME>, <NAME>. 2013,2034.21062 © TARA/ <NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3762004&partId=1&searchText=2013,2034.21062&page=1 - sys: id: RIKm0qhPO0CeIoommeWeO created_at: !ruby/object:DateTime 2016-09-12 11:30:30.503000000 Z updated_at: !ruby/object:DateTime 2016-10-17 11:07:04.906000000 Z content_type_id: chapter revision: 2 title_internal: 'Botswana: featured site, chapter 9' body: Grooves are less common than cupules, but are often easier to detect. They occur in small groups of 3 to 15 and are elongated oval or canoe-like in shape, and are found mostly on horizontal or near-horizontal surfaces. Their function is unknown, although a thin slab of stone with a curved round edge was excavated from Depression Shelter which matched one of the grooves in the shelter. - sys: id: 2rAlzTp1WMc4s8WiAESWcE created_at: !ruby/object:DateTime 2016-09-12 11:30:30.536000000 Z updated_at: !ruby/object:DateTime 2016-09-13 13:31:07.523000000 Z content_type_id: chapter revision: 5 title: Who were the artists? title_internal: 'Botswana: featured site, chapter 10' body: "It is a bit of a mystery about who actually created the paintings at Tsodilo, as the red images at Tsodilo do not fit neatly into other known styles of rock art in southern Africa. They do not show the fine brush work of San&#124;Bushmen¹ in other parts of southern Africa, nor the cruder style of white paintings attributed to later Bantu-speaking farmers.\n\nIt is possible that they were painted by the Khoesan during the first millennium AD, the original settlers in the area who made stone tools and herded livestock. A local Ncaekhoe man (a Central San people) claims his ancestors made the paintings and it is possible that some or many of the cattle images were painted by pastoral ancestors of Ncaekhoe. \n\nThe white paintings are more difficult to attribute authorship, although as they are comparable to the red paintings, comprising the same subject matter of elephant, rhino, giraffe and antelope as well as geometrics, they may reflect a later version of the red tradition.\n\n" - sys: id: 55nMUbiXCEequAa4egOUMS created_at: !ruby/object:DateTime 2016-09-12 11:30:30.558000000 Z updated_at: !ruby/object:DateTime 2016-10-17 11:10:22.009000000 Z content_type_id: chapter revision: 2 title: Dating title_internal: 'Botswana: featured site, chapter 11' body: The paintings at Tsodilo are often faded because they are located on rock faces exposed to the sun, wind and rain. As such, dating them scientifically is problematic as little or no suitable organic material remains. However, cattle paintings may help to date the art. There are about 160 depictions of cattle, which were common around the Tsodilo Hills between 800–1200 AD. As the cattle depictions are stylistically similar to other animal depictions it has been suggested that this seems to be a plausible date for most of the art (Coulson and Campbell, 2001:103) - sys: id: 6rU0fkhAasueAasEgyyg6S created_at: !ruby/object:DateTime 2016-09-12 11:32:40.775000000 Z updated_at: !ruby/object:DateTime 2018-05-15 12:49:05.907000000 Z content_type_id: image revision: 2 image: sys: id: Y7kLCRLHA2ciIS8eQOSyQ created_at: !ruby/object:DateTime 2016-09-12 11:42:17.633000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:42:17.633000000 Z title: BOTTSD1020001 description: url: "//images.ctfassets.net/xt8ne4gbbocd/Y7kLCRLHA2ciIS8eQOSyQ/f420a4f3e3f70bf173adffe97010596f/BOTTSD1020001_jpeg.jpg" caption: Red cow with upturned horns. Tsodilo Hills. 2013,2034.21070 © TARA/ <NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3762014&partId=1&searchText=2013,2034.21070&page=1 - sys: id: 3kNt1aGj6wssQ0SEwCgIcA created_at: !ruby/object:DateTime 2016-09-12 11:30:30.552000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:30:30.552000000 Z content_type_id: chapter revision: 1 title_internal: 'Botswana: featured site, chapter 12' body: 'Similarly, the first horses known to reach Tsodilo belonged to a party of Griqua traders who passed nearby on their way to Andara in 1852, the earliest probable date for the paintings of figures on horseback (Campbell, Robbins and Taylor, 2010:103). It is not clear when the red painting tradition ceased but this could have occurred in the twelfth century when Tsodilo stopped being a major trade centre and seemingly the local cattle population collapsed. ' - sys: id: 4v5vfCbdLy2WGqOIKO24Om created_at: !ruby/object:DateTime 2016-09-12 11:32:49.588000000 Z updated_at: !ruby/object:DateTime 2018-05-15 13:32:39.837000000 Z content_type_id: image revision: 2 image: sys: id: 59TnAobO36C8wcEkwwq2Yq created_at: !ruby/object:DateTime 2016-09-12 11:42:47.829000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:42:47.829000000 Z title: BOTTSD0520003 description: url: "//images.ctfassets.net/xt8ne4gbbocd/59TnAobO36C8wcEkwwq2Yq/363ccd57abf9e193881c3c012c92feba/BOTTSD0520003_jpeg.jpg" caption: 'White painted rock art showing figure on horseback adjacent to figure with hands on hips. White Paintings Shelter, Tsodilo Hills. 2013,2034.20954 © TARA/ <NAME> ' col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3761768&partId=1&searchText=2013%2c2034.20954&page=1 - sys: id: 3eB1mi7ZIIq6WAguuucCSk created_at: !ruby/object:DateTime 2016-09-12 11:30:30.591000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:30:30.591000000 Z content_type_id: chapter revision: 1 title: Interpretation title_internal: 'Botswana: featured site, chapter 13' body: "Giraffe, eland and rhino are by far the most common species depicted at Tsodilo, followed by elephant, gemsbok and cattle. However, these images tend to be discretely rendered and there does not appear to be any relationship between images on the same rock. \n\nRepresentations of people are simply painted and generally stick-like, identified to gender by either penis or breasts. In some cases this may represent sexual virility and fertility, although in scenes where both occur it may merely indicate gender differences.\n\nCattle seem to appear in the rock art at the same time as human figures. In one scene, three figures, one leading a child, has been interpreted as either herding or stealing cattle (Campbell, Robbins and Taylor, 2010:106). Three other sites show cattle depicted with what may be mythical rain animals. \n" - sys: id: OhQoTZwtQ4c6824AkMeIw created_at: !ruby/object:DateTime 2016-09-12 11:32:56.778000000 Z updated_at: !ruby/object:DateTime 2018-05-15 13:35:20.813000000 Z content_type_id: image revision: 2 image: sys: id: y5jBKXYeoCcMusKuIcKeG created_at: !ruby/object:DateTime 2016-09-12 11:43:17.613000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:43:17.613000000 Z title: BOTTSD0580002 description: url: "//images.ctfassets.net/xt8ne4gbbocd/y5jBKXYeoCcMusKuIcKeG/6ee8df8512d8e7c55e06cb2292166936/BOTTSD0580002_A_jpeg.jpg" caption: 'Two cattle with four figures, one leading a child. The scene has been interpreted as possibly herding or stealing cattle. 2013,2034.20996 © TARA/ <NAME> ' col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3761852&partId=1&searchText=2013%2c2034.20996&page=1 - sys: id: 3FUszfSDUQ42g2kUsukuQi created_at: !ruby/object:DateTime 2016-09-12 11:30:30.775000000 Z updated_at: !ruby/object:DateTime 2018-05-15 13:36:08.602000000 Z content_type_id: chapter revision: 2 title_internal: 'Botswana: featured site, chapter 14' body: "Geometric designs are trickier to decipher. Square geometric designs, also known as “shields” possibly represent human forms. Circular designs sometimes partially superimpose an animal or be placed within its outline. This superimposition may enhance the symbolic meaning of the animal.\n\nEither singly or in groups, and sometimes depicted with animals or people, geometric motifs show stylistic consistency across a wide area and are likely to have had some symbolic meaning. In Zambia, geometric designs are thought to have been made by women and associated with the weather and fertility, while depictions of animals were made by men. The geometric rock art of Tsodilo fits into a pattern of similar imagery in central Africa and may be related to the same meanings of weather and fertility.\t\n" - sys: id: 1ImUVBlPTSQIG00wy6Y6QQ created_at: !ruby/object:DateTime 2016-09-13 13:31:24.274000000 Z updated_at: !ruby/object:DateTime 2016-09-13 13:31:38.744000000 Z content_type_id: chapter revision: 2 title_internal: Botswana Chapter 14 body: "¹ San&#124;Bushmen is a collective term used to describe the many different hunter-gatherer-fisher groups living in southern Africa who have related languages and cultural traditions. Both 'San' and 'Bushmen' are considered offensive terms by some members of these groups, although others have positively adopted them." citations: - sys: id: Pu7wGVJ7C6EIqoKCmUuCk created_at: !ruby/object:DateTime 2016-09-12 11:33:04.551000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:33:04.551000000 Z content_type_id: citation revision: 1 citation_line: |- <NAME>; <NAME> (2010) Tsodilo Hills: Copper Bracelet of the Kalahari. East Lansing: Michigan State University Press. Coulson and Campbell, (2001) background_images: - sys: id: 1sR7vldVp2WgiY8MUyWI8E created_at: !ruby/object:DateTime 2016-09-12 11:40:46.655000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:40:46.655000000 Z title: BOTTSDNAS0010008 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1sR7vldVp2WgiY8MUyWI8E/3ee38dc4339bc8831fbc27c32789652b/BOTTSDNAS0010008_jpeg.jpg" - sys: id: 6vCru3T4QwO8kSOSSUwOsG created_at: !ruby/object:DateTime 2016-09-12 11:41:29.254000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:41:29.254000000 Z title: BOTTSD0100003 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6vCru3T4QwO8kSOSSUwOsG/9fa827f96116559169a415bb2abe204f/BOTTSD0100003_jpeg.jpg" key_facts: sys: id: 5oidYIzjWwYAOEyQuqO42s created_at: !ruby/object:DateTime 2016-09-12 11:03:11.059000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:03:11.059000000 Z content_type_id: country_key_facts revision: 1 title_internal: 'Botswana: key facts' image_count: '727' date_range: 'At least 2,000 years ago - around 150 years ago ' main_areas: Tsodilo Hills, Gubatshaa Hills and Tuli Block techniques: Paintings and engravings main_themes: Wild animals, domestic cattle, stick-like figures and geometric motifs thematic_articles: - sys: id: 9cRmg60WNGAk6i8Q6WKWm created_at: !ruby/object:DateTime 2018-05-10 14:12:25.736000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:42:15.905000000 Z content_type_id: thematic revision: 2 title: Introduction to rock art in southern Africa slug: rock-art-in-southern-africa lead_image: sys: id: 3cyElw8MaIS24gq8ioCcka created_at: !ruby/object:DateTime 2016-09-12 15:12:39.975000000 Z updated_at: !ruby/object:DateTime 2016-09-12 15:12:39.975000000 Z title: SOADRB0080007 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3cyElw8MaIS24gq8ioCcka/fcea216b7327f325bf27e3cebe49378e/SOADRB0080007.jpg" chapters: - sys: id: 5qv45Cw424smAwqkkg4066 created_at: !ruby/object:DateTime 2016-09-13 13:01:39.329000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:09:20.849000000 Z content_type_id: chapter revision: 6 title_internal: 'Southern Africa: regional, chapter 1' body: |+ The southern African countries of Zimbabwe, South Africa, Lesotho, Swaziland, Mozambique, Botswana and Namibia contain thousands of rock art sites and southern African rock art has been studied extensively. Due to perceived similarities in subject matter, even across great distances, much southern African rock art has been ascribed to hunter-gatherer painters and engravers who appear to have had a shared set of cultural references. These have been linked with beliefs and practices which remain common to modern San&#124;Bushman¹ people, a number of traditional hunter-gatherer groups who continue to live in Southern Africa, principally in Namibia, Botswana and South Africa. There are, however, differences in style and technique between regions, and various rock art traditions are attributed to other cultural groups and their ancestors. As is often the case with rock art, the accurate attribution of authorship, date and motivation is difficult to establish, but the rock art of this region continues to be studied and the richness of the material in terms of subject matter, as well as in the context of the archaeological record, has much to tell us, both about its own provenance and the lives of the people who produced it. - sys: id: r3hNyCQVUcGgGmmCKs0sY created_at: !ruby/object:DateTime 2016-09-13 13:02:04.241000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:09:49.095000000 Z content_type_id: chapter revision: 2 title: Geography and distribution title_internal: 'Southern Africa: regional, chapter 2' - sys: id: 5cKrBogJHiAaCs6mMoyqee created_at: !ruby/object:DateTime 2016-09-13 13:02:27.584000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:10:55.925000000 Z content_type_id: image revision: 4 image: sys: id: 4RBHhRPKHC2s6yWcEeWs0c created_at: !ruby/object:DateTime 2016-09-13 13:02:17.232000000 Z updated_at: !ruby/object:DateTime 2016-09-13 13:02:17.232000000 Z title: ZIMMSL0070001 description: url: "//images.ctfassets.net/xt8ne4gbbocd/4RBHhRPKHC2s6yWcEeWs0c/9d9bc5196cfac491fa099fd737b06e34/ZIMMSL0070001.jpg" caption: Yellow elephant calf painted on the roof of a shelter. Mashonaland, Zimbabwe. 2013,2034.22675 ©TARA/<NAME> col_link: http://bit.ly/2iUgvg0 - sys: id: 69tB5BiRVKG2QQEKoSYw08 created_at: !ruby/object:DateTime 2016-09-13 13:02:41.530000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:11:21.260000000 Z content_type_id: chapter revision: 3 title_internal: 'Southern Africa: regional, chapter 3' body: 'There is wide variation in the physical environments of southern Africa, ranging from the rainforests of Mozambique to the arid Namib Desert of western Namibia, with the climate tending to become drier towards the south and west. The central southern African plateau is divided by the central dip of the Kalahari basin, and bordered by the Great Escarpment, a sharp drop in altitude towards the coast which forms a ridge framing much of southern Africa. The escarpment runs in a rough inland parallel to the coastline, from northern Angola, south around the Cape and up in the east to the border between Zimbabwe and Malawi. Both painted and engraved rock art is found throughout southern Africa, with the type and distribution partially informed by the geographical characteristics of the different regions. Inland areas with exposed boulders, flat rock ‘pavements’ and rocky outcrops tend to feature engraved rock art, whereas paintings are more commonly found in the protective rock shelters of mountainous or hilly areas, often in ranges edging the Great Escarpment. ' - sys: id: 4BJ17cEGyIC6QYSYGAkoaa created_at: !ruby/object:DateTime 2016-09-13 13:03:04.486000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:11:57.877000000 Z content_type_id: image revision: 3 image: sys: id: 1hXbvhDSf2CmOss6ec0CsS created_at: !ruby/object:DateTime 2016-09-13 13:02:59.339000000 Z updated_at: !ruby/object:DateTime 2016-09-13 13:02:59.339000000 Z title: NAMBRG0030001 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1hXbvhDSf2CmOss6ec0CsS/0bb079e491ac899abae435773c74fcf4/NAMBRG0030001.jpg" caption: View out of a rock shelter in the Brandberg, Namibia. 2013,2034.20452 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3729901 - sys: id: 499lI34cAE6KAgKU4mkcqq created_at: !ruby/object:DateTime 2016-09-13 13:03:14.736000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:12:17.831000000 Z content_type_id: chapter revision: 5 title: Types of rock art title_internal: 'Southern Africa: regional, chapter 4' body: "Rock art of the type associated with hunter-gatherers is perhaps the most widely distributed rock art tradition in southern Africa, with numerous known examples in South Africa, Namibia and Zimbabwe, but also with examples found in Botswana and Mozambique. This tradition comprises paintings and engravings, with both techniques featuring images of animals and people. The type and composition varies from region to region. For example, rock art sites of the southern Drakensberg and Maloti mountains in South Africa and Lesotho contain a higher proportion of images of eland antelope, while those in Namibia in turn feature more giraffes. There are also regional variations in style and colour: in some sites and areas paintings are polychrome (multi-coloured) while in others they are not.\n\nDifferences also occur in composition between painting and engraving sites, with paintings more likely to feature multiple images on a single surface, often interacting with one another, while engraving sites more often include isolated images on individual rocks and boulders. \ However, there are commonalities in both imagery and style, with paintings throughout southern Africa often including depictions of people, particularly in procession and carrying items such as bows and arrows. Also heavily featured in both paintings and engravings are animals, in particular large ungulates which are often naturalistically depicted, sometimes in great detail. Additionally, images may include people and animals which appear to have the features of several species and are harder to identify. Some hunter-gatherer type paintings are described as ‘fine-line’ paintings because of the delicacy of their rendering with a thin brush. \n" - sys: id: 4NfdPoVtFKaM6K4w8I8ckg created_at: !ruby/object:DateTime 2016-09-13 13:22:13.102000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:12:40.860000000 Z content_type_id: image revision: 4 image: sys: id: 20oHYa0oEcSEMOyM8IcCcO created_at: !ruby/object:DateTime 2016-09-13 13:22:08.653000000 Z updated_at: !ruby/object:DateTime 2016-09-13 13:22:08.653000000 Z title: NAMBRT0010002 description: url: "//images.ctfassets.net/xt8ne4gbbocd/20oHYa0oEcSEMOyM8IcCcO/67a69f9814e8ec994003bfacff0962cc/NAMBRT0010002.jpg" caption: " Fine-line paintings of giraffes and line patterns, Brandberg, Namibia. \ It is thought that giraffes may have been associated with rain in local belief systems. 2013,2034.21324 © TARA/<NAME>" col_link: http://bit.ly/2j9778d - sys: id: 2nqpXdHTeoyKakEEOMUSA0 created_at: !ruby/object:DateTime 2016-09-13 13:03:40.877000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:13:26.231000000 Z content_type_id: chapter revision: 9 title_internal: 'Southern Africa: regional, chapter 5' body: "Hunter-gatherer rock paintings are found in particular concentrations in the Drakensberg-Maloti and Cape Fold Mountains in South Africa and Lesotho, the Brandberg and Erongo Mountains in Namibia and the Matobo Hills in Zimbabwe, while engraving sites are found throughout the interior, often near water courses. \n\nA different form of rock painting from the hunter-gatherer type, found mainly in the north-eastern portion of southern Africa is that of the ‘late whites’. Paintings in this tradition are so-called because they are usually associated with Bantu language-speaking Iron Age farming communities who entered the area from the north from around 2,000 years ago and many of these images are thought to have been painted later than some of the older hunter-gatherer paintings. ‘Late white’ paintings take many forms, but have generally been applied with a finger rather than a brush, and as the name suggests, are largely white in colour. These images represent animals, people and geometric shapes, often in quite schematic forms, in contrast to the generally more naturalistic depictions of the hunter-gatherer art. \n\nSometimes ‘late white’ art images relate to dateable events or depict objects and scenes which could only have taken place following European settlement, such as trains. \ Other forms of southern African rock art also depict European people and objects. These include images from the Western Cape in South Africa of a sailing ship, estimated to date from after the mid-17th century, as well as painted and engraved imagery from throughout South Africa showing people on horseback with firearms. Such images are sometimes termed ‘contact art’ as their subject matter demonstrates that they follow the period of first contact between European and indigenous people. \n" - sys: id: 1NrA6Z43fWIgwGoicy2Mw2 created_at: !ruby/object:DateTime 2016-09-13 13:03:57.014000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:13:43.550000000 Z content_type_id: image revision: 2 image: sys: id: 6QHTRqNGXmWic6K2cQU8EA created_at: !ruby/object:DateTime 2016-09-13 13:03:52.426000000 Z updated_at: !ruby/object:DateTime 2016-09-13 13:03:52.426000000 Z title: SOASWC0110006 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6QHTRqNGXmWic6K2cQU8EA/3d924964d904e34e6711c6224a7429e6/SOASWC0110006.jpg" caption: Painting of a ship from the south Western Cape in South Africa. 2013,2034.19495 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3730142&partId=1&searchText=2013%2c2034.19495&page=1 - sys: id: 4JVHOgrOyAAI8GWAuoyGY created_at: !ruby/object:DateTime 2016-09-13 13:24:14.217000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:17:20.511000000 Z content_type_id: chapter revision: 5 title_internal: 'Southern Africa: regional, chapter 6' body: "This kind of imagery is found in a variety of styles, and some of those producing ‘contact’ images in the Cape may have been people of Khoekhoen heritage. The Khoekhoen were traditionally cattle and sheep herders, culturally related to modern Nama people and more loosely to San&#124;Bushman hunter-gatherers. \ A distinct tradition of rock art has been suggested to be of ancestral Khoekhoen origin. This art is predominantly geometric in form, with a particular focus on circle and dotted motifs, and engravings in this style are often found near watercourses. \n" - sys: id: 3zUtkjM57Omyko6Q2O0YMG created_at: !ruby/object:DateTime 2016-09-13 13:04:05.564000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:17:47.538000000 Z content_type_id: chapter revision: 6 title: History of research title_internal: 'Southern Africa: regional, chapter 7' body: 'The first known reports of African rock art outside of the continent appear to come from the Bishop of Mozambique, who in 1721 reported sightings of paintings on rocks to the Royal Academy of History in Lisbon. Following this, reports, copies and publications of rock art from throughout modern South Africa were made with increasing frequency by officials and explorers. From the mid-19th century onwards, rock art from present-day Namibia, Zimbabwe and Botswana began to be documented, and during the first few decades of the twentieth century global public interest in the art was piqued by a series of illustrated publications. The hunter-gatherer rock art in particular had a strong aesthetic and academic appeal to western audiences, and reports, photographs and copied images attracted the attention of prominent figures in archaeology and ethnology such as <NAME>, <NAME> and the Abbé Breuil, researchers whose interest in rock art worldwide let them to visit and write about southern African rock art sites. A further intensification of archaeological and anthropological research and recording in the 1950s-70s, resulted in new insights into the interpretations and attributions for southern African rock art. Rock art research continues throughout the area today. ' - sys: id: 5bPZwsgp3qOGkogYuCIQEs created_at: !ruby/object:DateTime 2016-09-13 13:04:30.652000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:18:07.313000000 Z content_type_id: image revision: 3 image: sys: id: 3BLPJ6SPMcccCE2qIG4eQG created_at: !ruby/object:DateTime 2016-09-13 13:04:26.508000000 Z updated_at: !ruby/object:DateTime 2016-09-13 13:04:26.508000000 Z title: BOTTSD0300015 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3BLPJ6SPMcccCE2qIG4eQG/639dd24028612b985042ea65536eef2e/BOTTSD0300015.jpg" caption: Rhinoceros and cattle painting, Tsodilo Hills, Botswana. 2013,2034.20848 © TARA/<NAME> col_link: http://bit.ly/2i5xfUJ - sys: id: 1QaeG3pF1KOEaooucoMUeE created_at: !ruby/object:DateTime 2016-09-13 13:04:37.305000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:18:34.546000000 Z content_type_id: chapter revision: 4 title: Interpretation title_internal: 'Southern Africa: regional, chapter 8' body: Rather than showing scenes from daily life, as was once assumed, it is now usually accepted that hunter-gatherer art in southern Africa shows images and motifs of spiritual and cultural importance. In particular, it is thought that some images reflect trance visions of San&#124;Bushman spiritual leaders, or shamans, during which they are considered to enter the world of spirits, where they are held to perform tasks for themselves and their communities, such as healing the sick or encouraging rain. This interpretation, which has been widely accepted, explains certain features of the art, for example the predominance of certain animals like eland antelope (due to their special cultural significance) and themes such as dot patterns and zigzag lines (interpreted as geometric patterns that shamans may see upon entering a trance state). - sys: id: 1YgT9SlSNeU8C6Cm62602E created_at: !ruby/object:DateTime 2016-09-13 13:04:53.447000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:19:08.779000000 Z content_type_id: image revision: 2 image: sys: id: 5Zk1QhSjEAOy8U6kK4yS4c created_at: !ruby/object:DateTime 2016-09-13 13:04:48.941000000 Z updated_at: !ruby/object:DateTime 2016-09-13 13:04:48.941000000 Z title: SOADRB0030002 description: url: "//images.ctfassets.net/xt8ne4gbbocd/5Zk1QhSjEAOy8U6kK4yS4c/5896c3d088678257f9acd01bd59c4b26/SOADRB0030002.jpg" caption: 'Painting of an eland and an ambiguous figure in the Drakensberg, South Africa. Both the eland and this kind of human-like figure are thought to have had symbolic associations with beliefs about gender and power. 2013,2034.18187© TARA/<NAME> ' col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3738250&partId=1&searchText=2013,2034.18187&page=1 - sys: id: 5byxQopdNCqEC2kCa0OqCm created_at: !ruby/object:DateTime 2016-09-13 13:05:00.899000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:19:37.565000000 Z content_type_id: chapter revision: 4 title_internal: 'Southern Africa: regional, chapter 9' body: "The rock art attributed to ancestral San&#124;Bushman hunter-gatherers has many varied motifs, some of which may also relate to specific themes such as initiation or rainmaking (indeed within its cultural context one image may have several significances). San&#124;Bushman informants in the 19th century told researchers that certain ambiguously shaped animals in the rock art repertoire represented animals related to water. Images such as these are known to researchers as 'rain animals' and it has been suggested that certain images could reflect—or prompt—the shaman's attempt to control rainfall. Some 'late white' art has also been proposed to have associations with rainmaking practices, and indeed the proximity of some geometric rock art images, proposed to be of possible Khoekhoen origin, to watercourses appears to emphasise the practical and spiritual significance of water among historical southern African communities. It has also been proposed that some forms of geometric art attributed to Khoekhoen people may be linked by tradition and motif to the schematic art traditions of central Africa, themselves attributed to hunter-gatherers and possibly made in connection with beliefs about water and fertility. Much in the “late white” corpus of paintings appears to be connected to initiation practices, part of a larger set of connected traditions extending north as far as Kenya. \n\nThe long time periods, cultural connections, and movements involved can make attribution difficult. For example, the idiosyncratic rock paintings of Tsodilo Hills in Botswana which appear to have similarities with the hunter-gatherer style include images of domesticates and may have been the work of herders. More localised traditions, such as that of engravings in north-western South Africa representing the homesteads of ancestral Nguni or Sotho-Tswana language speakers, or the focus on engravings of animal tracks found in Namibia, demonstrate more specific regional significances. Research continues and in recent decades, researchers, focusing on studying individual sites and sets of sites within the landscape and the local historical context, have discussed how their placement and subject matter may reflect the shifting balances of power, and changes in their communities over time. \n" - sys: id: L9AkWhM1WwUKWC4MQ4iMe created_at: !ruby/object:DateTime 2016-09-13 13:05:15.123000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:21:01.026000000 Z content_type_id: image revision: 5 image: sys: id: ETDpJFg6beKyyOmQGCsKI created_at: !ruby/object:DateTime 2016-09-13 13:05:11.473000000 Z updated_at: !ruby/object:DateTime 2016-09-13 13:05:11.473000000 Z title: NAMSNH0030006 description: url: "//images.ctfassets.net/xt8ne4gbbocd/ETDpJFg6beKyyOmQGCsKI/3dabb2ba8a3abaa559a6652eb10ea1eb/NAMSNH0030006.jpg" caption: 'Geometric rock engravings of the type suggested by some to be the work of Khoekhoen pastoralists and their ancestors. 2013,2034.22405 © TARA/David Coulson ' col_link: http://bit.ly/2iVIIoL - sys: id: ayvCEQLjk4uUk8oKikGYw created_at: !ruby/object:DateTime 2016-09-13 13:05:22.665000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:21:16.059000000 Z content_type_id: chapter revision: 6 title: Dating title_internal: 'Southern Africa: regional, chapter 10' body: "Although dating rock art is always difficult, the study of rock art sites from southern Africa has benefitted from archaeological study and excavations at rock art sites have sometimes revealed useful information for ascribing dates. Some of the oldest reliably dated examples of rock art in the world have been found in the region, with the most well-known examples probably being the painted plaques from Apollo 11 Cave in Namibia, dated to around 30,000 years ago. A portion of an engraved animal found in South Africa’s Northern Cape is estimated to be 10,200 years old and painted spalls from shelter walls in Zimbabwe have been dated to 12,000 years ago or older. However, it is thought that the majority of existing rock art was made more recently. \ As ever, subject matter is also helpful in ascribing maximum date ranges. \ We know, for example,that images of domestic animals are probably less than 2,000 years old. The condition of the art may also help to establish relative ages, particularly with regards to engravings, which may be in some cases be categorised by the discolouration of the patina that darkens them over time. \n\nThe multiplicity of rock art sites throughout southern Africa form a major component of southern Africa’s archaeological record, with many interesting clues about the lives of past inhabitants and, in some cases, continuing religious and cultural importance for contemporary communities. \ Many sites are open to the public, affording visitors the unique experience of viewing rock art in situ. Unfortunately, the exposed nature of rock art in the field leaves it open to potential damage from the environment and vandalism. \ Many major rock art sites in southern Africa are protected by law in their respective countries and the Maloti-Drakensberg Park in South Africa and Lesotho, Twyfelfontein/ǀUi-ǁAis in Namibia, Tsodilo Hills in Botswana and the Matobo Hills in Zimbabwe are all inscribed on the UNESCO World Heritage list. \n" - sys: id: 3Kjcm7V1dYoCuyaqKga0GM created_at: !ruby/object:DateTime 2016-09-13 13:05:38.418000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:25:17.372000000 Z content_type_id: image revision: 2 image: sys: id: 58V5qef3pmMGu2aUW4mSQU created_at: !ruby/object:DateTime 2016-09-13 13:05:34.865000000 Z updated_at: !ruby/object:DateTime 2016-09-13 13:05:34.865000000 Z title: NAMDME0080012 description: url: "//images.ctfassets.net/xt8ne4gbbocd/58V5qef3pmMGu2aUW4mSQU/dec59cd8209d3d04b13447e9c985574a/NAMDME0080012.jpg" caption: Engraved human footprints, Erongo Region, Namibia. 2013,2034.20457 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3729958&partId=1&searchText=2013,2034.20457+&page=1 - sys: id: 1kwt8c4P0gSkYOq8CO0ucq created_at: !ruby/object:DateTime 2016-09-13 13:28:16.189000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:25:44.294000000 Z content_type_id: chapter revision: 2 title_internal: 'Southern Africa: regional, chapter 11' body: "¹ San&#124;Bushmen is a collective term used to describe the many different hunter-gatherer-fisher groups living in southern Africa who have related languages and cultural traditions. Both 'San' and 'Bushmen' are considered offensive terms by some members of these groups, although others have positively adopted them." citations: - sys: id: 6GlTdq2WbeIQ6UoeOeUM84 created_at: !ruby/object:DateTime 2016-10-17 10:45:36.418000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:39:37.963000000 Z content_type_id: citation revision: 2 citation_line: |+ <NAME>., <NAME>. and <NAME>. 2010. Tsodilo Hills: Copper Bracelet of the Kalahari. East Lansing: Michigan State University Press. <NAME>. 1995. The Hunter's Vision: The Prehistoric Art of Zimbabwe. London: British Museum Press. <NAME>. 1981. Believing and Seeing: Symbolic Meanings in San&#124;BushmanRock Paintings. Johannesburg: University of Witwatersrand Press <NAME>. 1995. 'Neglected Rock Art: The Rock Engravings of Agriculturist Communities in South Africa'. South African Archaeological Bulletin. Vol. 50 No. 162. pp. 132.142. <NAME>. 1989. Rock Paintings of the Upper Brandberg. vols. I-VI. Köln: Heinrich-Barth-Institut <NAME>. & <NAME>. 2008. 'Beyond Development - Global Visions and Local Adaptations of a Contested Concept' in Limpricht, C., & M. Biesele (eds) Heritage and Cultures in modern Namibia: in-depth views of the country: a TUCSIN Festschrift. Goettingen : Klaus Hess Publishers. pp 37:46. <NAME>. 2013. 'Rock Art Research in Africa' in Mitchell, P. and P. Lane (eds), The Oxford Handbook of African Archaeology. Oxford, Oxford University Press. <NAME>. & <NAME>. 2004. 'Taking Stock: Identifying Khoekhoen Herder Rock Art in Southern Africa'. Current Anthropology Vol. 45, No. 4. pp 499-52. background_images: - sys: id: 6oQGgfcXZYWGaeaiyS44oO created_at: !ruby/object:DateTime 2016-09-13 13:05:47.458000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:41:12.556000000 Z title: ZIMMSL0120015.tiff description: url: "//images.ctfassets.net/xt8ne4gbbocd/6oQGgfcXZYWGaeaiyS44oO/c8bc0d9d1ceee0d23517a1bc68276b24/ZIMMSL0120015.tiff.jpg" - sys: id: 69ouDCLqDKo4EQWa6QCECi created_at: !ruby/object:DateTime 2016-09-13 13:05:55.993000000 Z updated_at: !ruby/object:DateTime 2018-05-10 14:41:44.910000000 Z title: SOAEFS0030008 description: url: "//images.ctfassets.net/xt8ne4gbbocd/69ouDCLqDKo4EQWa6QCECi/9c5da3bf755188e90003a9bc55550f6f/SOAEFS0030008.jpg" - sys: id: 570TteJLy8EmE4SYAGKcQw created_at: !ruby/object:DateTime 2017-06-14 17:36:35.946000000 Z updated_at: !ruby/object:DateTime 2017-06-21 13:55:43.874000000 Z content_type_id: thematic revision: 5 title: Rhinos in rock art slug: rhinos-in-rock-art lead_image: sys: id: 4uVUj08mRGOCkmK64q66MA created_at: !ruby/object:DateTime 2016-09-26 14:46:35.956000000 Z updated_at: !ruby/object:DateTime 2019-02-12 02:01:17.553000000 Z title: '2013,2034.20476' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3730556&partId=1&searchText=NAMDMT0010010&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/4uVUj08mRGOCkmK64q66MA/c1c895d4f72a2260ae166ab9c2148daa/NAMDMT0010010.jpg" chapters: - sys: id: 4kAwRERjIIQ4wSkS6y2i8c - sys: id: 2hohzbPqWMU2IGWEeSo2ma - sys: id: 5Ld8vmtLAAGcImkQaySck2 - sys: id: 6jA55SyPksGMQIYmYceMkQ - sys: id: 7gBWq5BdnOYUGm6O4KK4u0 - sys: id: 1LYEwVNEogggeMOcuQUOQW - sys: id: 4dbpdyyr2UAk4yKAomw42I - sys: id: 3VgqyhGcViwkwCoI88W4Ii - sys: id: 4TnBbYK1SEueSCAIemKOcA - sys: id: 4Z8zcElzjOCyO6iOasMuig - sys: id: 2Z9GGCpzCMk4sCKKYsmaU8 - sys: id: 2S3mX9yJfqoMka8QoWUqOE - sys: id: 4KLSIsvlmEMeOsCo8SGOQA - sys: id: 1IlptwbzFmIaSkIWWAqw8U - sys: id: 2Moq7jFKLCc60oamksKUgU - sys: id: 2OfGVIZFbOOm8w6gg6AucI - sys: id: 16oCD2X1nmEYmCOMOm6oWi - sys: id: 2jfI6k6zKAauIS62IC6weq - sys: id: 4k9Uy1dQzmkcIY0kIogeWK - sys: id: 2QFAA8hik82Y4EAIwGSiEs - sys: id: 3ApAq8tLfG6wWaswQEwuaU - sys: id: 4S5oC30EcwEUGEuEO6sa4m - sys: id: 4Y3xOdstSowoYOGOEmW6K6 - sys: id: 6ZjeUWwA5aCEMUiIgukK48 citations: - sys: id: TwHxmivy8uW8mIKAkkMeA background_images: - sys: id: 2ztUAznRiwc0qiE4iUIQGc created_at: !ruby/object:DateTime 2017-05-17 11:44:42.255000000 Z updated_at: !ruby/object:DateTime 2017-05-17 11:44:42.255000000 Z title: <NAME> Chauvet description: url: "//images.ctfassets.net/xt8ne4gbbocd/2ztUAznRiwc0qiE4iUIQGc/5958ce98b795f63e5ee49806275209b7/Rhinoc__ros_grotte_Chauvet.jpg" - sys: id: 6m2Q1HCGT6Q2cey00sKGmu created_at: !ruby/object:DateTime 2017-05-17 12:26:24.400000000 Z updated_at: !ruby/object:DateTime 2017-05-17 12:26:24.400000000 Z title: Black Rhino description: url: "//images.ctfassets.net/xt8ne4gbbocd/6m2Q1HCGT6Q2cey00sKGmu/92caad1c13d4bbefe80a5a94aef9844e/Black_Rhino.jpg" country_introduction: sys: id: 70Jk3F9iU0OaCQGQWkGqM6 created_at: !ruby/object:DateTime 2016-09-12 11:04:27.819000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:04:27.819000000 Z content_type_id: country_information revision: 1 title: 'Botswana: country introduction' chapters: - sys: id: 5wtp5JwhDUU0cMoCcWgGgy created_at: !ruby/object:DateTime 2016-09-12 11:25:13.083000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:25:13.083000000 Z content_type_id: chapter revision: 1 title: Introduction title_internal: 'Botswana: country, chapter 1' body: 'Botswana, a landlocked country in southern Africa, has a landscape defined by the Kalahari Desert in the west and the Okavango Delta in the north. Rock art can be found in the north, north-west and east of the country. One of the most well-known locations is the Tsodilo Hills in the north-west which contains evidence of human occupation that goes back 100,000 years. This area has yielded more than 4,000 paintings and has been termed the *Louvre of the Desert*. It also has engraved cupules and grooves dating back to the first millennium AD. ' - sys: id: 2UQ5NTtwJO42YcwmMkwQEC created_at: !ruby/object:DateTime 2016-09-12 11:25:32.308000000 Z updated_at: !ruby/object:DateTime 2018-05-10 15:41:27.865000000 Z content_type_id: image revision: 2 image: sys: id: 3nU9N3ePduuQ60SQsiuYUO created_at: !ruby/object:DateTime 2016-09-12 11:37:45.576000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:37:45.576000000 Z title: BOTTSD0190005 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3nU9N3ePduuQ60SQsiuYUO/726dcb36ac6ab50baa1de073e8672153/BOTTSD0190005_jpeg.jpg" caption: 'This schematic painting of a zebra can be found in the Tsodilo Hills in Botswana, now a UNESCO World Heritage Site. This image became the first logo of the National Museum and Art Gallery of Botswana. 2013,2034.20773 © TARA/ <NAME>. ' col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3758628&partId=1&searchText=2013,2034.20773&page=1 - sys: id: 2ZUfI0WpgssmaomWYocswq created_at: !ruby/object:DateTime 2016-09-12 11:26:11.853000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:26:11.853000000 Z content_type_id: chapter revision: 1 title: Geography and rock art distribution title_internal: 'Botswana: country, chapter 2' body: The Republic of Botswana is bordered by South Africa to the south, Namibia to the west and north and Zimbabwe to the north-east. It shares a short border consisting of a few hundred metres with Zambia to the north. The majority of this flat country, around 70%, is made up of the Kalahari Desert, with the Okavango Delta, one of the world’s largest inland deltas located in the north. Botswana has a subtropical climate of hot summers and warm winters due to its high altitude and is semi-arid due to the short rainy season. Rock art is scattered across the country with the main sites being found in the Tsodilo Hills in the north- west; the Gubatshaa Hills in the Chobe National Park, east of the Okavango Delta; Tuli Block in the far east of the country and Manyana in the south-east. - sys: id: 5gcQn3IFgAE6UYMQMyUgik created_at: !ruby/object:DateTime 2016-09-12 11:26:28.774000000 Z updated_at: !ruby/object:DateTime 2018-05-10 15:29:05.947000000 Z content_type_id: image revision: 2 image: sys: id: 67txlVj7aMsymikMMMKm4U created_at: !ruby/object:DateTime 2016-09-12 11:36:31.689000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:36:31.689000000 Z title: BOTTSDNAS0010017 description: url: "//images.ctfassets.net/xt8ne4gbbocd/67txlVj7aMsymikMMMKm4U/1cc7960b055b1328802e0c794a3e65b6/BOTTSDNAS0010017_jpeg.jpg" caption: 'Aerial view of Tsodilo Hills, Botswana. 2013,2034.21162 © TARA/ <NAME>. ' col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3762286&partId=1&searchText=2013,2034.21162&page=1 - sys: id: FXOBNXwFq0WAuyUQC4uGm created_at: !ruby/object:DateTime 2016-09-12 11:26:42.821000000 Z updated_at: !ruby/object:DateTime 2016-10-17 15:41:00.509000000 Z content_type_id: chapter revision: 2 title: Research history title_internal: 'Botswana: country, chapter 3' body: | German geologist Siegfried Passarge visited the Tsodilo Hills on the 1st July 1898, mapping the area, writing on the geology and photographing a few rock paintings. In 1907, he published tracings of his photos in Die Buschmänner der Kalahari. A passing mention of the Hills was made in 1913 in a brief report by <NAME>, but it was Fran<NAME>, a French industrialist and explorer, who raised the profile of Tsodilo Hills when over two days he photographed and prepared tracings of what has come to be known as the “Rhino Panel” on September 27-28 1951. Laurens van der Post’s publication of *The Lost World of the Kalahari* in 1958 brought Tsodilo Hills and its rock art to the attention of the wider world. Van der Post, an Afrikaner, had planned to make a film of the rock art in the region, but a number of events including the shooting of a steenbok (a severe crime locally), the cameras jamming and swarms of bees descending upon their camp, conspired against him and resulted in van der Post leaving the Hills in despair. However, he also left an apologetic note at the rock art panel he had been trying to film as a way of assuaging the wrath of the “Spirit of the Hills” as he put it. The rock face he was trying to film, comprising eland, giraffe and handprints, is now known as “Van der Post Panel”. - sys: id: vMbGVjcFe8YOcigyG6iuc created_at: !ruby/object:DateTime 2016-09-12 11:26:52.599000000 Z updated_at: !ruby/object:DateTime 2018-05-10 15:41:44.339000000 Z content_type_id: image revision: 4 image: sys: id: 54OlxJkeXK0ywWs4oQMqAK created_at: !ruby/object:DateTime 2016-09-12 11:38:11.611000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:38:11.611000000 Z title: BOTTSD0040004 description: url: "//images.ctfassets.net/xt8ne4gbbocd/54OlxJkeXK0ywWs4oQMqAK/875873fafa0f76e30cf3fcdcd7799454/BOTTSD0040004_jpeg.jpg" caption: 'View of the Van der Post Panel in the Tsodilo Hills as the sun is setting. 2013,2034.20449 © TARA/ <NAME>. ' col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3729885&partId=1&searchText=2013,2034.20449&page=1 - sys: id: dqvTnHT7xeCC0omYUgyas created_at: !ruby/object:DateTime 2016-09-12 11:26:59.386000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:26:59.386000000 Z content_type_id: chapter revision: 1 title: title_internal: 'Botswana: country, chapter 4' body: | In 1963 <NAME> visited the region with <NAME>, an ethnographer who had studied the San&#124;Bushmen in Botswana. As Director of Botswana’s National Museum, Campbell had a little government funding to record the rock art and excavate the rock shelters. Subsequently he collaborated with archaeologists <NAME>, <NAME>, and paleo-geographer <NAME>. During the 1990s, Campbell, along with the staff from the National Museum recorded around 400 rock art sites numbering over 4,000 individual paintings. In 2001 Tsodilo Hills became a UNESCO World Heritage Site because of its spiritual significance to local peoples, as well as its unique record of human settlement over many millennia. - sys: id: 6oBrvFH0WcGAAOqYEg2Q4s created_at: !ruby/object:DateTime 2016-09-12 11:27:09.816000000 Z updated_at: !ruby/object:DateTime 2018-05-10 15:41:53.538000000 Z content_type_id: image revision: 3 image: sys: id: 6Nezz3ZlxCMOeSOiEKuG0s created_at: !ruby/object:DateTime 2016-09-12 11:38:28.208000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:38:28.208000000 Z title: BOTTSD0170011 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6Nezz3ZlxCMOeSOiEKuG0s/ba6319e8dbe59b7609ad756a15489bc2/BOTTSD0170011_jpeg.jpg" caption: '<NAME> next to painted rock art at Rhino Cave in the Tsodilo Hills, Botswana. 2013,2034.20750 © TARA/ <NAME>. ' col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3758479&partId=1&searchText=2013,2034.20750&page=1 - sys: id: 7DJn8Jqhy0cwGwksoWSOIS created_at: !ruby/object:DateTime 2016-09-12 11:27:18.797000000 Z updated_at: !ruby/object:DateTime 2016-10-17 15:41:18.565000000 Z content_type_id: chapter revision: 5 title: Distribution and themes title_internal: 'Botswana: country, chapter 5' body: |- Tuli Block is a narrow fringe of land in the far east of the country that borders South Africa and lies on the banks of the Limpopo River. This area is characterised by rock engravings of human and animal footprints, and cupules, which hold spiritual importance both for San&#124;Bushman¹ hunter-gatherers and Tswana farmers. The engravings are thought to refer to a local myth that tells of an ancestor, named Matsieng, who is believed to have emerged from a waterhole followed by his animals. However, there are several localities in the region that claim this origin myth. It is thought the engravings in this area were created by the San&#124;Bushmen and linked to their belief system, appropriated later by the Tswana farmers. The most renowned rock art in Botswana comes from the Tsodilo Hills in the north-west of the country. With more than 4,500 paintings preserved in an area of 10km² it has been termed the “Louvre of the Desert”. Tsodilo is made up of four main hills; Male Hill, Female Hill, Child Hill and North Hill, and paintings occur on all four. The subject matter, comprised of red and white paintings, includes animals, human figures and geometric designs. Red paintings are likely to have been made by San&#124;Bushmen, while the white paintings are more difficult to attribute authorship to but may be a later continuation of the red tradition. There are no engraved images at Tsodilo but cupules and ground grooves are a common feature. Dating of the paintings at Tsodilo has been difficult, and because many of them occur on exposed surfaces where they are susceptible to damage by the sun, rain and wind, what remains is probably not very old. However, paintings of cattle, which are also badly faded, probably date to between AD 800 and 1150 when people kept these animals in this area. ¹ San&#124;Bushmen is a collective term used to describe the many different hunter-gatherer-fisher groups living in southern Africa who have related languages and cultural traditions. Both 'San' and 'Bushmen' are considered offensive terms by some members of these groups, although others have positively adopted them. - sys: id: 5TetNeY7kWwAQWW0gks2ya created_at: !ruby/object:DateTime 2016-09-12 11:27:26.815000000 Z updated_at: !ruby/object:DateTime 2018-05-10 15:43:00.396000000 Z content_type_id: image revision: 4 image: sys: id: 4bfNSUilHiW0aqEus0CQeI created_at: !ruby/object:DateTime 2016-09-12 11:38:44.342000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:38:44.342000000 Z title: BOTTSD0300004 description: url: "//images.ctfassets.net/xt8ne4gbbocd/4bfNSUilHiW0aqEus0CQeI/be79f76088201d6fabfcf13ed6cf9df5/BOTTSD0300004_jpeg.jpg" caption: Two painted rhinoceros on Female Hill, Tsodilo, Botswana. 2013,2034.20450 © TARA/ <NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3729906&partId=1&searchText=2013,2034.20450&page=1 - sys: id: 4zsMKPKa9qCmqy0YU4mCu0 created_at: !ruby/object:DateTime 2016-09-12 11:27:35.809000000 Z updated_at: !ruby/object:DateTime 2018-05-10 15:42:24.988000000 Z content_type_id: image revision: 4 image: sys: id: 19Wy6q0o68Saeo0uISC4e6 created_at: !ruby/object:DateTime 2016-09-12 11:39:05.578000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:39:05.578000000 Z title: BOTTSD0570002 description: url: "//images.ctfassets.net/xt8ne4gbbocd/19Wy6q0o68Saeo0uISC4e6/1b50517b69d707e8c2b03599e1a182f5/BOTTSD0570002_jpeg.jpg" caption: Known as the ‘Giraffe Panel’ this site is located on the east side of Female Hill at Tsodilo. 2013,2034.21232 © TARA/ <NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3744521&partId=1&searchText=2013,2034.21232&page=1 - sys: id: 5Uz37dTcS4WM0wsMqykGyM created_at: !ruby/object:DateTime 2016-09-12 11:27:44.093000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:27:44.093000000 Z content_type_id: chapter revision: 1 title_internal: 'Botswana: country, chapter 6' body: '250 km east of the Tsodilo Hills, on the eastern side of the Okavango Delta, lie the Gubatshaa Hills. Paintings here consist of geometric designs and finger painted animals such as eland, elephant, antelope and giraffe. Geometric designs are stylistically different from those at Tsodilo but share similarities with some painted designs in Carnarvon District, Northern Cape, South Africa. ' - sys: id: G2bUDmiGmi4UwaEcU8GeC created_at: !ruby/object:DateTime 2016-09-12 11:27:53.423000000 Z updated_at: !ruby/object:DateTime 2018-05-10 15:42:46.477000000 Z content_type_id: image revision: 3 image: sys: id: FTRXrT2TQao4qQ2O6Yiea created_at: !ruby/object:DateTime 2016-09-12 11:39:20.609000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:39:20.609000000 Z title: BOTGUB0010004 description: url: "//images.ctfassets.net/xt8ne4gbbocd/FTRXrT2TQao4qQ2O6Yiea/beb96fd5bfa4c52cf6a5ef1776c0096c/BOTGUB0010004_jpeg.jpg" caption: Geometric designs at Gubatshaa Hils. These differ from those at Tsodilo Hills but share similarities with painted design in the Northern Cape of South Africa. 2013,2034.20507 © TARA/ <NAME>son col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3755221&partId=1&searchText=2013,2034.20507&page=1 - sys: id: 47oOZzqdvqw4624OYwIwMY created_at: !ruby/object:DateTime 2016-09-12 11:28:00.942000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:28:00.942000000 Z content_type_id: chapter revision: 1 title_internal: 'Botswana: country, chapter 7' body: 'Rock art is rare in the south-east of the country, but the site of Manyana is noteworthy because it is the only one that has been excavated. The paintings are found at five sites along a rock outcrop of 0.75 km at the base of the Koboleng Hills, and while once richly decorated, many of the paintings have now faded. It is difficult to determine exactly when the paintings were made, but excavation shows the use of ochre from the earliest occupation levels dating to the Late Stone Age, around AD 100 - 800, with the latest occupation levels dating to the Late Iron Age, around AD 1600-1700. Interestingly, none of the paintings were done in white, a colour found at many other sites in Botswana and other regions of southern Africa, and often attributed to paintings of Iron Age date. In addition, there are no images of eland or figures combining human/antelope form which are common occurrences in South African rock art. ' - sys: id: 2eBKXXsYDuuoy4UmoGAcce created_at: !ruby/object:DateTime 2016-09-12 11:28:09.513000000 Z updated_at: !ruby/object:DateTime 2018-05-10 15:43:52.079000000 Z content_type_id: image revision: 2 image: sys: id: 5DlH7qo75uqEUsW4qmGywg created_at: !ruby/object:DateTime 2016-09-12 11:39:36.074000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:39:36.074000000 Z title: BOTMAN0010005 description: url: "//images.ctfassets.net/xt8ne4gbbocd/5DlH7qo75uqEUsW4qmGywg/5b4e35d5e2f7648155d762f230aac57f/BOTMAN0010005_jpeg.jpg" caption: Three faded yellow giraffe at Manyana. 2013,2034.20530 © TARA/ David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3755681&partId=1&searchText=2013,2034.20530&page=1 - sys: id: dPgwiUL3AkUeqOoAcmgG0 created_at: !ruby/object:DateTime 2016-09-12 11:28:17.317000000 Z updated_at: !ruby/object:DateTime 2018-05-10 15:45:07.843000000 Z content_type_id: chapter revision: 3 title: Cupules and grooves title_internal: 'Botswana: country, chapter 8' body: Cupules and grooves can be found in the Tsodilo Hills, and also in the eastern part of the country in Tuli Block and Gubatshaa Hills. Engravings include human footprints and animal tracks. Most sites with engravings and/or cupules occur near water; for example at the site of Riverslee in the Tuli Block they encircle a waterhole while at Basinghall the cupule site is near the Limpopo River. - sys: id: 5dJBDiteWQoIui2AKAAC00 created_at: !ruby/object:DateTime 2016-09-12 11:28:26.560000000 Z updated_at: !ruby/object:DateTime 2018-05-10 15:46:13.060000000 Z content_type_id: image revision: 2 image: sys: id: 66x1NGJT6Eku8UIAYqQEMW created_at: !ruby/object:DateTime 2016-09-12 11:39:52.783000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:39:52.783000000 Z title: BOTTSD0410013 description: url: "//images.ctfassets.net/xt8ne4gbbocd/66x1NGJT6Eku8UIAYqQEMW/0390827df5133b4dad256c5abb3e6e3f/BOTTSD0410013_jpeg.jpg" caption: Boulder engraved with elongated oval grooves found in Crab Shelter on the west side of Female Hill, Tsodilo, Botswana. 2013,2034.20922 © TARA/ <NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3761599&partId=1&searchText=2013,2034.20922&page=1 - sys: id: 4Jy5ySl2ByIo6wE442Ua4k created_at: !ruby/object:DateTime 2016-09-12 11:28:33.030000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:28:33.030000000 Z content_type_id: chapter revision: 1 title_internal: 'Botswana: country, chapter 9' body: Because the identity of the artists are unknown to us we can only speculate on the function and/or meanings of the art in relation to other rock art traditions in southern Africa. These may include fertility, health, abundance, protection against evil spirits or summoning rain. Contemporary communities at Tsodilo Hills believe that spirits live in the Hills and have explained how those who enter the Hills must be respectful as the spirits are capable of both curing and punishing people. In particular, White Paintings Shelter in the Tsodilo Hills was used as a place to perform curative dances that involved the placing of hands on the paintings in order to use its power. Geometric designs are more difficult to interpret but may fit into a tradition of other geometric symbols in the region and represent weather and fertility symbols. citations: - sys: id: 4MTpPfi0MgCWMswEYQocii created_at: !ruby/object:DateTime 2016-09-12 11:03:48.079000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:03:48.079000000 Z content_type_id: citation revision: 1 citation_line: "<NAME>; <NAME>, Taylor, Michael (2010) Tsodilo Hills: Copper Bracelet of the Kalahari. East Lansing: Michigan State University Press.\n\nVan der Ryst, Maria; Lombard, Marlize; <NAME>. (2004) Rocks of potency: engravings and cupules from the Dovedale Ward, Southern Tuli Block, Botswana, in \nSouth African Archaeological Bulletin, 58 (178), pp: 53-62.\n" background_images: - sys: id: 6my0V8KAecKKKeOOMgYKoo created_at: !ruby/object:DateTime 2015-12-08 13:44:12.943000000 Z updated_at: !ruby/object:DateTime 2015-12-15 11:45:30.249000000 Z title: BOTTSD0230001 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6my0V8KAecKKKeOOMgYKoo/861e0eeef2b9dd8ecccb33ac3ea81910/BOTTSD0230001.jpg" - sys: id: 67txlVj7aMsymikMMMKm4U created_at: !ruby/object:DateTime 2016-09-12 11:36:31.689000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:36:31.689000000 Z title: BOTTSDNAS0010017 description: url: "//images.ctfassets.net/xt8ne4gbbocd/67txlVj7aMsymikMMMKm4U/1cc7960b055b1328802e0c794a3e65b6/BOTTSDNAS0010017_jpeg.jpg" - sys: id: 6pHrsUcc2kaeKqeEcO0WmW created_at: !ruby/object:DateTime 2016-09-12 11:09:24.045000000 Z updated_at: !ruby/object:DateTime 2019-02-12 02:13:24.351000000 Z title: '2013,2034.21107' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3762101&partId=1&searchText=BOTTSD1170002&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/6pHrsUcc2kaeKqeEcO0WmW/c92b5e947430fcfbf28de83322cb1241/BOTTSD1170002_jpeg.jpg" region: Southern Africa ---<file_sep>/_coll_country/algeria.md --- contentful: sys: id: 1iBECXLcNSSAUkasIIa0GW created_at: !ruby/object:DateTime 2015-11-26 18:51:59.868000000 Z updated_at: !ruby/object:DateTime 2018-05-17 16:51:45.169000000 Z content_type_id: country revision: 13 name: Algeria slug: algeria col_url: http://www.britishmuseum.org/research/collection_online/search.aspx?people=197356&place=40992 map_progress: true intro_progress: true image_carousel: - sys: id: 5migSD5CiAa48U4gOyqCao created_at: !ruby/object:DateTime 2015-11-27 15:15:13.229000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:55:22.577000000 Z title: '2013,2034.4280' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3601594&partId=1&searchText=ALGDJA0050061&page=1 url: "//downloads.ctfassets.net/xt8ne4gbbocd/5migSD5CiAa48U4gOyqCao/b2d00aaa4e29281fe3dcca614dd381b5/ALGDJA0050061.jpg" - sys: id: 16CSt7fIQy4yyEY2aysOGK created_at: !ruby/object:DateTime 2015-11-27 15:12:52.496000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:56:16.475000000 Z title: '2013,2034.4191' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3601323&partId=1&searchText=ALGDJA0040001&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/16CSt7fIQy4yyEY2aysOGK/02706f11b80f640af920a6ee3158a924/ALGDJA0040001.jpg" - sys: id: 1OIGayI82E4Ksqg26wWus8 created_at: !ruby/object:DateTime 2015-11-27 15:15:02.141000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:57:20.617000000 Z title: '2013,2034.4323' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3601754&partId=1&searchText=crying+cows&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/1OIGayI82E4Ksqg26wWus8/13a2208350452112e99f1fe9035013ac/algeria1.jpg" - sys: id: 3bBZIG7wBWQe2s06S4w0gE created_at: !ruby/object:DateTime 2015-11-26 11:29:42.872000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:58:02.758000000 Z title: '2013,2034.4248' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3601516&partId=1&searchText=2013,2034.4248&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/3bBZIG7wBWQe2s06S4w0gE/503eeec9a0aa84ff849de9d81dcd091e/2013_2034.4248.jpg" - sys: id: 6TFwgxGXtYy6OgA02aKUCC created_at: !ruby/object:DateTime 2015-11-26 11:29:47.274000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:58:43.476000000 Z title: '2013,2034.4098' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3595539&partId=1&searchText=2013,2034.4098&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/6TFwgxGXtYy6OgA02aKUCC/cf9adf1bdc99801fbf709fc87fd87acb/2013_2034.4098.jpg" featured_site: sys: id: 47IFi4eXxuIaQ2Kkikkm4y created_at: !ruby/object:DateTime 2015-11-25 14:54:23.245000000 Z updated_at: !ruby/object:DateTime 2015-12-07 20:53:29.640000000 Z content_type_id: featured_site revision: 3 title: Crying cows, Algeria slug: crying-cows chapters: - sys: id: 3vWqlaPPKouEaiKsKIkAGm created_at: !ruby/object:DateTime 2015-11-25 14:52:16.750000000 Z updated_at: !ruby/object:DateTime 2015-11-25 14:52:16.750000000 Z content_type_id: chapter revision: 1 title_internal: 'Algeria: featured site, chapter 1' body: At the base of an inselberg at Tegharghart, south of Djanet, is a site that has come to be known as ‘Crying Cows’, because of the way teardrops appear to roll down the faces of the animals. - sys: id: 2CX1X82zg0Wm8OCikiCM2a created_at: !ruby/object:DateTime 2015-11-25 14:50:47.548000000 Z updated_at: !ruby/object:DateTime 2017-01-06 15:42:29.513000000 Z content_type_id: image revision: 2 image: sys: id: 6eeWLekeOI6MC2OO8SkAEk created_at: !ruby/object:DateTime 2015-11-25 14:49:37.233000000 Z updated_at: !ruby/object:DateTime 2015-11-25 14:49:37.233000000 Z title: '2013,2034.4323' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6eeWLekeOI6MC2OO8SkAEk/2ce480e7c388db97e2619927c84ca059/2013_2034.4323.jpg" caption: Polished cattle engravings belonging to the Early Hunter Period. Tegharghart, south of Djanet, Tassili n'Ajjer, Algeria. 2013,2034.4323 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3601754&partId=1&images=true&people=197356&museumno=2013,2034.4323&page=1 - sys: id: 4iofe61DXWSWEe2iIkmoQC created_at: !ruby/object:DateTime 2015-11-25 14:52:40.114000000 Z updated_at: !ruby/object:DateTime 2015-11-25 14:52:40.115000000 Z content_type_id: chapter revision: 1 title_internal: 'Algeria: featured site, chapter 2' body: |- These skilfully engraved images depict long-horned cattle with their heads bowed. Thought to date between 7,000 and 8,000 years ago, today these images stand alone in a vast wilderness of sand and rock. However, this environment was once wetter and more fertile, and this site may have been close to a local watering hole where animals regularly drank and bathed. Indeed, even today during the rains, the depression in the sand at the base of the inselberg fills up with water, which gives the appearance that the cows are bending their heads to drink. These engravings are incorporated in a local myth that tells of a shepherd who engraved the crying cows after travelling night and day with his herd to a spring he thought would quench their thirst. Finding it dry, he captured in stone his cattle’s grief as he watched them die one by one. Climatic data has shown a number of significant cooling events in the North Atlantic, one of which – dating to around eight thousand years ago – resulted in a period of aridity lasting a number of centuries across the Sahara, and may coincide with these engravings and of the associated myth. - sys: id: 1Amw4cfI1K6G6guu4aQQey created_at: !ruby/object:DateTime 2015-11-25 14:51:44.418000000 Z updated_at: !ruby/object:DateTime 2017-01-06 15:43:21.104000000 Z content_type_id: image revision: 2 image: sys: id: 4BNQt2lt84WMoouGQgc6G0 created_at: !ruby/object:DateTime 2015-11-25 14:49:37.249000000 Z updated_at: !ruby/object:DateTime 2015-11-25 14:49:37.249000000 Z title: '2013,2034.4328' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4BNQt2lt84WMoouGQgc6G0/96d40531dacc2538ad5c32de06190654/2013_2034.4328.jpg" caption: Close-up of polished cattle engravings. 2013,2034.4328 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3601772&partId=1&images=true&people=197356&museumno=2013,2034.4328&page=1 - sys: id: 6zymCcOSMo8AAimOWw0IuK created_at: !ruby/object:DateTime 2015-11-25 14:53:00.226000000 Z updated_at: !ruby/object:DateTime 2015-11-25 14:53:00.226000000 Z content_type_id: chapter revision: 1 title_internal: 'Algeria: featured site, chapter 3' body: In artistic terms, the execution of this panel of engraved cows is extremely accomplished and testifies to someone who was not only a skilful carver but who we might even regard as a sculptor in the modern sense, who understood both materials and the interplay of light and shade in the reductive process of carving. But even more than this, the artist understood the environmental conditions in which he was working. It has been observed that the depth and thickness of the engraved lines has been carefully calculated to ensure that as the sun travels across them during the day, they appear to move. This sense of movement is made most acute as the evening shadows, falling into each groove, give the cattle a sense of mass and movement. Other artistic devices, such as double lines with recessed areas and internal polishing, evoke a perception of depth and density. The interplay of light and shade is consummately adept and dynamic, and the sculptural quality of the image sensorially evocative. This is the work of a practised craftsman, who demonstrates a deep of understanding of materials, techniques and the natural environment. background_images: - sys: id: 3bwDgmmud2wssS4kAi0YMe created_at: !ruby/object:DateTime 2015-12-07 20:09:47.529000000 Z updated_at: !ruby/object:DateTime 2015-12-07 20:09:47.529000000 Z title: ALGDJA0010009 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3bwDgmmud2wssS4kAi0YMe/e6733b7060e67b2e94eecf1e08563a1b/ALGDJA0010009.jpg" - sys: id: 7vsU1HA1s44SaSkK2mGiAU created_at: !ruby/object:DateTime 2015-12-07 20:09:47.502000000 Z updated_at: !ruby/object:DateTime 2015-12-07 20:09:47.502000000 Z title: ALGTDR0140002 description: url: "//images.ctfassets.net/xt8ne4gbbocd/7vsU1HA1s44SaSkK2mGiAU/cfa5804c371b2239e6d843593c6297fd/ALGTDR0140002.jpg" key_facts: sys: id: 4ZqlOQDPO8Kuq4U4sWmAkA created_at: !ruby/object:DateTime 2015-11-26 11:21:04.381000000 Z updated_at: !ruby/object:DateTime 2015-11-26 11:22:29.771000000 Z content_type_id: country_key_facts revision: 2 title_internal: 'Algeria: key facts' image_count: 1,511 images date_range: Mostly 10,000 BC main_themes: Animals, symbolically or magically charged figures, hunting, pastoralism, scenes of everyday life, trade and transport using horses and camels famous_for: Paintings from the Round Head Period thematic_articles: - sys: id: bl0Xb7b67YkI4CMCwGwgy created_at: !ruby/object:DateTime 2015-11-27 11:40:20.548000000 Z updated_at: !ruby/object:DateTime 2019-02-12 02:25:05.303000000 Z content_type_id: thematic revision: 8 title: The art of the warrior slug: the-art-of-the-warrior lead_image: sys: id: 69ZiYmRsreOiIUUEiCuMS6 created_at: !ruby/object:DateTime 2015-11-25 17:20:27.484000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:20:27.484000000 Z title: '2013,2034.9707' description: url: "//images.ctfassets.net/xt8ne4gbbocd/69ZiYmRsreOiIUUEiCuMS6/3b4c3bdee6c66bce875eef8014e5fe93/2013_2034.9707.jpg" chapters: - sys: id: 2YeH0ki7Pq08iGWoyeI2SY created_at: !ruby/object:DateTime 2015-11-27 12:04:20.772000000 Z updated_at: !ruby/object:DateTime 2015-12-11 11:29:10.545000000 Z content_type_id: chapter revision: 2 title_internal: 'Warrior: thematic, chapter 1' body: | Historically, much of the rock art from across northern Africa has been classified according to a particular style or ‘school’ of depictions. One such category of images, known as the Libyan Warrior School or Libyan Warrior style is found predominantly in Niger. Typically, this style “…commonly depicts human figures, mainly armed warriors; women are very rare. The style is fairly crude and the technique unsophisticated, almost invariably a rather careless pecking. The figures, almost always presented frontally with their heads quite circular, with added lobes, or mushroom-shaped, are shown according to a symmetrical schema. Various garment decorations and feathers in the hair are common, and the warrior often holds one or two throwing-spears – the bow is almost lacking – and frequently also holds by the leading rein a typical horse; foreshortened with large hindquarters” (Muzzolini, 2001:614) Termed *Libyan Warriors* by French ethnographer <NAME>, these representations have been associated with Garamantes’ raids, possibly 2,500 years ago. Thought to be descended from Berbers and Saharan pastoralists who settled in central Libya from around 1500 BC, the Garamantes developed a thriving urban centre, with flourishing trade networks from Libya to Niger. In contrast, <NAME>, a military man who led two big expeditions to the Sahara in the 1920s, proposed that these figures represent Tuareg; a people reputedly of Berber descent who live a nomadic pastoralist lifestyle. They have their own script known as Tifinagh, which is thought to have Libyan roots and which is engraved onto rocks alongside other rock art depictions. - sys: id: 3TQXxJGkAgOkCuQeq4eEEs created_at: !ruby/object:DateTime 2015-11-25 17:21:56.426000000 Z updated_at: !ruby/object:DateTime 2018-05-15 14:09:37.769000000 Z content_type_id: image revision: 2 image: sys: id: 2HdsFc1kI0ogGEmGWi82Ci created_at: !ruby/object:DateTime 2015-11-25 17:20:56.981000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:20:56.981000000 Z title: '2013,2034.11148' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2HdsFc1kI0ogGEmGWi82Ci/5c85cb71338ff7ecd923c26339a73ef5/2013_2034.11148.jpg" caption: "‘Typical’ Libyan Warrior style figure with horse. Indakatte, Western Aïr Mountains, Niger. 2013,2034.11148 © TARA/<NAME>" col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3649143&partId=1&searchText=2013,2034.11148&page=1 - sys: id: IENFM2XWMKmW02sWeYkaI created_at: !ruby/object:DateTime 2015-11-27 12:05:01.774000000 Z updated_at: !ruby/object:DateTime 2015-12-11 11:30:21.015000000 Z content_type_id: chapter revision: 2 title_internal: 'Warrior: thematic, chapter 2' body: | Libyan Warrior figures are almost exclusively located in the Aïr Mountains of Niger although can also be found in the Adrar des Iforas, north-east Mali extending into Algeria. Defining the Libyan Warrior Period chronologically is a challenge and dates are fairly fluid; the earliest dates suggested start from 5,200 years ago; it certainly coincides with the Horse period between 3,000-2,000 years ago but has also been proposed to continue throughout the Camel Period, from 2,000 years ago to present. From the sample of images we have as part of this collection it is clear that not all figures designated as falling under the umbrella term of Libyan Warrior style all share the same characteristics; there are similarities, differences and adjacencies even between what we may term a ‘typical’ representation. Of course, if these images span a period of 5,000 years then this may account for the variability in the depictions. - sys: id: 1vwQrEx1gA2USS0uSUEO8u created_at: !ruby/object:DateTime 2015-11-25 17:22:32.328000000 Z updated_at: !ruby/object:DateTime 2018-05-15 14:10:06.087000000 Z content_type_id: image revision: 2 image: sys: id: 69ZiYmRsreOiIUUEiCuMS6 created_at: !ruby/object:DateTime 2015-11-25 17:20:27.484000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:20:27.484000000 Z title: '2013,2034.9707' description: url: "//images.ctfassets.net/xt8ne4gbbocd/69ZiYmRsreOiIUUEiCuMS6/3b4c3bdee6c66bce875eef8014e5fe93/2013_2034.9707.jpg" caption: "‘Typical’ Libyan Warrior style figure with antelope. Iwellene, Northern Aïr Mountains, Niger. 2013,2034.9707 © TARA/<NAME>" col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3649767&partId=1&searchText=2013,2034.9707&page=1 - sys: id: 13aC6FIWtQAauy2SYC6CQu created_at: !ruby/object:DateTime 2015-11-27 12:05:26.289000000 Z updated_at: !ruby/object:DateTime 2015-11-27 12:05:26.289000000 Z content_type_id: chapter revision: 1 title_internal: 'Warrior: thematic, chapter 3' body: However, for the majority of figures their posture is remarkably similar even though objects of material culture and the types of garments they wear may show more diversity. The overriding feature is that figures are positioned frontally with arms bent and raised, often displaying splayed fingers. In some cases figures hold weapons and shields, but some do not. Some wear obviously elaborate headdresses, but in others the features look more coiffure-like. Selected garments are decorated with geometric patterns, others are plain; not all wear items of personal ornamentation. Certainly, not all figures are associated with horses, as typically characterised. Moreover, rather than all being described as unsophisticated or careless, many are executed showing great technique and skill. So how do we start to make sense of this contradiction between consistency and variation? - sys: id: 4thny4IiHKW66c2sGySMqE created_at: !ruby/object:DateTime 2015-11-25 17:28:05.405000000 Z updated_at: !ruby/object:DateTime 2018-05-15 14:15:37.257000000 Z content_type_id: image revision: 3 image: sys: id: 4Mq2eZY2bKogMqoCmu6gmW created_at: !ruby/object:DateTime 2015-11-25 17:20:40.548000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:20:40.548000000 Z title: '2013,2034.11167' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4Mq2eZY2bKogMqoCmu6gmW/9916aa4ecde51858768639f010a0442e/2013_2034.11167.jpg" caption: Infissak, Western Aïr Mountains, Niger. 2013,2034.11167 © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3648925&partId=1&searchText=2013,2034.11167&page=1 - sys: id: 1D7OVEK1eouQAsg6e6esS4 created_at: !ruby/object:DateTime 2015-11-27 12:05:50.702000000 Z updated_at: !ruby/object:DateTime 2015-12-11 11:36:43.690000000 Z content_type_id: chapter revision: 3 title_internal: 'Warrior: thematic, chapter 4' body: A criticism of Saharan rock art research, in comparison to that which has focused on other parts of Africa, is an under-theorisation of how the art links to past ethnic, archaeological or other identities (Smith,2013:156). This is tricky when dealing with past societies which were potentially nomadic, and where their archaeological remains are scarce. However, recent anthropological research may inform our thinking in this area. A member of the Wodaabe cultural group (nomadic cattle-herders and traders in the Sahel) on seeing a photograph of a Libyan-Warrior engraving and noting the dress and earrings told photographer <NAME> that it represents a woman performing a traditional greeting dance with arms outstretched and about to clap (Coulson and Campbell,2001:210). - sys: id: 6GvLgKrVXaSIQaAMECeE2m created_at: !ruby/object:DateTime 2015-11-25 17:31:34.914000000 Z updated_at: !ruby/object:DateTime 2018-05-15 14:15:11.171000000 Z content_type_id: image revision: 2 image: sys: id: 18c47Fe9jeoIi4CouE8Eya created_at: !ruby/object:DateTime 2015-11-25 17:20:10.453000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:20:10.453000000 Z title: '2013,2034.11133' description: url: "//images.ctfassets.net/xt8ne4gbbocd/18c47Fe9jeoIi4CouE8Eya/189da8bf1c84d7f95b532cf59780fe82/2013_2034.11133.jpg" caption: Two Libyan Warrior style figures, Western Aïr Mountains, Niger. 2013,2034.11133 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3649155&partId=1&searchText=2013,2034.11133&page=1 - sys: id: 4wQK9fpysE0GEaGYOEocws created_at: !ruby/object:DateTime 2015-11-27 12:06:27.167000000 Z updated_at: !ruby/object:DateTime 2018-05-15 14:17:33.313000000 Z content_type_id: chapter revision: 3 title_internal: 'Warrior: thematic, chapter 5' body: "Such a comment suggests that local ethnographies might assist in an understanding of more recent rock art, that not all figures described as Libyan-Warrior may necessarily be the same, and indeed that women may not be as rare as previously documented. In fact, the Wodaabe have been noted to resemble figures in other Saharan rock art contexts (see article on Hairdressing in the Acacus).\n\nIf we accept that some of these representations share affinities with the Wodaabe then thinking about this category of images from an ethnographic perspective may prove productive. Moreover, the British Museum’s existing ethnographic collections are simultaneously a useful resource by which we can potentially add more meaning to the rock art images.\n\nThe Wodaabe belong to the Fulani people, numbering 20 million and currently living across eighteen countries. The Wodaabe comprise 2-3% of the Fulani cultural group, still live as true nomads and are considered to have the most traditional culture of all the Fulani (Bovin,2001:13).\t\n" - sys: id: 2oNDIVZY2cY6y2ACUykYiW created_at: !ruby/object:DateTime 2015-11-25 17:31:55.456000000 Z updated_at: !ruby/object:DateTime 2018-05-15 14:26:02.339000000 Z content_type_id: image revision: 2 image: sys: id: 2klydX5Lbm6sGIUO8cCuow created_at: !ruby/object:DateTime 2015-11-25 17:20:40.581000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:20:40.581000000 Z title: Wodaabe description: url: "//images.ctfassets.net/xt8ne4gbbocd/2klydX5Lbm6sGIUO8cCuow/af221201c757ffe51e741300ffaefcba/Wodaabe.jpg" caption: Wodaabe men preparing for Gerewol ceremony ©<NAME>, Wikimedia Commons col_link: https://commons.wikimedia.org/wiki/File:Flickr_-_Dan_Lundberg_-_1997_%5E274-33_Gerewol_contestants.jpg - sys: id: 3SOhBsJLQACesg4wogaksm created_at: !ruby/object:DateTime 2015-11-27 12:07:09.983000000 Z updated_at: !ruby/object:DateTime 2015-11-27 12:07:09.983000000 Z content_type_id: chapter revision: 1 title_internal: 'Warrior: thematic, chapter 6' body: "The Wodaabe have become particularly well-known in the West through visual anthropology, because of their emphasis on cultivating male personal beauty and adornment. Men invest enormous amounts of time in personal artistic expression; much more so than women. Anthropologists have documented the constant checking of Wodaabe men in their mirrors; a Wodaabe man will not even go out among the cows in the morning until he has checked and tidied himself. They spend hours every day on their appearance and have been described as styling themselves like “living paintings” and “living statues” (Bovin, 2001:72). Symmetry plays a particularly significant part in Wodaabe culture and is reflected in all their artistic expressions. Symmetry stands for culture, asymmetry stands for nature. Culture is order and nature is disorder (Bovin,2001:17). Everyday Wodaabe life is imbued with artistic expression, whereby “every individual is an active creator, decorator and performer (Bovin, 2001:15).\n\nSo, how might we see Wodaabe cultural traits reflected in the Libyan-Warrior figures?\n\nPlumage is often depicted on these Warrior figures and for the most part is assumed to simply be part of the warrior regalia. The ostrich feather, a phallic symbol in Wodaabe culture, is an important element in male adornment and is carefully placed in the axis of symmetry in the middle of a man’s turban, worn during dancing ceremonies (Bovin, 2001:41). Music and dancing are typical of Fulani traditions, characterized by group singing and accompanied by clapping, stomping and bells. The feathers in the British Museum’s collections are known to be dance ornaments, worn during particular ceremonies. \n" - sys: id: 4AsNsHJ1n2USWMU68cIUko created_at: !ruby/object:DateTime 2015-11-27 11:46:03.474000000 Z updated_at: !ruby/object:DateTime 2018-05-15 14:30:37.659000000 Z content_type_id: image revision: 4 image: sys: id: 6QT0CdFAgoISmsuUk6u4OW created_at: !ruby/object:DateTime 2015-11-27 11:54:37.045000000 Z updated_at: !ruby/object:DateTime 2015-11-27 11:54:37.045000000 Z title: Af2005,04.6 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6QT0CdFAgoISmsuUk6u4OW/02489b2a4374bdb0a92ad9684f6120f4/Af2005_04.6_1.jpg" caption: Wodaabe dancing feather from the British Museum collections. Af2005,04.6 © Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=1585897&partId=1&searchText=Af2005%2c04.6&view=list&page=1 - sys: id: 5z7EqYMmFaI0Eom6AAgu6i created_at: !ruby/object:DateTime 2015-11-27 11:57:19.817000000 Z updated_at: !ruby/object:DateTime 2018-05-15 14:28:41.984000000 Z content_type_id: image revision: 2 image: sys: id: 10pBS62m3eugyAkY8iQYGs created_at: !ruby/object:DateTime 2015-11-25 17:20:48.548000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:20:48.548000000 Z title: '2013,2034.9037' description: url: "//images.ctfassets.net/xt8ne4gbbocd/10pBS62m3eugyAkY8iQYGs/b54aab41922ff6690ca59533afddeb84/2013_2034.9037.jpg" caption: Libyan Warrior figure showing symmetrical plumage from Eastern Aïr Mountains, Niger. 2013,2034.9037 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3636108&partId=1&searchText=2013,2034.9037&page=1 - sys: id: 1UmQD1rR0IISqKmGe4UWYs created_at: !ruby/object:DateTime 2015-11-27 11:47:12.062000000 Z updated_at: !ruby/object:DateTime 2018-05-15 14:28:08.133000000 Z content_type_id: image revision: 3 image: sys: id: 5oL3JD0PbaEMMyu4mA0oGw created_at: !ruby/object:DateTime 2015-11-27 11:54:37.053000000 Z updated_at: !ruby/object:DateTime 2015-11-27 11:54:37.053000000 Z title: Af2005,04.20 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/5oL3JD0PbaEMMyu4mA0oGw/72bb636538c36d21c62fef5628556238/Af2005_04.20_1.jpg" caption: Wodaabe dancing feather from the British Museum collections. Af2005,04.20 © Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=1585792&partId=1&searchText=Af2005%2c04.20&view=list&page=1 - sys: id: 45NYo7UU5ymOCYiqEYyQQO created_at: !ruby/object:DateTime 2015-11-27 12:07:34.816000000 Z updated_at: !ruby/object:DateTime 2015-11-27 12:07:34.816000000 Z content_type_id: chapter revision: 1 title_internal: 'Warrior: thematic, chapter 7' body: One of the recurring features of the Warrior engravings is the round discs that seem to be suspended from a figure’s arm or shoulder. Historically, these have been interpreted as shields, which one might expect a warrior to be carrying and in part this may be the case. - sys: id: 55JXs6mmfCoM6keQuwSeKA created_at: !ruby/object:DateTime 2015-11-27 11:59:13.850000000 Z updated_at: !ruby/object:DateTime 2018-05-15 14:31:16.112000000 Z content_type_id: image revision: 2 image: sys: id: 3s0PrjlXlS2QwMKMk0giog created_at: !ruby/object:DateTime 2015-11-25 17:20:56.985000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:20:56.985000000 Z title: '2013,2034.9554' description: url: "//images.ctfassets.net/xt8ne4gbbocd/3s0PrjlXlS2QwMKMk0giog/bef0019b59e2abe3ba3e29a4377eedd0/2013_2034.9554.jpg" caption: Warrior style figure holding ‘shields’. Eastern Aïr Mountains, Niger. 2013,2034.9554 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3639988&partId=1&searchText=2013,2034.9554&page=1 - sys: id: 2UL4zsEuwgekwI0ugSOSok created_at: !ruby/object:DateTime 2015-11-27 11:59:49.961000000 Z updated_at: !ruby/object:DateTime 2018-05-15 14:31:41.776000000 Z content_type_id: image revision: 2 image: sys: id: 3XjtbP2JywoCw8Qm0O8iKo created_at: !ruby/object:DateTime 2015-11-25 17:20:48.555000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:20:48.555000000 Z title: '2013,2034.9600' description: url: "//images.ctfassets.net/xt8ne4gbbocd/3XjtbP2JywoCw8Qm0O8iKo/fc0ccf0eb00a563da9a60276c87bbc11/2013_2034.9600.jpg" caption: Warrior style figure holding ‘shields’. Eastern Aïr Mountains, Niger. 2013,2034.9600 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3639940&partId=1&searchText=2013,2034.9600&page=1 - sys: id: 64MCgMHx60M8e0GSCaM2qm created_at: !ruby/object:DateTime 2015-11-27 12:07:53.749000000 Z updated_at: !ruby/object:DateTime 2015-11-27 12:07:53.749000000 Z content_type_id: chapter revision: 1 title_internal: 'Warrior: thematic, chapter 8' body: However, others may represent shoulder bags or flat baskets which are used as vessel covers or food trays; both of which are vital items in a nomadic lifestyle. Alternatively, they may represent calabashes. Wodaabe women measure their worldly wealth in calabashes and can acquire many in a lifetime, mostly ornamental to be displayed only on certain ceremonial occasions. If some of these depictions are not necessarily men or warriors then what have been considered shields may in fact represent some other important item of material culture. - sys: id: 78Ks1B0PPUA8YIm0ugMkQK created_at: !ruby/object:DateTime 2015-11-27 12:00:47.553000000 Z updated_at: !ruby/object:DateTime 2018-05-15 14:33:27.671000000 Z content_type_id: image revision: 2 image: sys: id: 5SDdxljduwuQggsuWcYUCA created_at: !ruby/object:DateTime 2015-11-25 17:20:48.583000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:20:48.583000000 Z title: Af,B47.19 description: url: "//images.ctfassets.net/xt8ne4gbbocd/5SDdxljduwuQggsuWcYUCA/eeb48a1ec8550bb4e1622317e5b7cea0/Af_B47.19.jpg" caption: Photograph of three Fulani male children 'dressed up for a ceremonial dance'. They are carrying shoulder-bags and holding sticks, and the male at right has flat basket impaled on stick. Rural setting. Af,B47.19 © Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=1410664&partId=1&searchText=Af,B47.19&page=1 - sys: id: 5nvXXoq4Baa0IwOmMSiUkI created_at: !ruby/object:DateTime 2015-11-27 12:08:13.833000000 Z updated_at: !ruby/object:DateTime 2015-11-27 12:08:13.833000000 Z content_type_id: chapter revision: 1 title_internal: 'Warrior: thematic, chapter 9' body: Engraved figures are often depicted with geometric patterning across their torso which may reflect traditional garments. This armless Wodaabe vest is decorated with abstract geometric combinations; patterns similar to those found on amulets, bags, containers and other artefacts as well as rock art. - sys: id: 1Huul8DwMcACSECuGoASE2 created_at: !ruby/object:DateTime 2015-11-27 12:01:35.826000000 Z updated_at: !ruby/object:DateTime 2018-05-15 14:35:18.268000000 Z content_type_id: image revision: 2 image: sys: id: 1PmWIHnxq0cAESkGiiWCkK created_at: !ruby/object:DateTime 2015-11-25 17:20:48.554000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:20:48.554000000 Z title: '7,2023.1' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1PmWIHnxq0cAESkGiiWCkK/51912ac1b7bffafe18fbbbb48a253fe9/7_2023.1.jpg" caption: Wodaabe vest, Niger. 2007,2023.1 ©Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3372277&partId=1&searchText=2007%2c2023.1&view=list&page=1 - sys: id: GT1E1E6FMc04CaQQUEuG6 created_at: !ruby/object:DateTime 2015-11-27 12:02:14.003000000 Z updated_at: !ruby/object:DateTime 2018-05-15 14:37:15.633000000 Z content_type_id: image revision: 2 image: sys: id: lz2F9O4kSWoi2g68csckA created_at: !ruby/object:DateTime 2015-11-25 17:20:48.580000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:20:48.580000000 Z title: '2013,2034.9016' description: url: "//images.ctfassets.net/xt8ne4gbbocd/lz2F9O4kSWoi2g68csckA/97f7a9fbec98c4af224273fbd3f7e9a5/2013_2034.9016.jpg" caption: Eastern Aïr Mountains, Niger. 2013,2034.9016 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3636134&partId=1&searchText=2013%2c2034.9016&&page=1 - sys: id: MH7tazL1u0ocyy6ysc8ci created_at: !ruby/object:DateTime 2015-11-27 12:08:38.359000000 Z updated_at: !ruby/object:DateTime 2015-11-27 12:08:38.359000000 Z content_type_id: chapter revision: 1 title_internal: 'Warrior: thematic, chapter 10' body: |- There is also a consensus within Wodaabe society about beauty and ugliness; what makes something beautiful or indeed ugly generally is agreed upon, there is a commonality of taste. This may account for the paradox of why there is individuality within a corpus of images that inherently are comparable (Bovin,2001:16). As nomads, Wodaabe do not identify themselves by place or territory as such, but a Wodaabe’s body is a repository of culture to mark them out against nature. Culture is not seen as an unessential indulgence but as an imperative necessity, it is part of one’s survival and existence in an inhospitable environment. We may speculate that rock art images may be seen as a way of stamping culture on nature; markers of socialised space. - sys: id: 5f7LkndYMoCiE0C6cYI642 created_at: !ruby/object:DateTime 2015-11-27 12:02:44.521000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:04:54.162000000 Z content_type_id: image revision: 4 image: sys: id: 4S1bl6LKUEKg0mMiQMoS2i created_at: !ruby/object:DateTime 2015-11-25 17:20:33.489000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:20:33.489000000 Z title: Gerewol description: url: "//images.ctfassets.net/xt8ne4gbbocd/4S1bl6LKUEKg0mMiQMoS2i/77678da7ac7b9573cfdfdcc9222b4187/Gerewol.jpg" caption: Wodaabe participants in the Gerewol beauty contest. ©<NAME> via Wikimedia Commons col_link: https://commons.wikimedia.org/wiki/File:1997_274-5_Gerewol.jpg - sys: id: 2s5eLxURwgEKUGYiCc62MM created_at: !ruby/object:DateTime 2015-11-27 12:03:20.752000000 Z updated_at: !ruby/object:DateTime 2018-05-15 14:40:40.756000000 Z content_type_id: image revision: 2 image: sys: id: 3as8UfaNIk22iQwu2uccsO created_at: !ruby/object:DateTime 2015-11-25 17:20:57.016000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:20:57.016000000 Z title: '2013,2034.9685' description: url: "//images.ctfassets.net/xt8ne4gbbocd/3as8UfaNIk22iQwu2uccsO/bef9cc4c65f13f394c4c6c03fa665aab/2013_2034.9685.jpg" caption: Four Warrior style figures, Eastern Aïr Mountains, Niger. 2013,2034.9685 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3644735&partId=1&searchText=2013,2034.9685&page=1 - sys: id: 4c37ixkB72GaCAkSYwGmSI created_at: !ruby/object:DateTime 2015-11-27 12:08:59.408000000 Z updated_at: !ruby/object:DateTime 2015-11-27 12:08:59.408000000 Z content_type_id: chapter revision: 1 title_internal: 'Warrior: thematic, chapter 11' body: This brief review was motivated, in part, by the underlying problems inherent in the categorisation of visual culture. Historically assigned classifications are not fixed and armed with current knowledge across a range of resources we may provide further insights into these enigmatic representations. Obviously, a much more systematic study of this category known as Libyan-Warrior figures needs to be undertaken to determine their distribution and the similarities and differences between depictions across sites. Additionally, care must be taken making connections with a cultural group whose material culture has changed over the course of the twentieth century. Nevertheless, it seems the category of Libyan-Warrior figures is an area that is ripe for more intensive investigation. citations: - sys: id: 2YpbTzVtq8og44KCIYKySK created_at: !ruby/object:DateTime 2015-11-25 17:17:36.606000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:17:36.606000000 Z content_type_id: citation revision: 1 citation_line: | <NAME>. 2001. *Nomads Who Cultivate Beauty*. Uppsala: Nordiska Afrikainstitutet <NAME> and <NAME>. 2001. *African Rock Art: Paintings and Engravings on Stone*. New York: Harry N Abrams Muzzolini, Alfred. 2001. ‘Saharan Africa’ In Whitley, D. (ed) *Handbook of Rock Art Research*: pp.605-636. Walnut Creek: Altamira Press <NAME>. 2013. Rock art research in Africa. In: Lane, P. & Mitchell, P. (eds) *Handbook of African Archaeology*: 145-162. Oxford: Oxford University Press. background_images: - sys: id: 4ICv2mLYykaUs2K6sI600e created_at: !ruby/object:DateTime 2015-12-07 19:16:46.680000000 Z updated_at: !ruby/object:DateTime 2015-12-07 19:16:46.680000000 Z title: NIGNAM0010007 description: url: "//images.ctfassets.net/xt8ne4gbbocd/4ICv2mLYykaUs2K6sI600e/175a170bba1f5856e70c2bb59a88e28f/NIGNAM0010007.jpg" - sys: id: 4sWbJZXtCUKKqECk24wOwi created_at: !ruby/object:DateTime 2015-12-07 19:16:46.673000000 Z updated_at: !ruby/object:DateTime 2015-12-07 19:16:46.673000000 Z title: NIGEAM0070022 description: url: "//images.ctfassets.net/xt8ne4gbbocd/4sWbJZXtCUKKqECk24wOwi/63797d84c9f0c89db25bd2f2cebaa21b/NIGEAM0070022.jpg" - sys: id: 5QHjLLZ7gs846I0a68CGCg created_at: !ruby/object:DateTime 2015-11-25 17:59:00.673000000 Z updated_at: !ruby/object:DateTime 2015-12-11 12:29:03.345000000 Z content_type_id: thematic revision: 6 title: 'Written in stone: the Libyco-Berber scripts' slug: written-in-stone lead_image: sys: id: 5m9CnpjjOgEIeiaW6k6SYk created_at: !ruby/object:DateTime 2015-11-25 17:39:38.305000000 Z updated_at: !ruby/object:DateTime 2015-12-08 08:25:55.339000000 Z title: '2013,2034.4200' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5m9CnpjjOgEIeiaW6k6SYk/3dd6ae7d242722aa740c7229eb70d4e7/ALGDJA0040010.jpg" chapters: - sys: id: 3fpuPIJW9i2ESgqYsEMe02 created_at: !ruby/object:DateTime 2015-11-25 17:49:07.520000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:49:16.531000000 Z content_type_id: chapter revision: 2 title_internal: 'Libyco-Berber: thematic, chapter 1' body: 'A remarkable feature of North African rock art is the existence of numerous engraved or painted inscriptions which can be found throughout the Sahara Desert. These inscriptions, generically named Libyco-Berber, are found from the west of Egypt to the Canary Islands and from the Mediterranean Sea to the Sahel countries to the south. Together with Egyptian hieroglyphs, they show us one of the earliest written languages in Africa and represent a most interesting and challenging topic in North African history. They appear in two different formats: engraved on *stelae* (mainly on the Mediterranean coast and its hinterland) or on rock faces, either isolated or alongside rock art paintings or engravings of the later periods of rock art.' - sys: id: 6MFGcsOw2QYceK2eWSsGqY created_at: !ruby/object:DateTime 2015-11-25 17:43:10.618000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:32:20.694000000 Z content_type_id: image revision: 3 image: sys: id: 5m9CnpjjOgEIeiaW6k6SYk created_at: !ruby/object:DateTime 2015-11-25 17:39:38.305000000 Z updated_at: !ruby/object:DateTime 2015-12-08 08:25:55.339000000 Z title: '2013,2034.4200' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5m9CnpjjOgEIeiaW6k6SYk/3dd6ae7d242722aa740c7229eb70d4e7/ALGDJA0040010.jpg" caption: View of red wolf or lion with an spiral tail. A Libyco-Berber script has been written under the belly, and another one can be seen to the lower left of the photograph. <NAME>, <NAME>'<NAME>. 2013,2034.4200 ©TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3601330&partId=1&searchText=2013,2034.4200&page=1 - sys: id: TwRWy4YkkUmg2yMGIWOQw created_at: !ruby/object:DateTime 2015-11-25 17:49:54.544000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:33:58.483000000 Z content_type_id: chapter revision: 3 title_internal: 'Libyco-Berber: thematic, chapter 2' body: Libyco-Berber characters were identified as written language as early as the 17th century, when some inscriptions in the language were documented in the Roman city of Dougga (Tunisia). They were deciphered by <NAME> in 1843 through the comparison of personal names with equivalent Punic names in bilingual scenes, although a few characters still remain uncertain. Since the beginning of the 19th century onwards many different proposals have been made to explain the origin, expansion and translation of these alphabets. There are three main explanations of its origin - the most accepted theory considers that the Libyco-Berber alphabet and principles of writing were borrowed from the Phoenician script, with other symbols added locally. - sys: id: pfjxB9ZjI4c68SYYOcc6C created_at: !ruby/object:DateTime 2015-11-25 17:43:34.886000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:35:37.505000000 Z content_type_id: image revision: 3 image: sys: id: 1i0U2eePgyWQKE8WgOEuug created_at: !ruby/object:DateTime 2015-11-25 17:40:16.321000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:56:27.808000000 Z title: Libyco theme figure 2 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1i0U2eePgyWQKE8WgOEuug/03cf171fe9cde8389b055b4740f8d1fd/29-10-2015_11.05.jpg" caption: Half of a bilingual inscription written in Numidian, part of a monument dedicated to Ateban, a Numidian prince. Numidian is one of the languages written in Libyco-Berber alphabets. 1852,0305.1 ©Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=368104&partId=1&searchText=1852,0305.1&page=1 - sys: id: 2QHgN5FuFGK4aoaWUcKuG2 created_at: !ruby/object:DateTime 2015-11-25 17:50:30.377000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:50:30.377000000 Z content_type_id: chapter revision: 1 title_internal: 'Libyco-Berber: thematic, chapter 3' body: A second, recent proposal has defended an indigenous (autochthonous) origin deriving from a stock of ancient signs –tribal tattoos, marks of ownership, or even geometric rock art- which could have resulted in the creation of the alphabet. Finally, a mixture of both theories accepts the borrowing of the idea of script and some Phoenician signs, which would be complemented with indigenous symbols. Although none of these theories can be fully accepted or refuted at the present moment, the proposal of a Phoenician borrowing has a wider support among linguistics and archaeologists. - sys: id: 67cDVCAn3GMK8m2guKMeuY created_at: !ruby/object:DateTime 2015-11-25 17:44:09.415000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:37:11.219000000 Z content_type_id: image revision: 2 image: sys: id: 4kXC2w9xCwAASweyCgwg2O created_at: !ruby/object:DateTime 2015-11-25 17:40:34.619000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:40:34.619000000 Z title: '2013,2034.4996' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4kXC2w9xCwAASweyCgwg2O/4d864b520d505029c7c8b90cd9e5fde2/ALGTOD0050035.jpg" caption: Engraved panel full of camels and human figures, surrounded by Libyco-Berber graffiti. <NAME> n’<NAME>. 2013,2034.4996 ©TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3623989&partId=1&searchText=2013,2034.4996&page=1 - sys: id: 4UXtnuK0VGkYKMGyuqseKI created_at: !ruby/object:DateTime 2015-11-25 17:50:56.343000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:50:56.343000000 Z content_type_id: chapter revision: 1 title: title_internal: 'Libyco-Berber: thematic, chapter 4' body: 'How is the Libyco-Berber alphabet composed? In fact, we should talk about Libyco-Berber alphabets, as one of the main characteristics of these scripts is their variety. In the mid-20th century, two main groups (eastern and western) were proposed, but this division is not so evident, and some studies have identified up to 25 different groups (grouped in 5 major families); some of them show strong similarities while between others up to half of the alphabetic symbols may be different. However, all these variants share common features: Libyco-Berber alphabetic symbols tend to be geometric, consisting of straight lines, circles and dots combined in different ways.' - sys: id: 13CDv9voc48oCmC0wqG4AA created_at: !ruby/object:DateTime 2015-11-25 17:44:51.935000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:37:41.169000000 Z content_type_id: image revision: 2 image: sys: id: 5rTkM78qGckOKu2q4AIUAI created_at: !ruby/object:DateTime 2015-11-25 17:40:51.188000000 Z updated_at: !ruby/object:DateTime 2015-12-08 08:28:43.019000000 Z title: '2013,2034.9338' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5rTkM78qGckOKu2q4AIUAI/1868823d4c9b78591d8fd94d156a8afc/NIGEAM0040013.jpg" caption: View of Libyan warrior holding a spear, surrounded by Libyco-Berber scripts. Ibel, Niger. 2013,2034.9338 ©TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3641907&partId=1&searchText=2013,2034.9338&page=1 - sys: id: 1gWJWaxXZYc4IiUyiC8IkQ created_at: !ruby/object:DateTime 2015-11-25 17:51:32.328000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:51:32.328000000 Z content_type_id: chapter revision: 1 title_internal: 'Libyco-Berber: thematic, chapter 5' body: 'The study of Libyco-Berber script faces some huge challenges. In addition to its aforementioned variability, it is necessary to differentiate the ancient languages spoken and written in North Africa during the Classical Antiquity for which a generic term of Libyco-Berber is used. Furthermore, Tifinagh script, the modern script of Tuareg people shares some symbols with the Libyco-Berber alphabet, but otherwise is a quite different language. Contemporary Tuareg cannot understand the old Libyco-Berber inscriptions although they recognize some symbols. Chronology represents another challenge: although the first dated inscription on a *stela* is from 138 BC, some pottery sherds with Libyco-Berber symbols could date from the 3rd century BC. For some researchers the oldest date (as old as the 7th century BC) is believed to correspond to an engraving located in the Moroccan High Atlas, although that theory is still under discussion. Finally, the characteristics of the scripts present some problems: they are usually short, repetitive and in many cases incomplete. Moreover, Libyco-Berber can be written in different directions (from right to left, bottom to top), complicating the identification, transcription and translation of the inscriptions. ' - sys: id: 6K1hjSQHrGSmMIwyi4aEci created_at: !ruby/object:DateTime 2015-11-25 17:46:00.776000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:39:20.711000000 Z content_type_id: image revision: 4 image: sys: id: 373GOE3JagQYoyY2gySyMy created_at: !ruby/object:DateTime 2015-11-25 17:41:18.933000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:41:18.933000000 Z title: '2013,2034.5878' description: url: "//images.ctfassets.net/xt8ne4gbbocd/373GOE3JagQYoyY2gySyMy/75c096cc7f233cedc2f75f58b0b41290/Oukaimeden_adapted.jpg" caption: Panel with elephants and human figures superimposed by two Libyco-Berber inscriptions, which some consider one of the oldest written in this alphabet, enhanced for a better view of the symbols. Oukaïmeden, Morocco. 2013,2034.5878 ©TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3613939&partId=1&searchText=2013,2034.5878&page=1 - sys: id: 3ik84OMvkQaEu6yOAeCMS6 created_at: !ruby/object:DateTime 2015-11-25 17:51:51.719000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:51:51.719000000 Z content_type_id: chapter revision: 1 title_internal: 'Libyco-Berber: thematic, chapter 6' body: Considering all these problems, what do we know about Libyco-Berber scripts? First of all, they normally used only consonants, although due to the influence of Punic (the language used in areas controlled or influenced by Carthage) and Latin, vowels were added in some alphabet variants. The translation of Libyco-Berber scripts is complicated, since the existing texts are very short and can only be translated through comparison with equivalent texts in Punic or Latin. Most of the translated scripts are very simple and correspond to personal and site names, or fixed formulations as “X son of Y”, characteristics of funerary epigraphy, or others such as, “It’s me, X”. Perhaps surprisingly, some of the translated inscriptions have an amorous meaning, with expressions as “I, X, love Y”. As the known Libyco-Berber corpus of inscriptions grows, it seems possible that more and more inscriptions will be translated, leading to a better understanding of the languages. - sys: id: 1t5dVxKpiIqeqy82O4McOI created_at: !ruby/object:DateTime 2015-11-25 17:46:35.246000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:43:47.775000000 Z content_type_id: image revision: 3 image: sys: id: 7x2yrpGfGEKaUQgyuiOYwk created_at: !ruby/object:DateTime 2015-11-25 17:41:38.056000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:41:38.056000000 Z title: '2013,2034.3203' description: url: "//images.ctfassets.net/xt8ne4gbbocd/7x2yrpGfGEKaUQgyuiOYwk/27f613c48b37dbb1114df7b733465787/LIBMES0180013.jpg" caption: Panel depicting cattle, giraffes and Libyco-Berber graffiti. In Galgiwen, Libya. 2013,2034.3203 ©TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3589647&partId=1&searchText=2013,2034.3203&page=1 - sys: id: 3Ju6IkGoneueE2gYQKaAQm created_at: !ruby/object:DateTime 2015-11-25 17:52:16.445000000 Z updated_at: !ruby/object:DateTime 2015-12-11 12:27:17.030000000 Z content_type_id: chapter revision: 2 title_internal: 'Libyco-Berber: thematic, chapter 7' body: Of course, the Libyco-Berber scripts evolved through time, although discussion is still going on about the chronologies and rhythms of this process. After the adoption and development of the alphabet, the Libyco-Berber reached a consideration of “official language” in the Numidian kingdom, which flourished in the north-western coast of Africa during the two latest centuries BC. The kingdom was highly influenced by Carthage and Rome, resulting in the existence of bilingual inscriptions that were the key to the translation of Libyco-Berber scripts. After Roman conquest, Libyco-Berber was progressively abandoned as a written language in the area, but inscriptions in the Sahara were still common until an unknown moment in the first millennium BC (the scripts sometimes receiving the name of Tifinagh). The Berber language, however, has been preserved and a new alphabet was developed in the 1960s to be used by Berber people. - sys: id: 1fPVVfXalmoKy2mUUCQQOw created_at: !ruby/object:DateTime 2015-11-25 17:47:18.568000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:44:36.059000000 Z content_type_id: image revision: 2 image: sys: id: 2GLzuqBeIMgoUW0wqeiiKY created_at: !ruby/object:DateTime 2015-11-25 17:41:59.073000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:41:59.073000000 Z title: '2013,2034.4468' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2GLzuqBeIMgoUW0wqeiiKY/0ec84dd4272a7227215c45d16f1451c5/ALGDJA0100009.jpg" caption: Raid scene on a camel caravan, with several interspersed Libyco-Berber inscriptions. Tassili plateau, Djanet, Algeria. 2013,2034.4468 ©TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3602846&partId=1&searchText=2013,2034.4468&page=1 - sys: id: 5GOzFzswmcs8qgiqQgcQ2q created_at: !ruby/object:DateTime 2015-11-25 17:52:52.167000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:52:52.167000000 Z content_type_id: chapter revision: 1 title_internal: 'Libyco-Berber: thematic, chapter 8' body: The many challenges that surround the study of Libyco-Berber scripts have led to a complex crossroads of terms, chronologies and theories which sometimes are contradictory and confusing. For the Rock Art Image Project, a decision had to be made to define the painted or engraved scripts in the collection and the chosen term was Libyco-Berber, as most of the images are associated with paintings of the Horse and Camel periods and thus considered to be up to 3,000 years old. Using the term Tifinagh could lead to misunderstandings with more modern scripts and the alphabet currently used by Berber peoples throughout North Africa. - sys: id: 6qjMP5OeukCMEiWWieE4O8 created_at: !ruby/object:DateTime 2015-11-25 17:47:52.571000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:46:54.999000000 Z content_type_id: image revision: 2 image: sys: id: FGpTfysHqEay4OMO66YSE created_at: !ruby/object:DateTime 2015-11-25 17:42:18.963000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:42:18.963000000 Z title: '2013,2034.2792' description: url: "//images.ctfassets.net/xt8ne4gbbocd/FGpTfysHqEay4OMO66YSE/c735c56a5dff7302beb58cec0e35bc85/LIBMES0040160.jpg" caption: Libyco-Berber inscription engraved near a cow. Wadi Mathendous, Libya. 2013,2034.2792 ©TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3584843&partId=1&searchText=2013,2034.2792&page=1 - sys: id: NeG74FoyYuOowaaaUYgQq created_at: !ruby/object:DateTime 2015-11-25 17:53:11.586000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:53:11.586000000 Z content_type_id: chapter revision: 1 title_internal: 'Libyco-Berber: thematic, chapter 9' body: Undoubtedly, the deciphering of forgotten languages captures the imagination and is one of the most exciting challenges in the study of ancient cultures. However, it is usually a difficult enterprise, as extraordinary finds which aid translation such as the Rosetta Stone are fairly exceptional and most of the time the transcription and translation of these languages is a long and difficult process in which the meaning of words and grammar rules is slowly unravelled. Although there are no shortcuts to this method, there are some initiatives that help to ease the task. One of them is making available catalogues of high quality images of inscriptions which can be studied and analysed by specialists. In that sense, the Libyco-Berber inscriptions present in the Rock Art Image Project catalogue can be truly helpful for all those interested in one of the most fascinating languages in the world; a language, which albeit modified has endured in different forms for hundreds of years. citations: - sys: id: 4r54ew5pNSwQ8ckQ8w8swY created_at: !ruby/object:DateTime 2015-11-25 17:48:24.656000000 Z updated_at: !ruby/object:DateTime 2015-12-11 12:28:59.132000000 Z content_type_id: citation revision: 2 citation_line: | <NAME>. 2012. Rock Art, Scripts and proto-scripts in Africa: the Libyco-berber example. In: Delmas, A. and Penn, P. (eds.), *Written Culture in a Colonial Context: Africa and the Americas 1500 – 1900*. Brill Academic Publishers, Boston, pp. 3-29. <NAME>. 2007. Origin and Development of the Libyco-Berber Script. Berber Studies 15. Rüdiger Köppe Verlag, Köln. [http://lbi-project.org/](http://lbi-project.org/) background_images: - sys: id: 4kXC2w9xCwAASweyCgwg2O created_at: !ruby/object:DateTime 2015-11-25 17:40:34.619000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:40:34.619000000 Z title: '2013,2034.4996' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4kXC2w9xCwAASweyCgwg2O/4d864b520d505029c7c8b90cd9e5fde2/ALGTOD0050035.jpg" - sys: id: 2GLzuqBeIMgoUW0wqeiiKY created_at: !ruby/object:DateTime 2015-11-25 17:41:59.073000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:41:59.073000000 Z title: '2013,2034.4468' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2GLzuqBeIMgoUW0wqeiiKY/0ec84dd4272a7227215c45d16f1451c5/ALGDJA0100009.jpg" - sys: id: 7oNFGUa6g8qSweyAyyiCAe created_at: !ruby/object:DateTime 2015-11-26 18:11:30.861000000 Z updated_at: !ruby/object:DateTime 2015-12-07 20:51:34.879000000 Z content_type_id: thematic revision: 4 title: The domesticated horse in northern African rock art slug: the-domesticated-horse lead_image: sys: id: n2MxgdjbMW2gm0IoOKkCU created_at: !ruby/object:DateTime 2015-11-26 17:51:43.133000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:43.133000000 Z title: Fig. 1. Painted horse description: url: "//images.ctfassets.net/xt8ne4gbbocd/n2MxgdjbMW2gm0IoOKkCU/e2c7369ef1e4ab11c71023a769f8fe0d/Fig._1._Painted_horse.jpg" chapters: - sys: id: 27bcd1mylKoMWiCQ2KuKMa created_at: !ruby/object:DateTime 2015-11-26 18:00:19.777000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:00:19.777000000 Z content_type_id: chapter revision: 1 title_internal: 'Thematic: horse, chapter 1' body: Throughout northern Africa, there is a wealth of rock art depicting the domestic horse and its various uses, providing valuable evidence for the uses of horses at various times in history, as well as a testament to their importance to Saharan peoples. - sys: id: 2EbfpTN9L6E0sYmuGyiaec created_at: !ruby/object:DateTime 2015-11-26 17:52:26.605000000 Z updated_at: !ruby/object:DateTime 2018-05-15 16:39:29.412000000 Z content_type_id: image revision: 2 image: sys: id: n2MxgdjbMW2gm0IoOKkCU created_at: !ruby/object:DateTime 2015-11-26 17:51:43.133000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:43.133000000 Z title: Fig. 1. Painted horse description: url: "//images.ctfassets.net/xt8ne4gbbocd/n2MxgdjbMW2gm0IoOKkCU/e2c7369ef1e4ab11c71023a769f8fe0d/Fig._1._Painted_horse.jpg" caption: 'Painted horse and rider, Ennedi Plateau, Chad. 2013,2034.6406 © TARA/David Coulson. ' col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3641775&partId=1&searchText=2013,2034.6406&page=1 - sys: id: 4QexWBEVXiAksikIK6g2S4 created_at: !ruby/object:DateTime 2015-11-26 18:00:49.116000000 Z updated_at: !ruby/object:DateTime 2018-05-15 16:40:28.446000000 Z content_type_id: chapter revision: 2 title: Horses and chariots title_internal: 'Thematic: horse, chapter 2' body: The first introduction of the domestic horse to Ancient Egypt- and thereby to Africa- is usually cited at around 1600 BC, linked with the arrival in Egypt of the Hyksos, a group from the Levant who ruled much of Northern Egypt during the Second Intermediate Period. By this point, horses had probably only been domesticated for about 2,000 years, but with the advent of the chariot after the 3rd millennium BC in Mesopotamia, the horse proved to be a valuable martial asset in the ancient world. One of the first clear records of the use of horses and chariots in battle in Africa is found in depictions from the mortuary complex of the Pharaoh Ahmose at Abydos from around 1525 BC, showing their use by Egyptians in defeating the Hyksos, and horses feature prominently in later Egyptian art. - sys: id: 22x06a7DteI0C2U6w6oKes created_at: !ruby/object:DateTime 2015-11-26 17:52:52.323000000 Z updated_at: !ruby/object:DateTime 2018-05-15 16:40:52.214000000 Z content_type_id: image revision: 2 image: sys: id: 1AZD3AxiUwwoYUWSWY8MGW created_at: !ruby/object:DateTime 2015-11-26 17:51:50.284000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:50.284000000 Z title: '2013,2034.1001' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1AZD3AxiUwwoYUWSWY8MGW/b68bd24c9b19c5c8c7752bfb75a5db0e/2013_2034.1001.jpg" caption: Painted two-horse chariot, Acacus Mountains, Libya. 2013,2034.1001 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3588526&partId=1&people=197356&museumno=2013,2034.1001&page=1 - sys: id: 1voXfvqIcQkgUYqq4w8isQ created_at: !ruby/object:DateTime 2015-11-26 18:01:15.173000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:01:15.173000000 Z content_type_id: chapter revision: 1 title_internal: 'Thematic: horse, chapter 3' body: 'Some of the most renowned images of horses in Saharan rock art are also those of chariot teams: in particular, those of the so-called ‘flying gallop’ style chariot pictures, from the Tassili n’Ajjer and Acacus mountains in modern Algeria and Libya. These distinctive images are characterised by depictions of one or more horses pulling a chariot with their legs outstretched in a stylised manner and are sometimes attributed to the Garamantes, a group who were a local power in the central Sahara from about 500 BC-700 AD. But the Ajjer Plateau is over a thousand miles from the Nile- how and when did the horse and chariot first make their way across the Western Desert to the rest of North Africa in the first place? Egyptian accounts indicate that by the 11th century BC Libyans (people living on the north African coast around the border of modern Egypt and Libya) were using chariots in war. Classical sources later write about the chariots of the Garamantes and of chariot use by peoples of the far western Sahara continuing into the 1st century BC, by which time the chariot horse had largely been eclipsed in war by the cavalry mount.' - sys: id: LWROS2FhUkywWI60eQYIy created_at: !ruby/object:DateTime 2015-11-26 17:53:42.845000000 Z updated_at: !ruby/object:DateTime 2018-05-15 16:41:33.841000000 Z content_type_id: image revision: 2 image: sys: id: 6N6BF79qk8EUygwkIgwcce created_at: !ruby/object:DateTime 2015-11-26 17:51:44.708000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:44.708000000 Z title: '2013,2034.4574' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6N6BF79qk8EUygwkIgwcce/ac95a5214a326794542e0707c0d819d7/2013_2034.4574.jpg" caption: Painted human figure and horse. Tarssed Jebest, Tassili n’Ajjer, Algeria. Horse displays Arabian breed-type characteristics such as dished face and high tail carriage. 2013,2034.4574 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3603790&partId=1&people=197356&museumno=2013,2034.4574+&page=1 - sys: id: 6eaH84QdUs46sEQoSmAG2u created_at: !ruby/object:DateTime 2015-11-26 18:01:48.835000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:01:48.835000000 Z content_type_id: chapter revision: 1 title: Horse Riding title_internal: 'Thematic: horse, chapter 4' body: As well as the unique iconography of rock art chariot depictions, there are also numerous paintings and engravings across northern Africa of people riding horses. Riding may have been practiced since the earliest times of horse domestication, though the earliest definitive depictions of horses being ridden come from the Middle East in the late 3rd and early 2nd millennia BC. Images of horses and riders in rock art occur in various areas of Morocco, Egypt and Sudan and are particularly notable in the Ennedi region of Chad and the Adrar and Tagant plateaus in Mauritania (interestingly, however, no definite images of horses are known in the Gilf Kebir/Jebel Uweinat area at the border of Egypt, Sudan and Libya). - sys: id: 6LTzLWMCTSak4IIukAAQMa created_at: !ruby/object:DateTime 2015-11-26 17:54:23.846000000 Z updated_at: !ruby/object:DateTime 2018-05-15 16:41:52.743000000 Z content_type_id: image revision: 2 image: sys: id: 4NdhGNLc9yEck4My4uQwIo created_at: !ruby/object:DateTime 2015-11-26 17:51:43.495000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:43.495000000 Z title: ME22958 description: url: "//images.ctfassets.net/xt8ne4gbbocd/4NdhGNLc9yEck4My4uQwIo/703945afad6a8e3c97d10b09c487381c/ME22958.jpg" caption: Terracotta mould of man on horseback, Old Babylonian, Mesopotamia 2000-1600 BC. One of the oldest known depictions of horse riding in the world. British Museum ME22958 © Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=388860&partId=1&people=197356&museumno=22958&page=1 - sys: id: 5YkSCzujy8o08yuomIu6Ei created_at: !ruby/object:DateTime 2015-11-26 17:54:43.227000000 Z updated_at: !ruby/object:DateTime 2018-05-16 11:12:34.068000000 Z content_type_id: image revision: 2 image: sys: id: 1tpjS4kZZ6YoeiWeIi8I4C created_at: !ruby/object:DateTime 2015-11-26 17:51:43.188000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:43.188000000 Z title: Fig. 5. Painted ‘bitriangular’ description: url: "//images.ctfassets.net/xt8ne4gbbocd/1tpjS4kZZ6YoeiWeIi8I4C/c798c1afb41006855c34363ec2b54557/Fig._5._Painted____bitriangular___.jpg" caption: Painted ‘bi-triangular’ horse and rider with saddle. Oued Jrid, Assaba, Mauritania. 2013,2034.12285 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3645983&partId=1&searchText=2013,2034.12285&page=1 - sys: id: 1vZDFfKXU0US2qkuaikG8m created_at: !ruby/object:DateTime 2015-11-26 18:02:13.433000000 Z updated_at: !ruby/object:DateTime 2018-05-16 11:14:56.468000000 Z content_type_id: chapter revision: 2 title_internal: 'Thematic: horse, chapter 5' body: Traditional chronologies for Saharan rock art areas tend to place depictions of ridden horses chronologically after those of horses and chariots, and in general use horse depictions to categorise regional stylistic periods of rock art according to broad date boundaries. As such, in most places, the ‘horse’ rock art period is usually said to cover about a thousand years from the end of the 2nd millennium BC. It is then considered to be succeeded by a ‘camel’ period, where the appearance of images of dromedaries – known only to have been introduced to the eastern Sahara from Arabia at the end of the 1st century BC – reflects the next momentous influx of a beast of burden to the area and thus a new dating parameter ([read more about depictions of camels in the Sahara](https://africanrockart.britishmuseum.org/thematic/camels-in-saharan-rock-art/)). However, such simplistic categorisation can be misleading. For one thing, although mounting horses certainly gained popularity over driving them, it is not always clear that depictions of ridden horses are not contemporary with those of chariots. Further, the horse remained an important martial tool after the use of war-chariots declined. Even after the introduction of the camel, there are several apparently contemporary depictions featuring both horse and camel riders. - sys: id: 2gaHPgtyEwsyQcUqEIaGaq created_at: !ruby/object:DateTime 2015-11-26 17:55:29.704000000 Z updated_at: !ruby/object:DateTime 2018-05-16 11:32:44.364000000 Z content_type_id: image revision: 3 image: sys: id: 6quML2y0nuYgSaeG0GGYy4 created_at: !ruby/object:DateTime 2015-11-26 17:51:50.292000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:50.292000000 Z title: '2013,2034.5739' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6quML2y0nuYgSaeG0GGYy4/7f48ae9c550dd6b4f0e80b8da10a3da6/2013_2034.5739.jpg" caption: Engraved ridden horse and camel. Draa Valley, Morocco. 2013,2034.5739 ©TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3619780&partId=1&people=197356&museumno=2013,2034.5739+&page=1 - sys: id: 583LKSbz9SSg00uwsqquAG created_at: !ruby/object:DateTime 2015-11-26 18:02:41.576000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:02:41.576000000 Z content_type_id: chapter revision: 1 title: Berber Horses title_internal: 'Thematic: horse, chapter 6' body: As the more manoeuvrable rider rose in popularity against the chariot as a weapon of war, historical reports from classical authors like Strabo tell us of the prowess of African horsemen such as the cavalry of the Numidians, a Berber group that allied with Carthage against the Romans in the 3rd century BC. Berber peoples would remain heavily associated with horse breeding and riding, and the later rock art of Mauritania has been attributed to Berber horsemen, or the sight of them. Although horses may already have reached the areas of modern Mauritania and Mali by this point, archaeological evidence does not confirm their presence in these south-westerly regions of the Sahara until much later, in the mid-1st millennium AD, and it has been suggested that some of the horse paintings in Mauritania may be as recent as 16th century. - sys: id: 7zrBlvCEGkW86Qm8k2GQAK created_at: !ruby/object:DateTime 2015-11-26 17:56:24.617000000 Z updated_at: !ruby/object:DateTime 2018-05-16 11:16:52.557000000 Z content_type_id: image revision: 2 image: sys: id: uOFcng0Q0gU8WG8kI2kyy created_at: !ruby/object:DateTime 2015-11-26 17:51:44.717000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:44.717000000 Z title: '2013,2034.5202' description: url: "//images.ctfassets.net/xt8ne4gbbocd/uOFcng0Q0gU8WG8kI2kyy/7fba0330e151fc416d62333f3093d950/2013_2034.5202.jpg" caption: Engraved horses and riders surrounded by Libyan-Berber script. Oued Djerat, Algeria. These images appear to depict riders using Arab-style saddles and stirrups, thus making them probably no older than 7th c. AD. 2013,2034.5202 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3624404&partId=1&people=197356&museumno=2013,2034.5202&page=1 - sys: id: 45vpX8SP7aGeOS0qGaoo4a created_at: !ruby/object:DateTime 2015-11-26 18:03:14.279000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:03:14.279000000 Z content_type_id: chapter revision: 1 title_internal: 'Thematic: horse, chapter 7' body: 'Certainly, from the 14th century AD, horses became a key commodity in trans-Saharan trade routes and became items of great military value in West Africa following the introduction of equipment such as saddles with structured trees (frames). Indeed, discernible images of such accoutrements in Saharan rock art can help to date it following the likely introduction of the equipment to the area: for example, the clear depiction of saddles suggests an image to be no older than the 1st century AD; images including stirrups are even more recent.' - sys: id: 7GeTQBofPamw0GeEAuGGee created_at: !ruby/object:DateTime 2015-11-26 17:56:57.851000000 Z updated_at: !ruby/object:DateTime 2018-05-16 11:29:02.520000000 Z content_type_id: image revision: 2 image: sys: id: 5MaSKooQvYssI4us8G0MyO created_at: !ruby/object:DateTime 2015-11-26 17:51:43.501000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:43.501000000 Z title: RRM12824 description: url: "//images.ctfassets.net/xt8ne4gbbocd/5MaSKooQvYssI4us8G0MyO/8c3a7c2d372f2c48a868d60201909932/RRM12824.jpg" caption: 19th-century Moroccan stirrups with typical curved base of the type possibly visible in the image above. 1939,0311.7-8 © Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=217451&partId=1&page=1 - sys: id: 6mNtqnqaEE2geSkU0IiYYe created_at: !ruby/object:DateTime 2015-11-26 18:03:32.195000000 Z updated_at: !ruby/object:DateTime 2018-05-16 11:29:50.228000000 Z content_type_id: chapter revision: 2 title_internal: 'Thematic: horse, chapter 8' body: 'Another intriguing possibility is that of gaining clues on the origins of modern horse breeds from rock art, in particular the ancient Barb breed native to the Maghreb, where it is still bred. Ancient Mesopotamian horses were generally depicted as heavily-built, and it has been suggested that the basic type for the delicate Arabian horse, with its dished (concave) facial profile and high-set tail, may have been developed in north-east Africa prior to its subsequent appearance and cultivation in Arabia, and that these features may be observed in Ancient Egyptian images from the New Kingdom. Likewise, there is the possibility that some of the more naturalistic paintings from the central Sahara show the similarly gracile features of the progenitors of the Barb, distinguishable from the Arab by its straight profile and low-set tail. Like the Arab, the Barb is a desert horse: hardy, sure-footed and able to withstand great heat; it is recognised as an ancient breed with an important genetic legacy, both in the ancestry of the Iberian horses later used throughout the Americas, and that of the modern racing thoroughbred.' - sys: id: 3OM1XJI6ruwGOwwmkKOKaY created_at: !ruby/object:DateTime 2015-11-26 17:57:25.145000000 Z updated_at: !ruby/object:DateTime 2018-05-16 11:30:30.915000000 Z content_type_id: image revision: 2 image: sys: id: 6ZmNhZjLCoQSEIYKIYUUuk created_at: !ruby/object:DateTime 2015-11-26 17:51:50.293000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:50.293000000 Z title: '2013,2034.1452' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6ZmNhZjLCoQSEIYKIYUUuk/45bbff5b29985eb19679e1e513499d6b/2013_2034.1452.jpg" caption: Engraved horses and riders, Awis, Acacus Mountains, Libya. High head carriage and full rumps suggest Arabian/Barb breed type features. Riders have been obscured. 2013,2034.1452 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3592678&partId=1&people=197356&museumno=2013,2034.1452&page=1 - sys: id: 40E0pTCrUIkk00uGWsus4M created_at: !ruby/object:DateTime 2015-11-26 17:57:49.497000000 Z updated_at: !ruby/object:DateTime 2018-05-16 11:33:55.443000000 Z content_type_id: image revision: 2 image: sys: id: 5mbJWrbZV6aQQOyamKMqIa created_at: !ruby/object:DateTime 2015-11-26 17:51:43.468000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:43.468000000 Z title: Fig. 10. Barb horses description: url: "//images.ctfassets.net/xt8ne4gbbocd/5mbJWrbZV6aQQOyamKMqIa/87f29480513be0a531e0a93b51f9eae5/Fig._10._Barb_horses.jpg" caption: Barb horses ridden at a festival in Agadir, Morocco. ©Notwist (Wikimedia Commons) col_link: https://commons.wikimedia.org/wiki/File:Berber_warriors_show.JPG - sys: id: 3z5YSVu9y8caY6AoYWge2q created_at: !ruby/object:DateTime 2015-11-26 18:04:02.770000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:04:02.770000000 Z content_type_id: chapter revision: 1 title: The symbolism of the horse title_internal: 'Thematic: horse, chapter 9' body: However, caution must be taken in drawing such comparisons based on morphology alone, especially given the gulf of time that has elapsed and the relative paucity of ‘naturalistic’ rock art images. Indeed, there is huge diversity of horse depictions throughout northern Africa, with some forms highly schematic. This variation is not only in style – and, as previously noted, in time period and geography – but also in context, as of course images of one subject cannot be divorced from the other images around them, on whichever surface has been chosen, and are integral to these surroundings. - sys: id: 1FRP1Z2hyQEWUSOoKqgic2 created_at: !ruby/object:DateTime 2015-11-26 17:58:21.234000000 Z updated_at: !ruby/object:DateTime 2019-02-21 15:41:39.821000000 Z content_type_id: image revision: 2 image: sys: id: 4EatwZfN72waIquQqWEeOs created_at: !ruby/object:DateTime 2015-11-26 17:51:43.121000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:43.121000000 Z title: '2013,2034.11147' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4EatwZfN72waIquQqWEeOs/d793f6266f2ff486e0e99256c2c0ca39/2013_2034.11147.jpg" caption: Engraved ‘Libyan Warrior-style’ figure with horse. Indakatte, Western Aïr Mountains, Niger. 2013,2034.11147 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3637713&partId=1&people=197356&museumno=2013,2034.11147+&page=1 - sys: id: 45pI4ivRk4IM6gaG40gUU0 created_at: !ruby/object:DateTime 2015-11-26 17:58:41.308000000 Z updated_at: !ruby/object:DateTime 2019-02-21 15:41:59.784000000 Z content_type_id: image revision: 2 image: sys: id: 2FcYImmyd2YuqMKQMwAM0s created_at: !ruby/object:DateTime 2015-11-26 17:51:43.117000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:43.117000000 Z title: Fig. 12. Human figure description: url: "//images.ctfassets.net/xt8ne4gbbocd/2FcYImmyd2YuqMKQMwAM0s/e48fda8e2a23b12e6afde5c560c3f164/Fig._12._Human_figure.jpg" caption: Human figure painted over by horse to appear mounted (digitally enhanced image). © TARA/<NAME> - sys: id: 54hoc6Htwck8eyewsa6kA8 created_at: !ruby/object:DateTime 2015-11-26 18:04:26.929000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:04:26.929000000 Z content_type_id: chapter revision: 1 title_internal: 'Thematic: horse, chapter 10' body: The nature of the depictions in this sense speaks intriguingly of the apparent symbolism and implied value of the horse image in different cultural contexts. Where some Tassilian horses are delicately painted in lifelike detail, the stockier images of horses associated with the so-called ‘Libyan Warrior’ style petroglyphs of the Aïr mountains and Adrar des Ifoghas in Niger and Mali appear more as symbolic accoutrements to the central human figures and tend not to be shown as ridden. By contrast, there are paintings in the Ennedi plateau of Chad where galloping horse figures have clearly been painted over existing walking human figures to make them appear as if riding. - sys: id: 4XMm1Mdm7Y0QacMuy44EKa created_at: !ruby/object:DateTime 2015-11-26 17:59:06.184000000 Z updated_at: !ruby/object:DateTime 2019-02-21 15:42:27.444000000 Z content_type_id: image revision: 2 image: sys: id: 21xnJrk3dKwW6uSSkGumMS created_at: !ruby/object:DateTime 2015-11-26 17:51:44.697000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:44.697000000 Z title: '2013,2034.6297' description: url: "//images.ctfassets.net/xt8ne4gbbocd/21xnJrk3dKwW6uSSkGumMS/698c254a9a10c5a9a56d69e0525bca83/2013_2034.6297.jpg" caption: Engraved horse, <NAME>, Ennedi Plateau, Chad. 2013,2034.6297 © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3637529&partId=1&people=197356&museumno=2013,2034.6297&page=1 - sys: id: 4rB9FCopjOCC4iA2wOG48w created_at: !ruby/object:DateTime 2015-11-26 17:59:26.549000000 Z updated_at: !ruby/object:DateTime 2019-02-21 15:43:34.211000000 Z content_type_id: image revision: 2 image: sys: id: 3PfHuSbYGcqeo2U4AEKsmM created_at: !ruby/object:DateTime 2015-11-26 17:51:43.196000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:43.196000000 Z title: Fig. 14. Engraved horse description: url: "//images.ctfassets.net/xt8ne4gbbocd/3PfHuSbYGcqeo2U4AEKsmM/33a068fa954954fd3b9b446c943e0791/Fig._14._Engraved_horse.jpg" caption: Engraved horse, Eastern Aïr Mountains. 2013,2034.9421 ©TARA/<NAME>. col_link: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3640574&partId=1&searchText=2013,2034.9421&page=1 - sys: id: 6tFSQzFupywiK6aESCgCia created_at: !ruby/object:DateTime 2015-11-26 18:04:56.612000000 Z updated_at: !ruby/object:DateTime 2019-02-21 15:47:26.838000000 Z content_type_id: chapter revision: 2 title_internal: 'Thematic: horse, chapter 11' body: |- In each of these cases, the original symbolic intent of the artists have been lost to time, but with these horse depictions, as with so much African rock art imagery, there is great scope for further future analysis. Particularly intriguing, for example, are the striking stylistic similarities in horse depictions across great distances, such the horse depictions with bi-triangular bodies (see above), or with fishbone-style tails which may be found almost two thousand miles apart in Chad and Mauritania. Whatever the myriad circumstances and significances of the images, it is clear that following its introduction to the continent, the hardy and surefooted desert horse’s usefulness for draught, transport and fighting purposes transformed the societies which used it and gave it a powerful symbolic value. - sys: id: 2P6ERbclfOIcGEgI6e0IUq created_at: !ruby/object:DateTime 2015-11-26 17:59:46.042000000 Z updated_at: !ruby/object:DateTime 2019-02-21 15:45:12.419000000 Z content_type_id: image revision: 2 image: sys: id: 3UXc5NiGTYQcmu2yuU42g created_at: !ruby/object:DateTime 2015-11-26 17:51:43.128000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:43.128000000 Z title: Fig. 15. Painted horse, Terkei description: url: "//images.ctfassets.net/xt8ne4gbbocd/3UXc5NiGTYQcmu2yuU42g/7586f05e83f708ca9d9fca693ae0cd83/Fig._15._Painted_horse__Terkei.jpg" caption: Painted horse, Terkei, En<NAME>, Chad. 2013,2034.6537 © TARA/David Coulson col_link: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3640682&partId=1&searchText=2013,2034.6537&page=1 citations: - sys: id: 32AXGC1EcoSi4KcogoY2qu created_at: !ruby/object:DateTime 2015-11-26 17:51:20.602000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:20.602000000 Z content_type_id: citation revision: 1 citation_line: "<NAME>. & <NAME>. 2000, *The Origins and Development of African Livestock: archaeology, genetics, linguistics and ethnography*. London; New York, NY: UCL Press\n \n<NAME>., <NAME>., <NAME>., 2012. *The Horse: From Arabia to Royal Ascot*. London: British Museum Press\n \nLaw, R., 1980. *The Horse in West African History*. Oxford: Oxford University Press\n \nHachid, M. 2000. *Les Premieres Berbères*. Aix-en-Provence: Edisud\n \n<NAME>. 1952. 'Le cheval et le chameau dans les peintures et gravures rupestres du Sahara', *Bulletin de l'Institut franç ais de l'Afrique noire* 15: 1138-228\n \nOlsen, <NAME>. & Culbertson, C. 2010, *A gift from the desert: the art, history, and culture of the Arabian horse*. Lexington, KY: Kentucky Horse Park\n\n" background_images: - sys: id: 2avgKlHUm8CauWie6sKecA created_at: !ruby/object:DateTime 2015-12-07 18:44:31.346000000 Z updated_at: !ruby/object:DateTime 2015-12-07 18:44:31.346000000 Z title: EAF 141485 description: url: "//images.ctfassets.net/xt8ne4gbbocd/2avgKlHUm8CauWie6sKecA/cf02168ca83c922f27eca33f16e8cc90/EAF_141485.jpg" - sys: id: 1wtaUDwbSk4MiyGiISE6i8 created_at: !ruby/object:DateTime 2015-12-07 18:43:51.804000000 Z updated_at: !ruby/object:DateTime 2015-12-07 18:43:51.804000000 Z title: 01522751 001 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1wtaUDwbSk4MiyGiISE6i8/5918544d0289f9c4b2b4724f4cda7a2d/01522751_001.jpg" - sys: id: 2t4epzwnhiUMcmeK4yIYQC created_at: !ruby/object:DateTime 2015-11-26 17:10:57.025000000 Z updated_at: !ruby/object:DateTime 2015-12-07 20:49:23.897000000 Z content_type_id: thematic revision: 6 title: Gone fishing... slug: gone-fishing lead_image: sys: id: 5O1g77GG9UEIeyWWgoCwOa created_at: !ruby/object:DateTime 2015-11-26 16:33:34.505000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:33:34.505000000 Z title: '2013,2034.4497' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5O1g77GG9UEIeyWWgoCwOa/18b8916dbaa566c488fb1d462f336b88/2013_2034.4497.jpg" chapters: - sys: id: 3FSGABeX9C2aieeekCUc6I created_at: !ruby/object:DateTime 2015-11-26 16:58:39.843000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:58:59.910000000 Z content_type_id: chapter revision: 2 title_internal: 'Thematic: fishing, chapter 1' body: Fishing is an ancient practice in Africa, dating back 100,000 years, when modern humans started moving into coastal environments. The remains of thousands of fish bones and shellfish from sites on the southern African coastline dating to the Middle Stone Age testify to its antiquity. At the same time that human populations in Africa were developing more sophisticated terrestrial hunting technologies, they were also acquiring innovative and productive fishing and riverine hunting skills. Concomitantly, marine shells were being collected to thread on to twine, probably for use as items of personal ornamentation. Archaeological research has shown that aquatic environments have been exploited for both subsistence and cultural purposes for tens of thousands of years. - sys: id: 5rah4C96eWkK6gUgYS2cKI created_at: !ruby/object:DateTime 2015-11-26 16:34:38.217000000 Z updated_at: !ruby/object:DateTime 2018-05-16 17:46:25.921000000 Z content_type_id: image revision: 2 image: sys: id: 5O1g77GG9UEIeyWWgoCwOa created_at: !ruby/object:DateTime 2015-11-26 16:33:34.505000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:33:34.505000000 Z title: '2013,2034.4497' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5O1g77GG9UEIeyWWgoCwOa/18b8916dbaa566c488fb1d462f336b88/2013_2034.4497.jpg" caption: Red outline of a fish swimming right showing dorsal fin and fish scales. A smaller fish superimposes larger fish underneath near the tail. Tassili n'Ajjer, Algeria. 2013,2034.4497 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3602875&partId=1&people=197356&museumno=2013,2034.4497&page=1 - sys: id: 1s82PsQrCsS8C0QQQ0gYie created_at: !ruby/object:DateTime 2015-11-26 16:35:04.493000000 Z updated_at: !ruby/object:DateTime 2018-05-16 17:48:40.438000000 Z content_type_id: image revision: 2 image: sys: id: 3PqImAJY3CeKKkMwqeayoe created_at: !ruby/object:DateTime 2015-11-26 16:34:03.906000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:34:03.906000000 Z title: '2013,2034.5019' description: url: "//images.ctfassets.net/xt8ne4gbbocd/3PqImAJY3CeKKkMwqeayoe/19a4c9ac1890f3aa6e7b6ef761b4373b/2013_2034.5019.jpg" caption: Outline engraving of fish facing right, incised on a sandstone slab beside a riverbed. <NAME>. 2013,2034.5019 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3624043&partId=1&people=197356&museumno=2013,2034.5019&page=1 - sys: id: oie98q7G1MoEw4c6ggEai created_at: !ruby/object:DateTime 2015-11-26 16:35:28.865000000 Z updated_at: !ruby/object:DateTime 2018-05-16 17:48:58.748000000 Z content_type_id: image revision: 2 image: sys: id: 5TVVOzkAlaWKaK4oG2wqq8 created_at: !ruby/object:DateTime 2015-11-26 16:33:50.727000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:33:50.727000000 Z title: '2013,2034.801' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5TVVOzkAlaWKaK4oG2wqq8/d1654d1e9de9bdf1f9a61eca5e81cebd/2013_2034.801.jpg" caption: Painted rock art showing series of dots in vertical lines that converge at top and bottom, possibly in a fish shape, placed in area of water seep on rock face. Afforzighiar, Acacus Mountains, Libya. 2013,2034.801 © David Coulson/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3586292&partId=1&people=197356&museumno=2013,2034.801&page=1 - sys: id: cjcvGndmak60E82YEQmEC created_at: !ruby/object:DateTime 2015-11-26 16:59:31.911000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:59:31.911000000 Z content_type_id: chapter revision: 1 title_internal: 'Thematic: fishing, chapter 2' body: |- We rarely consider the Sahara as the optimum environment for fishing. Seeing painted and engraved images of fish located in these waterless and unfavourable landscapes therefore seems at odds with our present-day knowledge of this vast desert. However, as we have noted before in these project pages (see introductions to Libya and Algeria), water-dependent animals such as crocodile and hippo have regularly been depicted in Saharan rock art, illustrating a once wetter and more fertile landscape. To date, the African rock art image project has catalogued representations of aquatic species in Libya, Algeria and Morocco, depicted with varying degrees of proficiency and ease of identification. This has been an insightful encounter, because it not only informs our thinking about the nature of the environment in the past and the way people were using their available resources, but also allows us to think about the cultural importance of water-based species. The rock art in these places is a glimpse into an aquatic past that is now supported by environmental evidence. In a recent collaborative project mapping ancient watercourses in the Sahara, it has been shown that during the Holocene (a period which started around 11,700 years ago), this now arid landscape was once covered by a dense interconnected river system, as well as large bodies of water known as ‘megalakes’. When these lakes overflowed, they linked catchment areas, resulting in a dense palaeoriver network that allowed water-dependent life (fish, molluscs and amphibians) to migrate and disperse across an extensive landscape. This interlinked waterway of the Sahara formed a single and vast biogeographic area. Perhaps not surprisingly, rock art sites appear to be clustered around inland deltas where resources would have been most plentiful. Across the Sahara, at least twenty-three species of fish have been identified in archaeological deposits from the Holocene, the most common being Tilapia, Catfish, African jewelfish, Silver fish and Nile perch. But can we go as far as to correlate the archaeological record with the rock art to species level? - sys: id: 5J2YaEVcDSk8E8mqsYeYC6 created_at: !ruby/object:DateTime 2015-11-26 16:36:02.168000000 Z updated_at: !ruby/object:DateTime 2018-05-16 17:51:34.767000000 Z content_type_id: image revision: 2 image: sys: id: 62OPN6zwbKOym4YUAKCoAY created_at: !ruby/object:DateTime 2015-11-26 16:33:44.984000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:33:44.984000000 Z title: Fig. 4. African jewelfish description: url: "//images.ctfassets.net/xt8ne4gbbocd/62OPN6zwbKOym4YUAKCoAY/b23a2b5b8d528ba735cf4e91c7a748c9/Fig._4._African_jewelfish.jpg" caption: African jewelfish (Hemichromis bimaculatus). Image ©Zhyla (Wikimedia Commons) col_link: https://commons.wikimedia.org/wiki/File:Hemichromis_bimaculatus1.jpg - sys: id: 4mxD1mNZu8OegCaGC60o8o created_at: !ruby/object:DateTime 2015-11-26 16:36:34.680000000 Z updated_at: !ruby/object:DateTime 2018-05-16 18:02:17.202000000 Z content_type_id: image revision: 3 image: sys: id: oV9yR91U3YSg2McmgeCA2 created_at: !ruby/object:DateTime 2015-11-26 16:33:44.982000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:33:44.982000000 Z title: Fig. 5. Redbelly Tilapia description: url: "//images.ctfassets.net/xt8ne4gbbocd/oV9yR91U3YSg2McmgeCA2/780ac15c52522b76348ecebbd4cc123d/Fig._5._Redbelly_Tilapia.jpg" caption: Redbelly Tilapia (Tilapia zillii). Image © <NAME> (Wikimedia Commons) col_link: https://commons.wikimedia.org/wiki/File%3AFresh_tilapia.jpg - sys: id: gbhjHlWzFCKyeeiUGEkaQ created_at: !ruby/object:DateTime 2015-11-26 17:00:13.905000000 Z updated_at: !ruby/object:DateTime 2018-05-16 17:57:51.334000000 Z content_type_id: chapter revision: 2 title_internal: 'Thematic: fishing, chapter 3' body: Rock art imagery is replete with both very naturalistic representations and also those which are more conceptual or abstract in nature, and the depictions of fish are no exception. While some representations are clearly identifiable as fish, other are more difficult to identify. For example, the image above from Afforzighiar shows vertical red dots on the left of the photograph are arranged in a fish-like shape that converges at the top and bottom. Additionally it has been deliberately placed on a section of the rock face where there is water seepage, blending the art with the natural environment. The dotted pattern is reminiscent of the African jewelfish (*Hemichromis bimaculatus*) or even the Redbelly Tilapia (*Tilapia zillii*), both shown to be species of fish found throughout much of the Sahara during the Holocene. - sys: id: 5XJMMCBGveKKqoIc8kGEQU created_at: !ruby/object:DateTime 2015-11-26 16:37:00.084000000 Z updated_at: !ruby/object:DateTime 2018-05-16 18:04:03.162000000 Z content_type_id: image revision: 3 image: sys: id: 4fQKRSGFIA6OMCe8waOWmM created_at: !ruby/object:DateTime 2015-11-26 16:33:34.492000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:33:34.492000000 Z title: '2013,2034.559' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4fQKRSGFIA6OMCe8waOWmM/0a976c617609964467168ae590f831a8/2013_2034.559.jpg" caption: Five fish engraved on a rock face. <NAME>, Acacus Mountains, Libya. 2013,2034.559 ©<NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3585024&partId=1&people=197356&museumno=2013,2034.559&page=1 - sys: id: 4gUY4mSYnKYk8UIMSGAike created_at: !ruby/object:DateTime 2015-11-26 16:37:27.294000000 Z updated_at: !ruby/object:DateTime 2018-05-16 18:02:43.933000000 Z content_type_id: image revision: 3 image: sys: id: rJLJBELLi0yAYiCuM4SWi created_at: !ruby/object:DateTime 2015-11-26 16:33:40.236000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:33:40.236000000 Z title: Fig. 7. African sharptooth catfish description: url: "//images.ctfassets.net/xt8ne4gbbocd/rJLJBELLi0yAYiCuM4SWi/31fdd8fe74786561592c1d104aa2ab13/Fig._7._African_sharptooth_catfish.jpg" caption: African sharptooth catfish (Clarias gariepinus). Image ©<NAME> (Wie146) (Wikimedia Commons) col_link: https://commons.wikimedia.org/wiki/File%3AClarias_garie_080516_9142_tdp.jpg - sys: id: 1pIt8kfkgAQ6ueEWMSqyAM created_at: !ruby/object:DateTime 2015-11-26 16:37:55.248000000 Z updated_at: !ruby/object:DateTime 2018-05-16 17:59:58.067000000 Z content_type_id: image revision: 2 image: sys: id: 14NfPoZlKIUOoacY8GWQ4c created_at: !ruby/object:DateTime 2015-11-26 16:33:44.971000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:33:44.971000000 Z title: '2013,2034.925' description: url: "//images.ctfassets.net/xt8ne4gbbocd/14NfPoZlKIUOoacY8GWQ4c/88845134e8a0ef3fcf489e93e67f321e/2013_2034.925.jpg" caption: Engraved fish. Affozighiar, Acacus Mountains, Libya 2013,2034.925 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3587559&partId=1&people=197356&museumno=2013,2034.925&page=1 - sys: id: 5Kvn7LZDEcc0iGm0O4u6uY created_at: !ruby/object:DateTime 2015-11-26 17:00:36.225000000 Z updated_at: !ruby/object:DateTime 2018-05-16 18:00:54.782000000 Z content_type_id: chapter revision: 2 title_internal: 'Thematic: fishing, chapter 4' body: Some of the engravings bear close morphological resemblances to Catfish, with even the barbels depicted. Catfish seem to occur more regularly in rock art than other species of fish, possibly due to their physical characteristics. They possess an auxiliary breathing organ which allows them to inhabit extremely de-oxygenated water; in fact, when necessary they can obtain up to 50% of their total oxygen requirements from the air. In some cases they will leave the water and crawl on dry ground to escape drying pools. This capacity to live in very shallow waters and to occupy the liminal spaces between land and water has elevated them to more than a simple food source and given them a place of cultural significance in many African societies. - sys: id: sTBWoIZ2yyuS04mEIYYus created_at: !ruby/object:DateTime 2015-11-26 16:38:21.905000000 Z updated_at: !ruby/object:DateTime 2018-05-16 18:01:22.453000000 Z content_type_id: image revision: 2 image: sys: id: 3nZmrbE5yUEuc2qaWc2Age created_at: !ruby/object:DateTime 2015-11-26 16:33:56.244000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:33:56.244000000 Z title: '2013,2034.5255' description: url: "//images.ctfassets.net/xt8ne4gbbocd/3nZmrbE5yUEuc2qaWc2Age/5bf831c50428a19572df28872a18e3d1/2013_2034.5255.jpg" caption: Engraved fish on a boulder. Ait Ouazik, Draa valley, Morocco. 2013,2034.5255 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3603483&partId=1&people=197356&museumno=2013,2034.5255&page=1 - sys: id: 5RuLsZVAOswgaaKG8CK0AQ created_at: !ruby/object:DateTime 2015-11-26 16:38:50.016000000 Z updated_at: !ruby/object:DateTime 2018-05-16 18:03:15.219000000 Z content_type_id: image revision: 2 image: sys: id: 7M6nZhpTuoUuOOk0oWu8ea created_at: !ruby/object:DateTime 2015-11-26 16:33:44.984000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:33:44.984000000 Z title: Fig. 10. Silver fish description: url: "//images.ctfassets.net/xt8ne4gbbocd/7M6nZhpTuoUuOOk0oWu8ea/04a411cc75ddded8230ee77128e3200a/Fig._10._Silver_fish.jpg" caption: Silver fish (Raiamas senegalensis). Image ©<NAME> (Wikimedia Commons) col_link: https://commons.wikimedia.org/wiki/File%3ACameroon2011_3_(1)_(7003774697).jpg - sys: id: 3SIbv3l2WQqe4Wa08Ew6cI created_at: !ruby/object:DateTime 2015-11-26 17:00:55.256000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:00:55.256000000 Z content_type_id: chapter revision: 1 title_internal: 'Thematic: fishing, chapter 5' body: In arid ecosystems, bodies of water are characterised by daily and seasonal fluctuations in water temperature, evaporation and other natural phenomena, and some fish species have adapted well to cope with these extreme changes in water chemistry. Catfish and Tilapia in particular are able to survive high salinity, which occurs through evaporation, while Redbelly Tilapia can also tolerate temperatures above 35° C. Both Sharptooth Catfish and Tilapia are floodplain dwellers and possess the ability to live and spawn in shallow waters, making them easily susceptible to predation. Catfish spines were also used to decorate Saharan pottery with dotted wavy-line patterns. These biological characteristics, which meant they could be easily hunted, may explain their frequent depiction in rock art. Perhaps their value was also reinforced by their being (possibly) the last fish species to survive once aridification had taken hold in the Sahara. - sys: id: 20MArnOyXuuIgo4g642QQa created_at: !ruby/object:DateTime 2015-11-26 17:01:46.522000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:01:46.522000000 Z content_type_id: chapter revision: 1 title: Fishing title_internal: 'Thematic: fishing, chapter 6' body: Fish are likely to have been caught in a variety of ways, but in the Sahara the most common technique was to use barbed bone point and/or fish hook technology, with the former being the most archaeologically visible. Barbed points may either be fixed – that is permanently attached to a spear or arrow shaft – or used as ‘harpoons’, when they separate from a shaft on impact and remain attached by a line. Barbed points can actually be used to catch multiple types of prey, but the primary use across Africa was for fish. - sys: id: 1bwCettQ98qY2wEyiQMOmU created_at: !ruby/object:DateTime 2015-11-26 16:39:23.290000000 Z updated_at: !ruby/object:DateTime 2019-02-21 14:59:03.644000000 Z content_type_id: image revision: 3 image: sys: id: 4cgsOBoxReGOAiCqw2UYM8 created_at: !ruby/object:DateTime 2015-11-26 16:33:40.242000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:33:40.242000000 Z title: Fig. 11. Bone point from Katanda description: url: "//images.ctfassets.net/xt8ne4gbbocd/4cgsOBoxReGOAiCqw2UYM8/e84d40b791670fc04e8b47d312248bd5/Fig._11._Bone_point_from_Katanda.jpg" caption: Bone point from Katanda, DRC, 80,000-90,000 BP. Image ©Human Origins Program, Smithsonian Institution col_link: hhttp://humanorigins.si.edu/evidence/behavior/getting-food/katanda-bone-harpoon-point - sys: id: 159mLyHGvyC4ccwOQMyQIs created_at: !ruby/object:DateTime 2015-11-26 17:02:05.585000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:02:05.585000000 Z content_type_id: chapter revision: 1 title_internal: 'Thematic: fishing, chapter 7' body: Chronologically, the earliest barbed bone point records are from Katanda in the Upper Semliki Valley in modern-day Democratic Republic of the Congo, dating to 80,000 – 90,000 years ago. Here people were catching Catfish weighing up to 68 kg (150 lb), sufficient to feed eighty people for two days. Research has noted the distribution of barbed bone points across the Sahara, and the correlation between these locations and the distribution of species requiring deep water. It is clear that there is continuity in sophisticated fishing technology and practice that has lasted tens of thousands of years. - sys: id: 2IWFdXQZl6WwuCgA6oUa8u created_at: !ruby/object:DateTime 2015-11-26 17:02:48.620000000 Z updated_at: !ruby/object:DateTime 2018-05-17 10:26:57.354000000 Z content_type_id: chapter revision: 2 title: Other aquatic species title_internal: 'Thematic: fishing, chapter 8' body: Other aquatic species are more difficult to identify and are much rarer. For example, the image below has been interpreted as a jelly-fish like creature. However, by manipulating the colour and lighting, the image is a little clearer and appears to share morphological characteristics, such as the rounded carapace and small flippers, with a turtle rather than a jellyfish. Furthermore, we know that softshell turtles (*Trionyx triunguis*) have been found in archaeological deposits in the Sahara dating to the Holocene. The vertical and wavy strands hanging down underneath could represent the pattern made in the sand by turtles when walking rather than being the tendrils of a jellyfish. In addition, the image from Wadi Tafak below appears to resemble a snail, and is consistent with what we know about the Capsian culture who inhabited modern Tunisia, Algeria, and parts of Libya during the early Holocene (10000–6000 BC). Their distinguishing culinary feature was a fondness for escargots – edible land snails. - sys: id: 5j7XInUteECEA6cSE48k4A created_at: !ruby/object:DateTime 2015-11-26 16:39:52.787000000 Z updated_at: !ruby/object:DateTime 2018-05-17 10:34:45.084000000 Z content_type_id: image revision: 2 image: sys: id: 7pDQ1Q7cm4u4KKkayeugGY created_at: !ruby/object:DateTime 2015-11-26 16:33:44.977000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:33:44.977000000 Z title: '2013,2034.4298' description: url: "//images.ctfassets.net/xt8ne4gbbocd/7pDQ1Q7cm4u4KKkayeugGY/094c9283ceeded55f016eafbc00e131c/2013_2034.4298.jpg" caption: Painting of a turtle (digitally manipulated) from Jabbaren, Algeria. 2013,2034.4298 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3601635&partId=1&people=197356&museumno=2013,2034.4298&page=1 - sys: id: 2pq6oldgxGsq48iIUsKEyg created_at: !ruby/object:DateTime 2015-11-26 16:40:52.658000000 Z updated_at: !ruby/object:DateTime 2018-05-17 10:35:17.649000000 Z content_type_id: image revision: 2 image: sys: id: 6k5J6VbwZOq2yg86Y4GsEc created_at: !ruby/object:DateTime 2015-11-26 16:33:40.222000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:33:40.222000000 Z title: '2013,2034.1167' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6k5J6VbwZOq2yg86Y4GsEc/3db2c57978de4879d82e7b04833d4564/2013_2034.1167.jpg" caption: Painting of a snail from Wadi Tafak, Acacus Mountains, Libya. 2013,2034.1167 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3593787&partId=1&people=197356&museumno=2013,2034.1167&page=1 - sys: id: k7ChxGbsyc2iSaOc0k62C created_at: !ruby/object:DateTime 2015-11-26 17:03:15.438000000 Z updated_at: !ruby/object:DateTime 2018-05-17 10:50:37.252000000 Z content_type_id: chapter revision: 2 title: Case study – Gobero title_internal: 'Thematic: fishing, chapter 9' body: A recently excavated cemetery site called Gobero (Sereno *et al.* 2008), situated on the western edge of the Ténéré desert in Niger, provides a uniquely preserved record of human occupation in the Sahara during the Holocene and puts into context some of the examples of rock art we have looked at here. Pollen analysis has indicated that during the Holocene, Gobero was situated in an open savannah landscape of grasses and sedges, with fig trees and tamarisk, where permanent water and marshy habitats were present. - sys: id: 7D5HIm20CW4WMy0IgyQQOu created_at: !ruby/object:DateTime 2015-11-26 16:41:18.798000000 Z updated_at: !ruby/object:DateTime 2018-05-17 10:52:51.807000000 Z content_type_id: image revision: 2 image: sys: id: 5ZHSZA9fHOyAu8kaMceGOa created_at: !ruby/object:DateTime 2015-11-26 16:33:40.277000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:33:40.277000000 Z title: Fig. 14. Aerial view of Gobero description: url: "//images.ctfassets.net/xt8ne4gbbocd/5ZHSZA9fHOyAu8kaMceGOa/a546de3d31a679d75b67e4e2f4e41c68/Fig._14._Aerial_view_of_Gobero.jpg" caption: Aerial view of Gobero archaeological site (from Sereno et al. 2008). col_link: http://journals.plos.org/plosone/article?id=10.1371/journal.pone.0002995 - sys: id: 1wHHAMslowaeSOAWaue4Om created_at: !ruby/object:DateTime 2015-11-26 17:03:47.119000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:03:47.119000000 Z content_type_id: chapter revision: 1 title_internal: 'Thematic: fishing, chapter 10' body: |- Approximately 200 burials, ranging over a 5000-year period, were found on the edge of an ancient lake. Grave goods include bones or tusks from wild fauna, ceramics, lithic projectile points, and bone, ivory and shell ornaments. One adult male was buried in a recumbent pose seated on the carapace of a mud turtle. Microliths, bone harpoon points and hooks, and ceramics with dotted wavy-line and zigzag impressed motifs were found in the burial fill, in an associated midden area, and in nearby paleolake deposits. Nile perch (*Lates niloticus*), large catfish, and tilapia dominate the midden fauna, which also includes bones and teeth from hippos, several bovids, small carnivores, softshell turtles and crocodiles. The early Holocene occupants at Gobero (7700–6300 BC.) were largely sedentary hunter-fisher-gatherers with lakeside funerary sites. Across the ‘green’ Sahara, Catfish, Tilapia and turtles played important roles socially, economically and culturally. We can see this most explicitly in the burial within a turtle carapace in Gobero, but the representation of aquatic animals in rock art is a significant testament to their value. citations: - sys: id: 6JNu3sK5DGaUyWo4omoc2M created_at: !ruby/object:DateTime 2015-11-26 16:58:14.227000000 Z updated_at: !ruby/object:DateTime 2019-02-21 15:03:53.071000000 Z content_type_id: citation revision: 2 citation_line: '<NAME>., <NAME>., <NAME>., <NAME>., Saliège J-F., et al. 2008. *Lakeside Cemeteries in the Sahara: 5000 Years of Holocene Population and Environmental Change*. PLoS ONE 3(8): [https://doi.org/10.1371/journal.pone.0002995](https://doi.org/10.1371/journal.pone.0002995)' background_images: - sys: id: 1MzxjY9CecYwee0IWcCQqe created_at: !ruby/object:DateTime 2015-12-07 18:22:52.418000000 Z updated_at: !ruby/object:DateTime 2015-12-07 18:22:52.418000000 Z title: EAF 141260 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1MzxjY9CecYwee0IWcCQqe/61da964c9b38a509ca9f602f7ac5747c/EAF_141260.jpg" - sys: id: BdGy2n8Krecyks0s4oe8e created_at: !ruby/object:DateTime 2015-12-07 18:22:52.407000000 Z updated_at: !ruby/object:DateTime 2015-12-07 18:22:52.407000000 Z title: 01557634 001 description: url: "//images.ctfassets.net/xt8ne4gbbocd/BdGy2n8Krecyks0s4oe8e/7130c75aba21829540524182a5350677/01557634_001.jpg" - sys: id: 1KwPIcPzMga0YWq8ogEyCO created_at: !ruby/object:DateTime 2015-11-26 16:25:56.681000000 Z updated_at: !ruby/object:DateTime 2015-12-07 20:49:15.151000000 Z content_type_id: thematic revision: 5 title: 'Sailors on sandy seas: camels in Saharan rock art' slug: camels-in-saharan-rock-art lead_image: sys: id: 46X3vtG1faouSYYws0Aywu created_at: !ruby/object:DateTime 2015-11-26 16:07:51.521000000 Z updated_at: !ruby/object:DateTime 2019-02-12 02:30:35.572000000 Z title: View of camel salt caravan crossing the Ténéré desert. Niger. ©David Coulson/TARA description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3652083&partId=1&searchText=2013,2034.10379&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/46X3vtG1faouSYYws0Aywu/6ff8cc3f26c918c81157746e1b2b3131/Fig._1._Camel.jpg" chapters: - sys: id: 1Q7xHD856UsISuceGegaqI created_at: !ruby/object:DateTime 2015-11-26 16:19:29.618000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:19:29.618000000 Z content_type_id: chapter revision: 1 title_internal: 'Camels: thematic, chapter 1' body: 'If we were to choose a defining image for the Sahara Desert, it would probably depict an endless sea of yellow dunes under a blue sky and, off in the distance, a line of long-legged, humped animals whose profiles have become synonymous with deserts: the one-humped camel (or dromedary). Since its domestication, the camel’s resistance to heat and its ability to survive with small amounts of water and a diet of desert vegetation have made it a key animal for inhabitants of the Sahara, deeply bound to their economy, material culture and lifestyle.' - sys: id: 4p7wUbC6FyiEYsm8ukI0ES created_at: !ruby/object:DateTime 2015-11-26 16:09:23.136000000 Z updated_at: !ruby/object:DateTime 2019-02-12 02:30:19.986000000 Z content_type_id: image revision: 3 image: sys: id: 46X3vtG1faouSYYws0Aywu created_at: !ruby/object:DateTime 2015-11-26 16:07:51.521000000 Z updated_at: !ruby/object:DateTime 2019-02-12 02:30:35.572000000 Z title: View of camel salt caravan crossing the Ténéré desert. Niger. ©David Coulson/TARA description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3652083&partId=1&searchText=2013,2034.10379&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/46X3vtG1faouSYYws0Aywu/6ff8cc3f26c918c81157746e1b2b3131/Fig._1._Camel.jpg" caption: Camel salt caravan crossing the Ténéré desert in Niger. 2013,2034.10487 ©<NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3652360&partId=1&searchText=2013,2034.10487&page=1 - sys: id: 1LsXHHPAZaIoUksC2US08G created_at: !ruby/object:DateTime 2015-11-26 16:19:46.820000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:19:46.820000000 Z content_type_id: chapter revision: 1 title_internal: 'Camels: thematic, chapter 2' body: Yet, surprising as it seems, the camel is a relative newcomer to the Sahara – at least when compared to other domestic animals such as cattle, sheep, horses and donkeys. Although the process is not yet fully known, camels were domesticated in the Arabian Peninsula around the third millennium BC, and spread from there to the Middle East, North Africa and Somalia from the 1st century AD onwards. The steps of this process from Egypt to the Atlantic Ocean have been documented through many different historical sources, from Roman texts to sculptures or coins, but it is especially relevant in Saharan rock art, where camels became so abundant that they have given their name to a whole period. The depictions of camels provide an incredible amount of information about the life, culture and economy of the Berber and other nomadic communities from the beginnings of the Christian era to the Muslim conquest in the late years of the 7th century. - sys: id: j3q9XWFlMOMSK6kG2UWiG created_at: !ruby/object:DateTime 2015-11-26 16:10:00.029000000 Z updated_at: !ruby/object:DateTime 2018-05-17 14:21:07.255000000 Z content_type_id: image revision: 2 image: sys: id: 6afrRs4VLUS4iEG0iwEoua created_at: !ruby/object:DateTime 2015-11-26 16:07:34.273000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:34.273000000 Z title: EA26664 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6afrRs4VLUS4iEG0iwEoua/e00bb3c81c6c9b44b5e224f5a8ce33a2/EA26664.jpg" caption: Roman terracotta camel with harness, 1st – 3rd century AD, Egypt. British Museum 1891,0403.31 © Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?museumno=1891,0430.31&objectId=118725&partId=1 - sys: id: NxdAnazJaUkeMuyoSOy68 created_at: !ruby/object:DateTime 2015-11-26 16:20:03.948000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:20:03.948000000 Z content_type_id: chapter revision: 1 title_internal: 'Camels: thematic, chapter 3' body: 'What is it that makes camels so suited to deserts? It is not only their ability to transform the fat stored in their hump into water and energy, or their capacity to eat thorny bushes, acacia leaves and even fish and bones. Camels are also able to avoid perspiration by manipulating their core temperature, enduring fluctuations of up to six degrees that could be fatal for other mammals. They rehydrate very quickly, and some of their physical features (nostrils, eyebrows) have adapted to increase water conservation and protect the animals from dust and sand. All these capacities make camels uniquely suited to hot climates: in temperatures of 30-40 °C, they can spend up to 15 days without water. In addition, they are large animals, able to carry loads of up to 300kg, over long journeys across harsh environments. The pads on their feet have evolved so as to prevent them from sinking into the sand. It is not surprising that dromedaries are considered the ‘ships of the desert’, transporting people, commodities and goods through the vast territories of the Sahara.' - sys: id: 2KjIpAzb9Kw4O82Yi6kg2y created_at: !ruby/object:DateTime 2015-11-26 16:10:36.039000000 Z updated_at: !ruby/object:DateTime 2018-05-17 14:39:34.523000000 Z content_type_id: image revision: 2 image: sys: id: 6iaMmNK91YOU00S4gcgi6W created_at: !ruby/object:DateTime 2015-11-26 16:07:51.477000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:51.477000000 Z title: Af1937,0105.16 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6iaMmNK91YOU00S4gcgi6W/4a850695b34c1766d1ee5a06f61f2b36/Af1937_0105.16.jpg" caption: Clay female dromedary (possibly a toy), Somalia. British Museum Af1937,0105.16 © Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?assetId=1088379&objectId=590967&partId=1 - sys: id: 12mIwQ0wG2qWasw4wKQkO0 created_at: !ruby/object:DateTime 2015-11-26 16:11:00.578000000 Z updated_at: !ruby/object:DateTime 2018-05-17 14:45:29.810000000 Z content_type_id: image revision: 2 image: sys: id: 4jTR7LKYv6IiY8wkc2CIum created_at: !ruby/object:DateTime 2015-11-26 16:07:51.505000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:51.505000000 Z title: Fig. 4. Man description: url: "//images.ctfassets.net/xt8ne4gbbocd/4jTR7LKYv6IiY8wkc2CIum/3dbaa11c18703b33840a6cda2c2517f2/Fig._4._Man.jpg" caption: Man leading a camel train through the Ennedi Plateau, Chad. 2013,2034.6134 ©<NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3636989&partId=1&searchText=2013,2034.6134&page=1 - sys: id: 6UIdhB0rYsSQikE8Yom4G6 created_at: !ruby/object:DateTime 2015-11-26 16:20:29.219000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:20:29.219000000 Z content_type_id: chapter revision: 1 title_internal: 'Camels: thematic, chapter 4' body: As mentioned previously, camels came from the Arabian Peninsula through Egypt, where bone remains have been dated to the early 1st millennium BC. However, it took hundreds of years to move into the rest of North Africa due to the River Nile, which represented a major geographical and climatic barrier for these animals. The expansion began around the beginning of the Christian era, and probably took place both along the Mediterranean Sea and through the south of the Sahara. At this stage, it appears to have been very rapid, and during the following centuries camels became a key element in the North African societies. They were used mainly for riding, but also for transporting heavy goods and even for ploughing. Their milk, hair and meat were also used, improving the range of resources available to their herders. However, it seems that the large caravans that crossed the desert searching for gold, ivory or slaves came later, when the Muslim conquest of North Africa favoured the establishment of vast trade networks with the Sahel, the semi-arid region that lies south of the Sahara. - sys: id: YLb3uCAWcKm288oak4ukS created_at: !ruby/object:DateTime 2015-11-26 16:11:46.395000000 Z updated_at: !ruby/object:DateTime 2018-05-17 14:46:15.751000000 Z content_type_id: image revision: 2 image: sys: id: 5aJ9wYpcHe6SImauCSGoM8 created_at: !ruby/object:DateTime 2015-11-26 16:06:48.336000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:06:48.336000000 Z title: '1923,0401.850' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5aJ9wYpcHe6SImauCSGoM8/74efd37612ec798fd91c2a46c65587f7/1923_0401.850.jpg" caption: Glass paste gem imitating beryl, engraved with a short, bearded man leading a camel with a pack on its hump. Roman Empire, 1st – 3rd century AD. 1923,0401.850 ©Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=434529&partId=1&museumno=1923,0401.850&page=1 - sys: id: 3uitqbkcY8s8GCcicKkcI4 created_at: !ruby/object:DateTime 2015-11-26 16:20:45.582000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:20:45.582000000 Z content_type_id: chapter revision: 1 title_internal: 'Camels: thematic, chapter 5' body: Rock art can be extremely helpful in learning about the different ways in which camels were used in the first millennium AD. Images of camels are found in both engravings and paintings in red, white or – on rare occasions – black; sometimes the colours are combined to achieve a more impressive effect. They usually appear in groups, alongside humans, cattle and, occasionally, dogs and horses. Sometimes, even palm trees and houses are included to represent the oases where the animals were watered. Several of the scenes show female camels herded or taking care of their calves, showing the importance of camel-herding and breeding for the Libyan-Berber communities. - sys: id: 5OWosKxtUASWIO6IUii0EW created_at: !ruby/object:DateTime 2015-11-26 16:12:17.552000000 Z updated_at: !ruby/object:DateTime 2018-05-17 15:11:49.775000000 Z content_type_id: image revision: 2 image: sys: id: 3mY7XFQW6QY6KekSQm6SIu created_at: !ruby/object:DateTime 2015-11-26 16:06:48.343000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:06:48.343000000 Z title: '2013,2034.383' description: url: "//images.ctfassets.net/xt8ne4gbbocd/3mY7XFQW6QY6KekSQm6SIu/85c0b70ab40ead396c695fe493081801/2013_2034.383.jpg" caption: Painted scene of a village, depicting a herd or caravan of camels guided by riders and dogs. <NAME>, Acacus Mountains, Libya. 2013,2034.383 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3579914&partId=1&museumno=2013,2034.383&page=1 - sys: id: 2Ocb7A3ig8OOkc2AAQIEmo created_at: !ruby/object:DateTime 2015-11-26 16:12:48.147000000 Z updated_at: !ruby/object:DateTime 2018-05-17 15:12:22.249000000 Z content_type_id: image revision: 2 image: sys: id: 2xR2nZml7mQAse8CgckCa created_at: !ruby/object:DateTime 2015-11-26 16:07:51.480000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:51.480000000 Z title: '2013,2034.5117' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2xR2nZml7mQAse8CgckCa/984e95b65ebdc647949d656cb08c0fc9/2013_2034.5117.jpg" caption: Engravings of a female camel with calves. <NAME>. 2013,2034.5117 © David Coulson/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3624292&partId=1&museumno=2013,2034.5117&page=1 - sys: id: 4iTHcZ38wwSyGK8UIqY2yQ created_at: !ruby/object:DateTime 2015-11-26 16:13:13.897000000 Z updated_at: !ruby/object:DateTime 2018-05-17 15:31:09.339000000 Z content_type_id: image revision: 2 image: sys: id: 1ecCbVeHUGa2CsYoYSQ4Sm created_at: !ruby/object:DateTime 2015-11-26 16:07:34.241000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:34.241000000 Z title: Fig. 8. Painted description: url: "//images.ctfassets.net/xt8ne4gbbocd/1ecCbVeHUGa2CsYoYSQ4Sm/21b2aebd215d0691482411608ad5682f/Fig._8._Painted.jpg" caption: " Painted scene of Libyan-Berber warriors riding camels, accompanied by infantry and cavalrymen. Kozen Pass, Chad. 2013,2034.7295 © David Coulson/TARA" col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3655154&partId=1&searchText=2013,2034.7295&page=1 - sys: id: 2zqiJv33OUM2eEMIK2042i created_at: !ruby/object:DateTime 2015-11-26 16:21:08.068000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:21:08.068000000 Z content_type_id: chapter revision: 1 title_internal: 'Camels: thematic, chapter 6' body: |- That camels were used to transport goods is obvious, and depictions of long lines of animals are common, sometimes with saddles on which to place the packs and ropes to tie the animals together. However, if rock art depictions are some indication of camel use, it seems that until the Muslim conquest the main function of one-humped camels was as mounts, often linked to war. The Sahara desert contains dozens of astonishingly detailed images of warriors riding camels, armed with spears, long swords and shields, sometimes accompanied by infantry soldiers and horsemen. Although camels are not as good as horses for use as war mounts (they are too tall and make insecure platforms for shooting arrows), they were undoubtedly very useful in raids – the most common type of war activity in the desert – as well as being a symbol of prestige, wealth and authority among the desert warriors, much as they still are today. Moreover, the extraordinary detail of some of the rock art paintings has provided inestimable help in understanding how (and why) camels were ridden in the 1st millennium AD. Unlike horses, donkeys or mules, one-humped camels present a major problem for riders: where to put the saddle. Although it might be assumed that the saddle should be placed over the hump, they can, in fact, also be positioned behind or in front of the hump, depending on the activity. It seems that the first saddles were placed behind the hump, but that position was unsuitable for fighting, quite uncomfortable, and unstable. Subsequently, a new saddle was invented in North Arabia around the 5th century BC: a framework of wood that rested over the hump and provided a stable platform on which to ride and fight more effectively. The North Arabian saddle led to a revolution in the domestication of one-humped camels, allowed a faster expansion of the use of these animals, and it is probably still the most used type of saddle today. - sys: id: 6dOm7ewqmA6oaM4cK4cy8c created_at: !ruby/object:DateTime 2015-11-26 16:14:25.900000000 Z updated_at: !ruby/object:DateTime 2018-05-17 15:31:33.078000000 Z content_type_id: image revision: 2 image: sys: id: 5qXuQrcnUQKm0qCqoCkuGI created_at: !ruby/object:DateTime 2015-11-26 16:06:48.345000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:06:48.345000000 Z title: As1974,29.17 description: url: "//images.ctfassets.net/xt8ne4gbbocd/5qXuQrcnUQKm0qCqoCkuGI/2b279eff2a6f42121ab0f6519d694a92/As1974_29.17.jpg" caption: North Arabian-style saddle, with a wooden framework designed to be put around the hump. Jordan. British Museum As1974,29.17 © Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3320111&partId=1&object=23696&page=1 - sys: id: 5jE9BeKCBUEK8Igg8kCkUO created_at: !ruby/object:DateTime 2015-11-26 16:21:27.156000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:21:27.156000000 Z content_type_id: chapter revision: 1 title_internal: 'Camels: thematic, chapter 7' body: 'Although North Arabian saddles are found throughout North Africa and are often depicted in rock art paintings, at some point a new kind of saddle was designed in North Africa: one placed in front of the hump, with the weight over the shoulders of the camel. This type of shoulder saddle allows the rider to control the camel with the feet and legs, thus improving the ride. Moreover, the rider is seated in a lower position and thus needs shorter spears and swords that can be brandished more easily, making warriors more efficient. This new kind of saddle, which is still used throughout North Africa today, appears only in the western half of the Sahara and is well represented in the rock art of Algeria, Niger and Mauritania. And it is not only saddles that are recognizable in Saharan rock art: harnesses, reins, whips or blankets are identifiable in the paintings and show astonishing similarities to those still used today by desert peoples.' - sys: id: 6yZaDQMr1Sc0sWgOG6MGQ8 created_at: !ruby/object:DateTime 2015-11-26 16:14:46.560000000 Z updated_at: !ruby/object:DateTime 2018-05-17 15:33:25.754000000 Z content_type_id: image revision: 2 image: sys: id: 40zIycUaTuIG06mgyaE20K created_at: !ruby/object:DateTime 2015-11-26 16:07:51.466000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:51.466000000 Z title: Fig. 10. Painting description: url: "//images.ctfassets.net/xt8ne4gbbocd/40zIycUaTuIG06mgyaE20K/1736927ffb5e2fc71d1f1ab04310a73f/Fig._10._Painting.jpg" caption: Painting of rider on a one-humped camel. Note the North Arabian saddle on the hump, similar to the example from Jordan above. Terkei, Ennedi plateau, Chad. 2013,2034.6568 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3640623&partId=1&searchText=2013,2034.6568&page=1 - sys: id: 5jHyVlfWXugI2acowekUGg created_at: !ruby/object:DateTime 2015-11-26 16:15:13.926000000 Z updated_at: !ruby/object:DateTime 2018-05-17 15:36:07.603000000 Z content_type_id: image revision: 2 image: sys: id: 6EvwTsiMO4qoiIY4gGCgIK created_at: !ruby/object:DateTime 2015-11-26 16:07:34.249000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:34.249000000 Z title: '2013,2034.4471' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6EvwTsiMO4qoiIY4gGCgIK/1db47ae083ff605b9533898d9d9fb10d/2013_2034.4471.jpg" caption: Camel-rider using a North African saddle (in front of the hump), surrounded by warriors with spears and swords, with Libyan-Berber graffiti. T<NAME>, Tassili, Algeria. 2013,2034.4471 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3602860&partId=1&museumno=2013,2034.4471&page=1 - sys: id: 57goC8PzUs6G4UqeG0AgmW created_at: !ruby/object:DateTime 2015-11-26 16:16:51.920000000 Z updated_at: !ruby/object:DateTime 2019-02-12 02:33:53.275000000 Z content_type_id: image revision: 3 image: sys: id: 5JDO7LrdKMcSEOMEG8qsS8 created_at: !ruby/object:DateTime 2015-11-26 16:07:34.250000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:34.250000000 Z title: Fig. 12. Tuaregs description: url: "//images.ctfassets.net/xt8ne4gbbocd/5JDO7LrdKMcSEOMEG8qsS8/76cbecd637724d549db8a7a101553280/Fig._12._Tuaregs.jpg" caption: Tuaregs at <NAME>, an annual meeting of desert peoples. Note the saddles in front of the hump and the camels' harnesses, similar to the rock paintings above such as the image from Terkei. Ingal, Northern Niger. 2013,2034.10523 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3652377&partId=1&searchText=2013,2034.10523&page=1 - sys: id: 3QPr46gQP6sQWswuSA2wog created_at: !ruby/object:DateTime 2015-11-26 16:21:50.767000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:21:50.767000000 Z content_type_id: chapter revision: 1 title_internal: 'Camels: thematic, chapter 8' body: Since their introduction to the Sahara during the first centuries of the Christian era, camels have become indispensable for desert communities, providing a method of transport for people and commodities, but also for their milk, meat and hair for weaving. They allowed the improvement of wide cultural and economic networks, transforming the Sahara into a key node linking the Mediterranean Sea with Sub-Saharan Africa. A symbol of wealth and prestige, the Libyan-Berber peoples recognized camels’ importance and expressed it through paintings and engravings across the desert, leaving a wonderful document of their societies. The painted images of camel-riders crossing the desert not only have an evocative presence, they are also perfect snapshots of a history that started two thousand years ago and seems as eternal as the Sahara. - sys: id: 54fiYzKXEQw0ggSyo0mk44 created_at: !ruby/object:DateTime 2015-11-26 16:17:13.884000000 Z updated_at: !ruby/object:DateTime 2018-05-17 16:01:13.379000000 Z content_type_id: image revision: 2 image: sys: id: 3idPZkkIKAOWCiKouQ8c8i created_at: !ruby/object:DateTime 2015-11-26 16:07:34.244000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:34.244000000 Z title: Fig. 13. Camel-riders description: url: "//images.ctfassets.net/xt8ne4gbbocd/3idPZkkIKAOWCiKouQ8c8i/4527b1eebe112ef9c38da1026e7540b3/Fig._13._Camel-riders.jpg" caption: Camel-riders galloping. Butress cave, <NAME>, Chad. 2013,2034.6077 ©<NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3637992&partId=1&searchText=2013,2034.6077&page=1 - sys: id: 1ymik3z5wMUEway6omqKQy created_at: !ruby/object:DateTime 2015-11-26 16:17:32.501000000 Z updated_at: !ruby/object:DateTime 2018-05-17 16:02:41.679000000 Z content_type_id: image revision: 2 image: sys: id: 4Y85f5QkVGQiuYEaA2OSUC created_at: !ruby/object:DateTime 2015-11-26 16:07:06.194000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:06.194000000 Z title: Fig. 14. Tuareg description: url: "//images.ctfassets.net/xt8ne4gbbocd/4Y85f5QkVGQiuYEaA2OSUC/4fbca027ed170b221daefdff0ae7d754/Fig._14._Tuareg.jpg" caption: Tuareg rider galloping at the Cure Salee meeting. Ingal, northern Niger. 2013,2034.10528 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3652371&partId=1&searchText=2013,2034.10528&page=1 background_images: - sys: id: 3mhr7uvrpesmaUeI4Aiwau created_at: !ruby/object:DateTime 2015-12-07 18:13:48.396000000 Z updated_at: !ruby/object:DateTime 2015-12-07 18:13:48.396000000 Z title: CHAENP0340003 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3mhr7uvrpesmaUeI4Aiwau/65c691f09cd60bb7aa08457e18eaa624/CHAENP0340003_1_.JPG" - sys: id: BPzulf3QNqMC4Iqs4EoCG created_at: !ruby/object:DateTime 2015-12-07 18:13:31.094000000 Z updated_at: !ruby/object:DateTime 2015-12-07 18:13:31.094000000 Z title: CHAENP0340001 description: url: "//images.ctfassets.net/xt8ne4gbbocd/BPzulf3QNqMC4Iqs4EoCG/356b921099bfccf59008b69060d20d75/CHAENP0340001_1_.JPG" - sys: id: 1hw0sVC0XOUA4AsiG4AA0q created_at: !ruby/object:DateTime 2017-11-23 11:49:41.362000000 Z updated_at: !ruby/object:DateTime 2017-11-23 11:49:41.362000000 Z content_type_id: thematic revision: 1 title: 'Introduction to rock art in northern Africa ' slug: rock-art-in-northern-africa lead_image: sys: id: 1fzfpavYuGaOKaAM2ko6es created_at: !ruby/object:DateTime 2015-11-26 15:53:30.004000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:53:30.004000000 Z title: '2013,2034.3840' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1fzfpavYuGaOKaAM2ko6es/f1e27e311dca40ce58657e5e88cb8526/2013_2034.3840.jpg" chapters: - sys: id: axu12ftQUoS04AQkcSWYI created_at: !ruby/object:DateTime 2015-11-26 15:58:10.885000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:58:10.885000000 Z content_type_id: chapter revision: 1 title: title_internal: 'North Africa: regional, chapter 1' body: 'The Sahara is the largest non-polar desert in the world, covering almost 8,600,000 km² and comprising most of northern Africa, from the Red Sea to the Atlantic Ocean. Although it is considered a distinct entity, it is composed of a variety of geographical regions and environments, including sand seas, hammadas (stone deserts), seasonal watercourses, oases, mountain ranges and rocky plains. Rock art is found throughout this area, principally in the desert mountain and hill ranges, where stone ''canvas'' is abundant: the highlands of Adrar in Mauritania and Adrar des Ifoghas in Mali, the Atlas Mountains of Morocco and Algeria, the Tassili n’Ajjer and Ahaggar Mountains in Algeria, the mountainous areas of Tadrart Acacus and Messak in Libya, the Aïr Mountains of Nigeria, the Ennedi Plateau and Tibesti Mountains in Chad, the Gilf Kebir plateau of Egypt and Sudan, as well as the length of the Nile Valley.' - sys: id: 4DelCmwI7mQ4MC2WcuAskq created_at: !ruby/object:DateTime 2015-11-26 15:54:19.234000000 Z updated_at: !ruby/object:DateTime 2016-12-22 10:12:21.657000000 Z content_type_id: image revision: 2 image: sys: id: 1fzfpavYuGaOKaAM2ko6es created_at: !ruby/object:DateTime 2015-11-26 15:53:30.004000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:53:30.004000000 Z title: '2013,2034.3840' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1fzfpavYuGaOKaAM2ko6es/f1e27e311dca40ce58657e5e88cb8526/2013_2034.3840.jpg" caption: Bubalus Period engraving. Pelorovis Antiquus, <NAME>ous, Libya. 2013,2034.3840 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3593438&partId=1&images=true&people=197356&museumno=2013,2034.3840&page=1 - sys: id: 2XmfdPdXW0Y4cy6k4O4caO created_at: !ruby/object:DateTime 2015-11-26 15:58:31.891000000 Z updated_at: !ruby/object:DateTime 2016-10-17 13:40:03.509000000 Z content_type_id: chapter revision: 3 title: Types of rock art and distribution title_internal: 'North Africa: regional, chapter 2' body: |+ Although the styles and subjects of north African rock art vary, there are commonalities: images are most often figurative and frequently depict animals, both wild and domestic. There are also many images of human figures, sometimes with accessories such as recognisable weaponry or clothing. These may be painted or engraved, with frequent occurrences of both, at times in the same context. Engravings are generally more common, although this may simply be a preservation bias due to their greater durability. The physical context of rock art sites varies depending on geographical and topographical factors – for example, Moroccan rock engravings are often found on open rocky outcrops, while Tunisia’s Djebibina rock art sites have all been found in rock shelters. Rock art in the vast and harsh environments of the Sahara is often inaccessible and hard to find, and there is probably a great deal of rock art that is yet to be seen by archaeologists; what is known has mostly been documented within the last century. - sys: id: 2HqgiB8BAkqGi4uwao68Ci created_at: !ruby/object:DateTime 2016-10-17 13:41:30.844000000 Z updated_at: !ruby/object:DateTime 2016-10-17 13:41:30.844000000 Z content_type_id: chapter revision: 1 title: History of research title_internal: 'North Africa: regional chapter 2.5' body: Although the existence of rock art throughout the Sahara was known to local communities, it was not until the nineteenth century that it became known to Europeans, thanks to explorers such as <NAME>, who crossed the Messak Plateau in Libya in 1850, first noting the existence of engravings. Further explorations in the early twentieth century by celebrated travellers, ethnographers and archaeologists such as <NAME>, <NAME>, <NAME>, <NAME> and <NAME> brought the rock art of Sahara, and northern Africa in general, to the awareness of a European public. - sys: id: 5I9fUCNjB668UygkSQcCeK created_at: !ruby/object:DateTime 2015-11-26 15:54:54.847000000 Z updated_at: !ruby/object:DateTime 2016-12-22 10:13:53.921000000 Z content_type_id: image revision: 2 image: sys: id: 2N4uhoeNLOceqqIsEM6iCC created_at: !ruby/object:DateTime 2015-11-26 15:53:37.250000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:53:37.250000000 Z title: '2013,2034.1424' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2N4uhoeNLOceqqIsEM6iCC/240a45012afba4ff5508633fcaea3462/2013_2034.1424.jpg" caption: Pastoral Period painting, cattle and human figure. <NAME>, Acacus Mountains, Libya. 2013,2034.1424 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3592663 - sys: id: 5OkqapzKtqEcomSucG0EoQ created_at: !ruby/object:DateTime 2015-11-26 15:58:52.432000000 Z updated_at: !ruby/object:DateTime 2016-10-17 13:45:37.885000000 Z content_type_id: chapter revision: 4 title: Attribution and dating title_internal: 'North Africa: regional, chapter 3' body: 'The investigations of these researchers and those who have followed them have sought to date and attribute these artworks, with varying measures of success. Rock art may be associated with certain cultures through known parallels with the imagery in other artefacts, such as Naqada Period designs in Egyptian rock art that mirror those on dateable pottery. Authorship may be also guessed at through corroborating evidence: for example, due to knowledge of their chariot use, and the location of rock art depicting chariots in the central Sahara, it has been suggested that it was produced by – or at the same time as – the height of the Garamantes culture, a historical ethnic group who formed a local power around what is now southern Libya from 500 BC–700 AD. However, opportunities to anchor rock art imagery in this way to known ancient cultures are few and far between, and rock art is generally ascribed to anonymous hunter-gatherers, nomadic peoples, or pastoralists, with occasional imagery-based comparisons made with contemporary groups, such as the Fulani peoples.' - sys: id: 2KmaZb90L6qoEAK46o46uK created_at: !ruby/object:DateTime 2015-11-26 15:55:22.104000000 Z updated_at: !ruby/object:DateTime 2016-12-22 10:16:53.318000000 Z content_type_id: image revision: 2 image: sys: id: 5A1AwRfu9yM8mQ8EeOeI2I created_at: !ruby/object:DateTime 2015-11-26 15:53:37.288000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:53:37.288000000 Z title: '2013,2034.1152' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5A1AwRfu9yM8mQ8EeOeI2I/cac0592abfe1b31d7cf7f589355a216e/2013_2034.1152.jpg" caption: Round Head Period painting, human figures. <NAME>, Acacus Mountains, Libya. 2013,2034.1152 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3592099&partId=1&images=true&people=197356&page=1 - sys: id: 27ticyFfocuOIGwioIWWYA created_at: !ruby/object:DateTime 2015-11-26 15:59:26.852000000 Z updated_at: !ruby/object:DateTime 2016-10-17 15:18:29.234000000 Z content_type_id: chapter revision: 2 title_internal: 'North Africa: regional, chapter 4' body: |- Occasionally, association with writing in the form of, for example, Libyan-Berber or Arabic graffiti can give a known dating margin, but in general, lack of contemporary writing and written sources (Herodotus wrote about the Garamantes) leaves much open to conjecture. Other forms of (rare) circumstantial evidence, such as rock art covered by a dateable stratigraphic layer, and (more common) stylistic image-based dating have been used instead to form a chronology of Saharan rock art periods that is widely agreed upon, although dates are contested. The first stage, known as the Early Hunter, Wild Fauna or Bubalus Period, is posited at about 12,000–6,000 years ago, and is typified by naturalistic engravings of wild animals, in particular an extinct form of buffalo identifiable by its long horns. - sys: id: q472iFYzIsWgqWG2esg28 created_at: !ruby/object:DateTime 2015-11-26 15:55:58.985000000 Z updated_at: !ruby/object:DateTime 2016-12-22 10:19:11.991000000 Z content_type_id: image revision: 2 image: sys: id: 1YAVmJPnZ2QQiguCQsgOUi created_at: !ruby/object:DateTime 2015-11-26 15:53:29.989000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:53:29.989000000 Z title: '2013,2034.4570' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1YAVmJPnZ2QQiguCQsgOUi/4080b87891cb255e12a17216d7e71286/2013_2034.4570.jpg" caption: Horse Period painting, charioteer and standing horses. Tarssed Jebest, <NAME>au, Algeria. 2013,2034.4570 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3603794 - sys: id: 7tsWGNvkQgACuKEMmC0uwG created_at: !ruby/object:DateTime 2015-11-26 15:59:47.880000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:59:47.880000000 Z content_type_id: chapter revision: 1 title_internal: 'North Africa: regional, chapter 5' body: A possibly concurrent phase is known as the Round Head Period (about 10,000 to 8,000 years ago) due to the large discoid heads of the painted human figures. Following this is the most widespread style, the Pastoral Period (around 7,500 to 4,000 years ago), which is characterised by numerous paintings and engravings of cows, as well as occasional hunting scenes. The Horse Period (around 3,000 to 2,000 years ago) features recognisable horses and chariots and the final Camel Period (around 2,000 years ago to present) features domestic dromedary camels, which we know to have been widely used across the Sahara from that time. - sys: id: 13V2nQ2cVoaGiGaUwWiQAC created_at: !ruby/object:DateTime 2015-11-26 15:56:25.598000000 Z updated_at: !ruby/object:DateTime 2016-12-22 10:39:22.861000000 Z content_type_id: image revision: 2 image: sys: id: 6MOI9r5tV6Gkae0CEiQ2oQ created_at: !ruby/object:DateTime 2015-11-26 15:53:29.964000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:53:29.964000000 Z title: 2013,2034.1424 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6MOI9r5tV6Gkae0CEiQ2oQ/bad4ec8dd7c6ae553d623e4238641561/2013_2034.1424_1.jpg" caption: Camel engraving. <NAME>, <NAME>, Sudan. 2013,2034.335 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3586831 - sys: id: 3A64bY4VeMGkKCsGCGwu4a created_at: !ruby/object:DateTime 2015-11-26 16:00:04.267000000 Z updated_at: !ruby/object:DateTime 2016-10-17 15:30:04.896000000 Z content_type_id: chapter revision: 2 title_internal: 'North Africa: regional, chapter 6' body: "While this chronology serves as a useful framework, it must be remembered that the area – and the time period in which rock art was produced – is extensive and there is significant temporal and spatial variability within and across sites. There are some commonalities in rock art styles and themes across the Sahara, but there are also regional variations and idiosyncrasies, and a lack of evidence that any of these were directly, or even indirectly, related. The engravings of weaponry motifs from Morocco and the painted ‘swimming’ figures of the Gilf Kebir Plateau in Egypt and Sudan are not only completely different, but unique to their areas. Being thousands of kilometres apart and so different in style and composition, they serve to illustrate the limitations inherent in examining northern African rock art as a unit. The contemporary political and environmental challenges to accessing rock art sites in countries across the Sahara serves as another limiting factor in their study, but as dating techniques improve and further discoveries are made, this is a field with the potential to help illuminate much of the prehistory of northern Africa.\n\n" citations: - sys: id: 4AWHcnuAVOAkkW0GcaK6We created_at: !ruby/object:DateTime 2016-10-17 15:15:38.284000000 Z updated_at: !ruby/object:DateTime 2016-10-17 15:15:38.284000000 Z content_type_id: citation revision: 1 citation_line: | <NAME>. 1998. Art rupestre et préhistoire du Sahara: le Messak Libyen. Paris: Payot & Rivages <NAME>. 1995. Les images rupestres du Sahara. — Toulouse (author’s ed.), p. 447 <NAME>. 2001. Saharan Africa in (ed) David S. Whitley, Handbook of Rock Art Research, pp 605-636. AltaMira Press, Walnut Creek <NAME>. 2013. Dating the rock art of Wadi Sura, in Wadi Sura – The Cave of Beasts, Kuper, R. (ed). Africa Praehistorica 26 – Köln: Heinrich-Barth-Institut, pp. 38-39 <NAME>. 1999. L'art rupestre du Haut Atlas Marocain. Paris, L'Harmattan Soukopova, J. 2012. Round Heads: The Earliest Rock Paintings in the Sahara. Newcastle upon Tyne: Cambridge Scholars Publishing Vernet, R. 1993. Préhistoire de la Mauritanie. Centre Culturel Français A. de Saint Exupéry-Sépia, Nouakchott background_images: - sys: id: 3ZTCdLVejemGiCIWMqa8i created_at: !ruby/object:DateTime 2015-12-07 19:41:46.025000000 Z updated_at: !ruby/object:DateTime 2015-12-07 19:41:46.025000000 Z title: EAF135068 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3ZTCdLVejemGiCIWMqa8i/5a0d13fdd2150f0ff81a63afadd4258e/EAF135068.jpg" - sys: id: 2jvgN3MMfqoAW6GgO8wGWo created_at: !ruby/object:DateTime 2015-12-07 19:41:50.029000000 Z updated_at: !ruby/object:DateTime 2015-12-07 19:41:50.029000000 Z title: EAF131007 description: url: "//images.ctfassets.net/xt8ne4gbbocd/2jvgN3MMfqoAW6GgO8wGWo/393c91068f4dc0ca540c35a79b965288/EAF131007.jpg" country_introduction: sys: id: 5XIlz0Mp6EQW0CaG4wYWoi created_at: !ruby/object:DateTime 2015-11-26 11:46:22.368000000 Z updated_at: !ruby/object:DateTime 2015-12-07 13:42:30.802000000 Z content_type_id: country_information revision: 3 title: 'Algeria: country introduction' chapters: - sys: id: 4oh7iTmoQ8WCE48sGCIkoG created_at: !ruby/object:DateTime 2015-11-26 11:37:15.701000000 Z updated_at: !ruby/object:DateTime 2015-11-26 11:37:15.701000000 Z content_type_id: chapter revision: 1 title: Introduction title_internal: 'Algeria: country, chapter 1' body: Algeria is Africa’s largest country geographically and has long been noted for its rich concentrations of rock art, particularly in the Tassili n’Ajjer, inscribed as a UNESCO World Heritage Site in 1986. More than 15,000 paintings and engravings, some of which date back up to 12,000 years, provide unique insights into the environmental, social, cultural and economic changes in the country across a period of 10,000 or more years. The area is particularly famous for its Round Head paintings, first described and published in the 1930s by French archaeologist <NAME>. - sys: id: KLxWuWwCkMWSuoA44EU8k created_at: !ruby/object:DateTime 2015-11-26 11:30:21.587000000 Z updated_at: !ruby/object:DateTime 2017-01-06 15:40:49.293000000 Z content_type_id: image revision: 2 image: sys: id: 3bBZIG7wBWQe2s06S4w0gE created_at: !ruby/object:DateTime 2015-11-26 11:29:42.872000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:58:02.758000000 Z title: '2013,2034.4248' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3601516&partId=1&searchText=2013,2034.4248&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/3bBZIG7wBWQe2s06S4w0gE/503eeec9a0aa84ff849de9d81dcd091e/2013_2034.4248.jpg" caption: Painted rock art depicting five red figures, from Jabbaren, Tassili n’Ajjer, Algeria. 2013,2034.4248 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3601516&partId=1&images=true&people=197356&museumno=2013,2034.4248&page=1 - sys: id: 5NCDKmpHVuime8uwqkKiMe created_at: !ruby/object:DateTime 2015-11-26 11:37:45.377000000 Z updated_at: !ruby/object:DateTime 2015-11-26 11:37:45.377000000 Z content_type_id: chapter revision: 1 title: Geography title_internal: 'Algeria: country, chapter 2' body: Algeria is situated in the Maghreb region of North Africa, bordered on the west by Morocco and on the east by Tunisia and Libya, with a long Mediterranean coastline to the north. The Atlas Mountains cross Algeria east to west along the Mediterranean coast. The northern portion of the country is an area of mountains, valleys, and plateaus, but more than 80% of the country falls within the Sahara Desert. Rock art is located in the Algerian Maghreb and the Hoggar Mountains but the richest zone of rock art is located in the mountain range of Tassili n'Ajjer, a vast plateau in the south-east of the country. Water and sand erosion have carved out a landscape of thin passageways, large arches, and high-pillared rocks, described by Lhote as 'forests of stone'. - sys: id: 1miMC9tEW0AqawCsYOO0co created_at: !ruby/object:DateTime 2015-11-26 11:30:59.823000000 Z updated_at: !ruby/object:DateTime 2015-11-26 11:30:59.823000000 Z content_type_id: image revision: 1 image: sys: id: 6T7rsl4ISssocM8K0O0g2U created_at: !ruby/object:DateTime 2015-11-26 11:29:42.909000000 Z updated_at: !ruby/object:DateTime 2015-11-26 11:29:42.909000000 Z title: '2013,2034.4551' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6T7rsl4ISssocM8K0O0g2U/ec87053980e76d10917feb28c045fa67/2013_2034.4551.jpg" caption: Tuareg looking over the Tassili n’Ajjer massif. 2013,2034.4551 © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3603812&partId=1&images=true&people=197356&museumno=2013,2034.4551&page=1 - sys: id: 6JVjGRQumAUaMIuMyOUwyM created_at: !ruby/object:DateTime 2015-11-26 11:42:31.967000000 Z updated_at: !ruby/object:DateTime 2015-11-26 11:42:31.967000000 Z content_type_id: chapter revision: 1 title: Research history title_internal: 'Algeria: country, chapter 3' body: |- Rock art in Algeria, notably the engravings in South Oran, has been the subject of European study since 1863. Notable surveys were made by <NAME> (1893-1898), <NAME> (1901-1927), <NAME> (1892-1921), <NAME> and <NAME> (1925), <NAME> (1931-1957), <NAME> (1918-1938), and <NAME> (1935-1955). Henri Lhote visited the area in 1955 and 1964, completing previous research and adding new descriptions included in a major publication on the area in 1970. The rock art of the Tassili region was introduced to Western eyes as a result of visits and sketches made by French legionnaires, in particular a Lt. Brenans during the 1930s. On several of his expeditions, Lt. Brenans took French archaeologist Henri Lhote who went on to revisit sites in Algeria between 1956-1970 documenting and recording the images he found. Regrettably, some previous methods of recording and/or documenting have caused damage to the vibrancy and integrity of the images. - sys: id: 6ljYMZr61ieuSkgCI2sUCs created_at: !ruby/object:DateTime 2015-11-26 11:31:39.981000000 Z updated_at: !ruby/object:DateTime 2015-11-26 11:31:39.981000000 Z content_type_id: image revision: 1 image: sys: id: 6TFwgxGXtYy6OgA02aKUCC created_at: !ruby/object:DateTime 2015-11-26 11:29:47.274000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:58:43.476000000 Z title: '2013,2034.4098' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3595539&partId=1&searchText=2013,2034.4098&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/6TFwgxGXtYy6OgA02aKUCC/cf9adf1bdc99801fbf709fc87fd87acb/2013_2034.4098.jpg" caption: Experiment undertaken by Lhote with experimental varnishes. The dark rectangular patch is the remnant of this experiment. 2013,2034.4098 © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3595539&partId=1&images=true&people=197356&museumno=2013,2034.4098&page=1 - sys: id: 6yYmsmTCWQS88mMakgAOyu created_at: !ruby/object:DateTime 2015-11-26 11:43:01.493000000 Z updated_at: !ruby/object:DateTime 2015-11-26 11:43:01.493000000 Z content_type_id: chapter revision: 1 title: Early rock art title_internal: 'Algeria: country, chapter 4' body: The earliest pieces of rock art are engraved images reflecting a past vibrant fertile environment teeming with life and includes elephant, rhinoceros, hippopotamus and fish as well as numerous predators, giraffe, and plains animals such as antelope and gazelle. When human figures are depicted in this period they are very small in stature and hold throwing sticks or axes. More than simply hunting scenes, they are likely to reflect people’s own place within their environment and their relationship with it. - sys: id: 6ymgBr7UZiEeqcYIK8ESQw created_at: !ruby/object:DateTime 2015-11-26 11:32:15.331000000 Z updated_at: !ruby/object:DateTime 2017-01-06 15:41:43.326000000 Z content_type_id: image revision: 2 image: sys: id: faUxnSK2ookUW6UWyoCOa created_at: !ruby/object:DateTime 2015-11-26 11:29:42.884000000 Z updated_at: !ruby/object:DateTime 2015-11-26 11:29:42.884000000 Z title: '2013,2034.4685' description: url: "//images.ctfassets.net/xt8ne4gbbocd/faUxnSK2ookUW6UWyoCOa/ec94f329a011643a9f0eba672fd5fb6f/2013_2034.4685.jpg" caption: Engraved elephant, Tadrart, Algeria. 2013,2034.4685 © TARA/David Coulson col_link: http://bit.ly/2iMdChh - sys: id: 61Gb2N3umIC8cAAq2q8SWK created_at: !ruby/object:DateTime 2015-11-26 11:43:56.920000000 Z updated_at: !ruby/object:DateTime 2015-11-26 11:44:04.420000000 Z content_type_id: chapter revision: 2 title: Round Head Period title_internal: 'Algeria: country, chapter 5' body: The area is especially famous for its Round Head paintings. Thought to be up to 9,000 years old, some of these paintings are the largest found on the African continent, measuring up to 13 feet in height. The Round Head period comprises depictions of figures with round, featureless heads and formless bodies, often appearing to be ‘floating’. Some features or characteristics of Round Head paintings found on the Tassili plateau are unique to the area, and the depiction of certain motifs may have held special significance locally, making particular sites where they occur the locus of rites, ritual or ceremonial activity. The majority of animal depictions are mouflon (wild mountain sheep) and antelope, but they are represented only in static positions and not as part of a hunting scene. - sys: id: 14fYsLFiwaOeGqSscuI4eW created_at: !ruby/object:DateTime 2015-11-26 11:32:46.062000000 Z updated_at: !ruby/object:DateTime 2015-11-26 11:32:46.062000000 Z content_type_id: image revision: 1 image: sys: id: 79I1hxTRDyYiqcMG02kgE8 created_at: !ruby/object:DateTime 2015-11-26 11:29:47.295000000 Z updated_at: !ruby/object:DateTime 2015-11-26 11:29:47.295000000 Z title: '2013,2034.4173' description: url: "//images.ctfassets.net/xt8ne4gbbocd/79I1hxTRDyYiqcMG02kgE8/0fa8b92cad626f5dfe083c814b30fdfb/2013_2034.4173.jpg" caption: Round Head Period painting, Tassili n’Ajjer, Algeria. 2013,2034.4173 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3595624&partId=1&images=true&people=197356&museumno=2013,2034.4173&page=1 - sys: id: 4SqZjJi0EoeEIKuywW8eqM created_at: !ruby/object:DateTime 2015-11-26 11:44:33.802000000 Z updated_at: !ruby/object:DateTime 2015-11-26 11:44:33.802000000 Z content_type_id: chapter revision: 1 title: Pastoral Period title_internal: 'Algeria: country, chapter 6' body: The subsequent Pastoral Period, from around 7,500-4,000 years ago, portrays a very different world to the preceding ethereal Round Head period and coincides with the transition from a temperate Sahara towards aridification. Images are stylistically varied, which may attest to the movement of different cultural groups. Depictions now include domesticated animals such as cattle, sheep, goats and dogs; scenes portray herders, men hunting with bows, and representations of camp life with women and children – in essence, scenes that reference more settled communities. - sys: id: 3VIsvEgqPSMMumIgAaO8WG created_at: !ruby/object:DateTime 2015-11-26 11:33:24.713000000 Z updated_at: !ruby/object:DateTime 2015-11-26 11:33:24.713000000 Z content_type_id: image revision: 1 image: sys: id: 2E7xpiKWhe6YEOymWI4W2U created_at: !ruby/object:DateTime 2015-11-26 11:29:42.877000000 Z updated_at: !ruby/object:DateTime 2015-11-26 11:29:42.877000000 Z title: '2013,2034.4193' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2E7xpiKWhe6YEOymWI4W2U/97b35a4e1f3bfaa5184d701c43f0457f/2013_2034.4193.jpg" caption: "‘The Archers Of Tin Aboteka’, Tassili n’Ajjer, Algeria. 2013,2034.4193 © TARA/<NAME>" col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3601339&partId=1&images=true&people=197356&museumno=2013,2034.4193&page=1 - sys: id: 40HLnbmrO8uqoewYai0IwM created_at: !ruby/object:DateTime 2015-11-26 11:44:57.711000000 Z updated_at: !ruby/object:DateTime 2015-11-26 11:44:57.711000000 Z content_type_id: chapter revision: 1 title: Horse Period title_internal: 'Algeria: country, chapter 7' body: |- Desertification across the Sahara required new methods of traversing and utilising the landscape; depictions of horses (often with riders) and of chariots indicate this change. Horse-drawn chariots are often depicted at a ‘flying’ gallop and are likely to have been used for hunting rather than warfare. Libyan-Berber script, used by ancestral Berber peoples, started to appear in association with images. However, the meaning of this juxtaposition of text and image remains an enigma, as it is indecipherable to modern day Tuareg. - sys: id: 19xQJunRyCWOOOMKScgcqA created_at: !ruby/object:DateTime 2015-11-26 11:34:00.220000000 Z updated_at: !ruby/object:DateTime 2015-11-26 11:34:00.220000000 Z content_type_id: image revision: 1 image: sys: id: czVoXzqkG4KUm2A4QcWUO created_at: !ruby/object:DateTime 2015-11-26 11:29:42.885000000 Z updated_at: !ruby/object:DateTime 2015-11-26 11:29:42.885000000 Z title: '2013,2034.4567' description: url: "//images.ctfassets.net/xt8ne4gbbocd/czVoXzqkG4KUm2A4QcWUO/d463d9da38652be56e35908b2bde6659/2013_2034.4567.jpg" caption: Horse-drawn chariot, <NAME>, Tassili n’Ajjer, Algeria. 2013,2034.4567 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3603797&partId=1&images=true&people=197356&museumno=2013,2034.4567&page=1 - sys: id: 46nmFnhwM8uuaWOwceYYku created_at: !ruby/object:DateTime 2015-11-26 11:45:24.076000000 Z updated_at: !ruby/object:DateTime 2015-11-26 11:45:24.076000000 Z content_type_id: chapter revision: 1 title: Camel Period title_internal: 'Algeria: country, chapter 8' body: The last defined period stylistically is characterised by the depiction of camels, representing an alternative method of negotiating this arid and harsh landscape. Camels can travel for days without water and were used extensively in caravans transporting trade goods and salt. Depictions in this period continue to include domestic animals and armed figures. - sys: id: 22za3qNw1SqCCSMKiQ4ose created_at: !ruby/object:DateTime 2015-11-26 11:34:35.045000000 Z updated_at: !ruby/object:DateTime 2015-11-26 11:34:35.045000000 Z content_type_id: image revision: 1 image: sys: id: 2F8RnTvFpKGUaYYcaY2YUS created_at: !ruby/object:DateTime 2015-11-26 11:29:42.916000000 Z updated_at: !ruby/object:DateTime 2015-11-26 11:29:42.916000000 Z title: '2013,2034.4469' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2F8RnTvFpKGUaYYcaY2YUS/c940797f40d292f5d2691f43c9a974b4/2013_2034.4469.jpg" caption: Camel train Tassili n’Ajjer, Algeria. 2013,2034.4469 © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3602862&partId=1&images=true&people=197356&museumno=2013,2034.4469&page=1 citations: - sys: id: 6rWROpK4k8wIAwAY8aMKo6 created_at: !ruby/object:DateTime 2015-11-26 11:35:36.510000000 Z updated_at: !ruby/object:DateTime 2015-11-26 11:35:36.510000000 Z content_type_id: citation revision: 1 citation_line: |- <NAME>. 2001. *Saharan Africa* in (ed) <NAME>, Handbook of Rock Art Research, pp 605-636. AltaMira Press, Walnut Creek Soukopova, J. 2012. *Round Heads: The Earliest Rock Paintings in the Sahara*. Newcastle upon Tyne: Cambridge Scholars Publishing [Tassili n’Ajjer, UNESCO](http://whc.unesco.org/en/list/179/) background_images: - sys: id: 2Yrtu5ZIDCq4Ca0EawKacC created_at: !ruby/object:DateTime 2015-12-08 17:16:05.134000000 Z updated_at: !ruby/object:DateTime 2015-12-08 17:16:05.134000000 Z title: ALGDJA0060004 description: url: "//images.ctfassets.net/xt8ne4gbbocd/2Yrtu5ZIDCq4Ca0EawKacC/9067c88302644cf52204fa4cfb08a4b1/ALGDJA0060004.jpg" - sys: id: 16CSt7fIQy4yyEY2aysOGK created_at: !ruby/object:DateTime 2015-11-27 15:12:52.496000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:56:16.475000000 Z title: '2013,2034.4191' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3601323&partId=1&searchText=ALGDJA0040001&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/16CSt7fIQy4yyEY2aysOGK/02706f11b80f640af920a6ee3158a924/ALGDJA0040001.jpg" - sys: id: 5migSD5CiAa48U4gOyqCao created_at: !ruby/object:DateTime 2015-11-27 15:15:13.229000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:55:22.577000000 Z title: '2013,2034.4280' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3601594&partId=1&searchText=ALGDJA0050061&page=1 url: "//downloads.ctfassets.net/xt8ne4gbbocd/5migSD5CiAa48U4gOyqCao/b2d00aaa4e29281fe3dcca614dd381b5/ALGDJA0050061.jpg" region: Northern / Saharan Africa ---<file_sep>/_coll_country/niger/dabous.md --- breadcrumbs: - label: Countries url: "../../" - label: Niger url: "../" layout: featured_site contentful: sys: id: 3iEbGKCOjuqgaMOGUQiQuS created_at: !ruby/object:DateTime 2015-11-25 15:50:42.860000000 Z updated_at: !ruby/object:DateTime 2015-12-07 20:52:09.605000000 Z content_type_id: featured_site revision: 4 title: Dabous, Niger slug: dabous chapters: - sys: id: 5j5MjrxkwgewSk0EAgqMkS created_at: !ruby/object:DateTime 2015-11-25 15:44:58.105000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:44:58.105000000 Z content_type_id: chapter revision: 1 title_internal: 'Niger: featured site, chapter 1' body: Dabous is located in north-eastern Niger, where the Ténéré desert meets the slopes of the Aïr Mountains. The area has been part of the trans-Saharan caravan trade route traversed by the Tuareg for over two millennia, but archaeological evidence shows much older occupation in the region dating back 8,000 years. More recently, it has become known to a wider global audience for its exceptional rock art. - sys: id: 5Tp7co5fdCUIi68CyKGm8o created_at: !ruby/object:DateTime 2015-11-25 15:38:46.775000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:38:46.775000000 Z content_type_id: image revision: 1 image: sys: id: 56TaQ0UFBK8sEE4GWaQOcw created_at: !ruby/object:DateTime 2015-11-25 15:37:38.020000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:37:38.020000000 Z title: '2013,2034.10543' description: url: "//images.ctfassets.net/xt8ne4gbbocd/56TaQ0UFBK8sEE4GWaQOcw/d8465329314fcafe9814b92028e90927/2013_2034.10543.jpg" caption: Dabous giraffe. Western Aïr Mountains, Niger. 2013,2034.10543 © David Coulson/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3637915&partId=1&searchText=2013,2034.9967&people=197356&place=13131&museumno=2013,2034.10543&page=1 - sys: id: 59s9c4KH8skCgKkQMaWymw created_at: !ruby/object:DateTime 2015-11-25 15:45:19.771000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:45:19.771000000 Z content_type_id: chapter revision: 1 title_internal: 'Niger: featured site, chapter 2' body: |- Recorded in 1987 by French archaeologist <NAME>, two remarkable life-size engravings of giraffe have generated much interest due to the size, realism and technique of the depictions. The two giraffe, thought to be one large male in front of a smaller female, were engraved on the weathered surface of a sandstone outcrop. The larger giraffe measures 5.4 m from top to toe and combines several techniques of production, including scraping, smoothing and deep engraving of the outlines. Each giraffe has an incised line emanating from its mouth or nose, meandering down to a small human figure. This motif is not unusual in Saharan rock art, but its meaning remains a mystery. Interpretations have suggested the line may indicate that giraffe were hunted or even domesticated, or may reflect a religious, mythical or cultural association. It has also been suggested that the lines and human figures were later additions. - sys: id: 5ZK8nNmuzKa66KOEqquoqI created_at: !ruby/object:DateTime 2015-11-25 15:39:28.089000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:39:28.089000000 Z content_type_id: image revision: 1 image: sys: id: 6Y2u961dcWISC2E2CK62KS created_at: !ruby/object:DateTime 2015-11-25 15:37:55.237000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:37:55.237000000 Z title: '2013,2034.10570' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6Y2u961dcWISC2E2CK62KS/64bef06da41a71f32cf8601c426d1608/2013_2034.10570.jpg" caption: Dabous giraffe. Western Aïr Mountains, Niger. 2013,2034.10570 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3637906&partId=1&searchText=2013,2034.10570&people=197356&place=13131&museumno=2013,2034.10570&page=1 - sys: id: ZKn6IIxaoeiw68c444iAM created_at: !ruby/object:DateTime 2015-11-25 15:40:08.118000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:40:08.118000000 Z content_type_id: image revision: 1 image: sys: id: n2nHWRqjXE0qkaEqCWK6Y created_at: !ruby/object:DateTime 2015-11-25 15:37:38.049000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:37:38.049000000 Z title: '2013,2034.10555' description: url: "//images.ctfassets.net/xt8ne4gbbocd/n2nHWRqjXE0qkaEqCWK6Y/7a3d94b2a4f3d792a0f9de60647d3d59/2013_2034.10555.jpg" caption: Dabous giraffe at night. Western Aïr Mountains, Niger. 2013,2034.10555 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3637914&partId=1&searchText=2013,2034.10570&people=197356&place=13131&museumno=2013,2034.10555&page=1 - sys: id: 1oNgYDPKxuquY6U6gsKY62 created_at: !ruby/object:DateTime 2015-11-25 15:45:53.655000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:45:53.655000000 Z content_type_id: chapter revision: 1 title_internal: 'Niger: featured site, chapter 3' body: |- The engravings cannot be seen from ground level; they are only visible by climbing onto the boulder. They are thought to date from between 6,000 and 8,000 years ago – a period known as the Neolithic Subpluvial, when environmental conditions were much wetter and the Sahara was a vast savannah stretching for thousands of miles, able to sustain large mammals such as giraffe. The soft sandstone is likely to have been incised using a harder material such as flint; there are chisels of petrified wood in the surrounding desert sands which would have acted as good tools for abrading and polishing outlines. It is easy to imagine people in the past sitting on the rocky outcrop watching these long-necked, graceful animals and immortalising them in stone for future generations. We can only speculate as to why the giraffe was selected for this special treatment. Any number of physical, behavioural, environmental or symbolic factors may have contributed to its significance. - sys: id: 3Xlo7BIZzy2umQ2Ac6M2QI created_at: !ruby/object:DateTime 2015-11-25 15:40:37.408000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:40:37.408000000 Z content_type_id: image revision: 1 image: sys: id: 4yEY9exQaswSA6k6Gu02c6 created_at: !ruby/object:DateTime 2015-11-25 15:38:02.784000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:38:02.784000000 Z title: '2013,2034.10751' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4yEY9exQaswSA6k6Gu02c6/307728aa6d1880f11af9dc45d7e7d830/2013_2034.10751.jpg" caption: Further engravings at the site. Dabous, Western Aïr Mountains, Niger. 2013,2034.10751 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3637901&partId=1&searchText=2013,2034.10570&people=197356&place=13131&museumno=2013,2034.10751&page=1 - sys: id: 2tsfZzpTFWoYacAQioAyQ0 created_at: !ruby/object:DateTime 2015-11-25 15:46:12.778000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:46:12.778000000 Z content_type_id: chapter revision: 1 title_internal: 'Niger: featured site, chapter 4' body: |- While the giraffe have taken centre stage at this site because of their size and the skill of the execution, a systematic study of the area has identified 828 further engravings, including 704 zoomorphs (animal forms), 61 anthropomorphs (human forms), and 17 inscriptions of Tifinâgh script. The animals identified include: bovines (cattle ) (46%), ostrich (16%), antelope and gazelle (16%), giraffe (16%), and finally 12 dromedaries (camels), 11 canids (dog-like mammals), 6 rhinoceros, 3 equids (horses or donkeys), 2 monkeys, 2 elephants, and 1 lion. Who might the artists have been? It is often the case in rock art research that artists are lost to us in time and we have little or no archaeological evidence that can offer insights into the populations that occupied these sites, sometimes only for a short time. However, in 2001 a site called Gobero was discovered that provides a glimpse of life in this region at the time that the Dabous engravings were produced. - sys: id: gku8mXGHUA06KW8YGgU64 created_at: !ruby/object:DateTime 2015-11-25 15:41:06.708000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:41:06.708000000 Z content_type_id: image revision: 1 image: sys: id: 5Lzyd3mFTUII2MEkgQ0ki2 created_at: !ruby/object:DateTime 2015-11-25 15:37:38.045000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:37:38.045000000 Z title: Gobero description: url: "//images.ctfassets.net/xt8ne4gbbocd/5Lzyd3mFTUII2MEkgQ0ki2/61cb38b7b4e4d62e911bb971cad67c7f/Gobero.jpg" caption: 'Aerial view of Gobero archaeological site in Niger, from the Holocene Period. Source: Sereno et al. 2008, (via Wikimedia Commons)' col_link: https://commons.wikimedia.org/wiki/File%3AGobero.jpg - sys: id: dSvovYGs3C6YsimmmIEeA created_at: !ruby/object:DateTime 2015-11-25 15:46:46.760000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:46:46.760000000 Z content_type_id: chapter revision: 1 title_internal: 'Niger: featured site, chapter 5' body: Gobero is located at the western tip of the Ténéré desert in Niger, approximately 150 km south-east of the Aïr Mountains. Situated on the edge of a paleaolake and dating from the early Holocene (7,700–6,200 years ago), it is the earliest recorded cemetery in the western Sahara and consists of around 200 burials. Skeletal evidence shows both male and females to be tall in stature, approaching two metres. Some of the burials included items of jewellery, including a young girl wearing a bracelet made from the tusk of a hippo, and a man buried with the shell of a turtle. - sys: id: 2bxmGW0ideQSs4esWCUCka created_at: !ruby/object:DateTime 2015-11-25 15:41:32.700000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:41:32.700000000 Z content_type_id: image revision: 1 image: sys: id: 24rwZWG7UA02KCgcKeaOQS created_at: !ruby/object:DateTime 2015-11-25 15:37:47.721000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:37:47.721000000 Z title: '2013,2034.10635' description: url: "//images.ctfassets.net/xt8ne4gbbocd/24rwZWG7UA02KCgcKeaOQS/762b9a27c73609c09017102e0f4cb3f4/2013_2034.10635.jpg" caption: Close up of head and neck of large giraffe. Dabous, Western Aïr Mountains, Niger. 2013,2034.10635 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3637902&partId=1&people=197356&place=13131&museumno=2013,2034.10635&page=1 - sys: id: 58NIyuAAcwEMy8WCsoIEwO created_at: !ruby/object:DateTime 2015-11-25 15:47:13.849000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:47:13.849000000 Z content_type_id: chapter revision: 1 title_internal: 'Niger: featured site, chapter 6' body: This cultural group were largely sedentary; their subsistence economy was based on fishing (Nile perch, catfish, soft-shell turtles) and hunting (hippos, bovids, small carnivores and crocodiles). Microlithis, bone harpoon points and hooks, as well as ceramics with dotted wavy-line and zig-zag impressed motif were found in burials, refuse areas and around the lake. A hiatus in the occupation of the area (6,200–5,200 years ago) occurred during a harsh arid interval, forcing the occupants to relocate. The Gobero population may not be the artists responsible for Dabous, but archaeological evidence can help formulate a picture of the environmental, social and material culture at the time of the engravings. - sys: id: 4M6x7TPSB2g20UC6ck0ism created_at: !ruby/object:DateTime 2015-11-25 15:41:59.887000000 Z updated_at: !ruby/object:DateTime 2017-01-09 17:08:32.539000000 Z content_type_id: image revision: 2 image: sys: id: 6HNDioOx44CMaGCccQQE2G created_at: !ruby/object:DateTime 2015-11-25 15:37:38.095000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:37:38.095000000 Z title: '2013,2034.10608' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6HNDioOx44CMaGCccQQE2G/9c2d264396e34b6900229a7142f38d8e/2013_2034.10608.jpg" caption: Taking a cast of the Dabous giraffe. Western Aïr Mountains, Niger. 2013,2034.10608 © <NAME>/TARA col_link: http://bit.ly/2j0rzed - sys: id: 1jPJvNv7dcciOCCiiUugQq created_at: !ruby/object:DateTime 2015-11-25 15:47:33.801000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:47:33.801000000 Z content_type_id: chapter revision: 1 title_internal: 'Niger: featured site, chapter 7' body: Unfortunately, the engravings have been subject to deterioration as a result of human intervention such as trampling, graffiti and fragments being stolen. As a result, the decision was made to preserve them by making a mould of the carvings in order to make a cast in a resistant material. Permission was granted by both the government of Niger and UNESCO and in 1999 the moulding process took place. The first cast of the mould, made in aluminium, stands at the airport of Agadez in the small desert town near the site of Dabous – an enduring symbol of the rich rock art heritage of the country. - sys: id: 2MlmKLhdHq6SQyiU0IyIww created_at: !ruby/object:DateTime 2015-11-25 15:48:27.320000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:48:27.320000000 Z content_type_id: chapter revision: 1 title_internal: 'Niger: featured site, chapter 8' body: In 2000, the giraffe engravings at Dabous were declared one of the 100 Most Endangered Sites by the [World Monuments Watch](https://www.wmf.org/). Today, a small group of Tuareg live in the area, acting as permanent guides and custodians of the site. citations: - sys: id: 5IQzdbUWHemE6WCkUUeQwi created_at: !ruby/object:DateTime 2015-11-25 15:43:52.331000000 Z updated_at: !ruby/object:DateTime 2015-12-08 18:25:23.674000000 Z content_type_id: citation revision: 3 citation_line: |+ <NAME>. ‘Réflexions sur l'identité des guerriers représentés dans les gravures de l'Adrar des Iforas et de l'Aïr’ in *Sahara*, 10, pp.31-54 <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., et al. 2008. ‘Lakeside Cemeteries in the Sahara: 5000 Years of Holocene Population and Environmental Change’. PLoS ONE, 3(8): pp.1-22 ‘The Giraffe Carvings of the Tenere Desert’: [http://www.bradshawfoundation.com/giraffe/](http://www.bradshawfoundation.com/giraffe/) background_images: - sys: id: 58CpIve4WQo8wq4ooU0SoC created_at: !ruby/object:DateTime 2015-12-07 20:33:25.148000000 Z updated_at: !ruby/object:DateTime 2015-12-07 20:33:25.148000000 Z title: NIGEAM0060015 description: url: "//images.ctfassets.net/xt8ne4gbbocd/58CpIve4WQo8wq4ooU0SoC/bdaac15fdb14d3baf1a2f2ffa2a00e80/NIGEAM0060015_jpeg.jpg" - sys: id: 4yEY9exQaswSA6k6Gu02c6 created_at: !ruby/object:DateTime 2015-11-25 15:38:02.784000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:38:02.784000000 Z title: '2013,2034.10751' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4yEY9exQaswSA6k6Gu02c6/307728aa6d1880f11af9dc45d7e7d830/2013_2034.10751.jpg" ---<file_sep>/_coll_country/chad.md --- contentful: sys: id: 38DAUm67FmsySguQseSW4G created_at: !ruby/object:DateTime 2015-11-26 18:53:33.946000000 Z updated_at: !ruby/object:DateTime 2018-05-17 17:07:52.975000000 Z content_type_id: country revision: 10 name: Chad slug: chad col_url: http://www.britishmuseum.org/research/collection_online/search.aspx?people=197356&place=17412 map_progress: true intro_progress: true image_carousel: - sys: id: 1EOAe1GFKQSG2oWYiKSIYI created_at: !ruby/object:DateTime 2015-11-25 16:38:31.745000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:11:12.941000000 Z title: '2013,2034.6164' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3637058&partId=1&searchText=Niola+Doa&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/1EOAe1GFKQSG2oWYiKSIYI/15c83103aa2766992fd90414a29ea01b/2013_2034.6164.jpg" - sys: id: 47ocQmZwI8iOE4Sskq8IeE created_at: !ruby/object:DateTime 2015-11-26 13:20:23.164000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:11:47.535000000 Z title: '2013,2034.6155' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3637041&partId=1&searchText=2013,2034.6155&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/47ocQmZwI8iOE4Sskq8IeE/8ce5836027971e7b02317274015177ac/2013_2034.6155.jpg" - sys: id: 6uYaJrzaMgAwK42CSgwcMW created_at: !ruby/object:DateTime 2015-11-26 13:20:23.253000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:12:19.070000000 Z title: '2013,2034.6595' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3640375&partId=1&searchText=2013,2034.6595&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/6uYaJrzaMgAwK42CSgwcMW/b71fe481a99fa36b16f32265828a440e/2013_2034.6595.jpg" - sys: id: 6oPleKTKGkMwAAqauyGIEg created_at: !ruby/object:DateTime 2015-11-30 14:48:21.552000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:13:02.868000000 Z title: CHAOUE0010004 description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3655371&partId=1&searchText=CHAOUE0010004&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/6oPleKTKGkMwAAqauyGIEg/32f1d8d0ec0e654367cf7714369bb892/CHAOUE0010004.jpg" - sys: id: 2PcrJHELNCAIIy2e0kaKCi created_at: !ruby/object:DateTime 2015-11-30 14:48:27.760000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:13:33.939000000 Z title: CHAOUE0010015 description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3655360&partId=1&searchText=CHAOUE0010015&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/2PcrJHELNCAIIy2e0kaKCi/0255e3508a43a6856a9e52cd1d5a2d0a/CHAOUE0010015.jpg" - sys: id: A8qbbR0yNEuSEqsYCia4U created_at: !ruby/object:DateTime 2015-11-30 14:48:34.511000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:14:23.527000000 Z title: CHATEK0070003 description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3651401&partId=1&searchText=CHATEK0070003&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/A8qbbR0yNEuSEqsYCia4U/274d59ef5d3bfc72adfa42e8bfd0cfce/CHATEK0070003.jpg" featured_site: sys: id: 3l1e5Bn0NOggigQsmiGG8q created_at: !ruby/object:DateTime 2015-11-25 16:45:15.719000000 Z updated_at: !ruby/object:DateTime 2015-12-07 20:52:38.130000000 Z content_type_id: featured_site revision: 3 title: Niola Doa, Chad slug: niola-doa chapters: - sys: id: 2HKVwIp55eweW6WcioyIAg created_at: !ruby/object:DateTime 2015-11-25 16:42:21.650000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:42:21.650000000 Z content_type_id: chapter revision: 1 title_internal: 'Chad: featured site, chapter 1' body: The Ennedi Plateau is a mountainous region in the north-eastern corner of Chad, an impressive sandstone massif eroded by wind and temperature changes into series of terraces, gorges, cliffs and outliers. Although it is part of the Sahara, the climate of the Ennedi Plateau is much more suitable for human habitation than most of the desert, with regular rain during summer, wadis (seasonal rivers) flowing once or twice a year, and a relatively large range of flora and fauna – including some of the few remaining populations of Saharan crocodiles west of the Nile. Throughout the caves, canyons and shelters of the Ennedi Plateau, thousands of images – dating from 5000 BC onwards – have been painted and engraved, comprising one of the biggest collections of rock art in the Sahara and characterised by a huge variety of styles and themes. - sys: id: 5fxX9unUx2i8G6Cw0II2Qk created_at: !ruby/object:DateTime 2015-11-25 16:39:08.235000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:39:08.235000000 Z content_type_id: image revision: 1 image: sys: id: 3x13gapfeoswomWyA0gyWS created_at: !ruby/object:DateTime 2015-11-25 16:38:31.707000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:38:31.707000000 Z title: '2013,2034.6150' description: url: "//images.ctfassets.net/xt8ne4gbbocd/3x13gapfeoswomWyA0gyWS/25cf96fec447ce7f0bf93d75ac2efa7f/2013_2034.6150.jpg" caption: View of the second main group of engraved human figures. Ennedi Plateau. 2013,2034.6150 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3637019&partId=1&people=197356&museumno=2013,2034.6150&page=1 - sys: id: 5JEd4uYIEMAQsCKkKIeWIK created_at: !ruby/object:DateTime 2015-11-25 16:42:38.368000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:42:38.368000000 Z content_type_id: chapter revision: 1 title_internal: 'Chad: featured site, chapter 2' body: 'Within this kaleidoscope, a series of engravings have become especially renowned for their singularity and quality: several groups of life-sized human figures depicted following very regular stylistic conventions. They were first reported internationally in the early 1950s; during the following decades more sites were discovered, almost all of them around Wadi Guirchi, and especially near a site known as <NAME>. To date, six sites have been documented, totalling about 40 depictions. Most of the figures were engraved on big, vertical boulders, in groups, although occasionally they appear isolated. They follow a very regular pattern: most of them are life-sized or even bigger and are represented upright facing right or left, with one arm bent upwards holding a stick resting over the neck or shoulder and the other arm stretched downwards. In some cases, the figures have an unidentified, horizontal object placed at the neck, probably an ornament. Interspersed among the bigger figures, there are smaller versions which are slightly different, some of them with the arms in the same position as the others but without sticks, and some facing forwards with hands on hips. In general, figures seem to be naked, although in some cases the smaller figures are depicted with skirts.' - sys: id: 6mkGfHTaJaqiAgiQYQqIYW created_at: !ruby/object:DateTime 2015-11-25 16:40:06.201000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:40:06.201000000 Z content_type_id: image revision: 1 image: sys: id: 1EOAe1GFKQSG2oWYiKSIYI created_at: !ruby/object:DateTime 2015-11-25 16:38:31.745000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:11:12.941000000 Z title: '2013,2034.6164' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3637058&partId=1&searchText=Niola+Doa&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/1EOAe1GFKQSG2oWYiKSIYI/15c83103aa2766992fd90414a29ea01b/2013_2034.6164.jpg" caption: Detail of the first main group of engraved human figures, where the standardized position of the arms and the stick can be observed. Ennedi Plateau. 2013,2034.6164 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3637058&partId=1&people=197356&museumno=2013,2034.6164&page=1 - sys: id: 6HD9yuFPckYYWOaWeQmA4Y created_at: !ruby/object:DateTime 2015-11-25 16:42:56.088000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:42:56.088000000 Z content_type_id: chapter revision: 1 title_internal: 'Chad: featured site, chapter 3' body: Another characteristic feature of these images is their abnormally wide buttocks and thighs, which have been interpreted as steatopygia (a genetic condition resulting in an accumulation of fat in and around the buttocks). Although the best documented examples of steatopygia (both in rock art and contemporary groups) correspond to southern Africa, steatopygic depictions occur elsewhere in North African rock art, with examples in other parts of the Ennedi Plateau, but also in Egypt and Sudan, where they occasionally appear incised in pottery. - sys: id: 3Nd1QIszi8wcWsm4W2CGw8 created_at: !ruby/object:DateTime 2015-11-25 16:40:36.716000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:40:36.716000000 Z content_type_id: image revision: 1 image: sys: id: 4r9HybjNjOaMU2wI44IUWw created_at: !ruby/object:DateTime 2015-11-25 16:38:31.713000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:38:31.713000000 Z title: '2013,2034.6175' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4r9HybjNjOaMU2wI44IUWw/dd398573be19287063d1427947409e9d/2013_2034.6175.jpg" caption: Close-up of figure from the first main group. Note the schematic birds depicted at the waist –the only known example of zoomorphic pattern in these figures. Ennedi Plateau. 2013,2034.6175 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3637066&partId=1&people=197356&museumno=2013,2034.6175&page=1 - sys: id: 5N8CCXZw5OCGiUGMQ8Sw8s created_at: !ruby/object:DateTime 2015-11-25 16:43:21.226000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:43:21.226000000 Z content_type_id: chapter revision: 1 title_internal: 'Chad: featured site, chapter 4' body: |- In addition, almost all the figures are decorated with intricate geometric patterns (straight and wavy lines, squares, meanders and, in one case, schematic birds), which could be interpreted as garments, tattoos, scarifications or body paintings. In some cases, figures appear simply outlined, but these very rare cases were probably left unfinished. The decorative patterns extend to the ears, which are always depicted with geometric designs, and to the head, where these designs could correspond to hairstyles. The decorative richness of the Niola Doa engravings has led to their interpretation as ritual scenes, probably special occasions when body decoration was part of a more complex set of activities with dancing or singing. On some occasions, comparisons have been established between the geometric designs of Niola Doa and different types of body decorations (body painting, scarifications). Scarifications, in particular, have a long tradition within some African cultures and in many cases parallels have been documented between this kind of body decoration and material culture (i.e. pottery, pipes, wood sculptures or clothes). The relative proximity of groups with well-known traditions of scarifications and body painting has led to comparisons which, although suggested, cannot be wholly proved. - sys: id: 2clJsITj8kM8uSE6skaYae created_at: !ruby/object:DateTime 2015-11-25 16:41:04.916000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:41:16.496000000 Z content_type_id: image revision: 2 image: sys: id: 3UndBeXLYs8mK4Y4OWkMU8 created_at: !ruby/object:DateTime 2015-11-25 16:38:31.717000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:38:31.717000000 Z title: Af,B1.25 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3UndBeXLYs8mK4Y4OWkMU8/be1053ea6e513ce14b92a736f6da52cf/Af_B1.25.jpg" caption: 'Scarification on upper back and shoulder of an adult. Sudan, early 20th century. Photograph: © British Museum Af,B1.25' col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=1412934&partId=1&people=197356&museumno=Af,B1.25&page=1 - sys: id: 5fnEMAOYzSs8quyaQiiUUA created_at: !ruby/object:DateTime 2015-11-25 16:43:40.154000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:43:40.154000000 Z content_type_id: chapter revision: 1 title_internal: 'Chad: featured site, chapter 5' body: 'Regarding their chronology, as with most rock art depictions the Niola Doa figures are difficult to date, although they undoubtedly belong to the older periods of Chadian rock art. Some parallels have been made with the Round Head-style figures of the Tassili n’Ajjer (Simonis et al 1994). However, the Round Head figures of Algeria have a very old chronology (up to 9000 years ago), while the rock art at the Ennedi Plateau is assumed to be much newer, up to the 5th or 4th millennium BC. These engravings could, therefore, correspond to what has been called the Archaic Period in this area, although a Pastoral Period chronology has also been proposed. In several other sites around the Ennedi Plateau, similar images have been painted, although whether these images are contemporary with those of Niola Doa or correspond to a different period is unclear. Regardless of their chronology, what is undeniable is the major impact these depictions had on later generations of people living in the area: even now, the engravings at one of the sites are known as the ‘Dancing Maidens’, while the name of Niola Doa means ‘The place of the girls’ in the local language.' citations: - sys: id: 2SoR8lQCF2SkAQAyGIYMc8 created_at: !ruby/object:DateTime 2015-11-25 16:41:51.721000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:41:51.721000000 Z content_type_id: citation revision: 1 citation_line: "<NAME> (1997). *Art rupestre en Ennedi. Looking for rock paintings and engravings in the Ennedi Hills*, Sépia, Saint-Maur.\n \nSimonis, R., <NAME>. and <NAME>. (1994) *Niola Doa, ‘il luogo delle fanciulle’ (Ennedi, Ciad)*, Sahara 6, pp.51-63." background_images: - sys: id: 1EOAe1GFKQSG2oWYiKSIYI created_at: !ruby/object:DateTime 2015-11-25 16:38:31.745000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:11:12.941000000 Z title: '2013,2034.6164' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3637058&partId=1&searchText=Niola+Doa&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/1EOAe1GFKQSG2oWYiKSIYI/15c83103aa2766992fd90414a29ea01b/2013_2034.6164.jpg" - sys: id: 4BGLzXecpqKOsuwwiIaM6K created_at: !ruby/object:DateTime 2015-12-07 20:31:44.334000000 Z updated_at: !ruby/object:DateTime 2015-12-07 20:31:44.334000000 Z title: CHANAS0103 description: url: "//images.ctfassets.net/xt8ne4gbbocd/4BGLzXecpqKOsuwwiIaM6K/a4318baa413e590cc6fb087d62888382/CHANAS0103.jpg" key_facts: sys: id: 6nVplLt1ZKMIuGI66U6K0I created_at: !ruby/object:DateTime 2015-11-26 11:25:35.954000000 Z updated_at: !ruby/object:DateTime 2015-11-26 11:25:35.954000000 Z content_type_id: country_key_facts revision: 1 title_internal: 'Chad: key facts' image_count: 2,066 images date_range: Mostly 5000 BC to AD 1700 main_areas: Tibesti Mountains, Ennedi Plateau techniques: Engravings, paintings main_themes: Boats, cattle, wild animals, inscriptions thematic_articles: - sys: id: 1KwPIcPzMga0YWq8ogEyCO created_at: !ruby/object:DateTime 2015-11-26 16:25:56.681000000 Z updated_at: !ruby/object:DateTime 2015-12-07 20:49:15.151000000 Z content_type_id: thematic revision: 5 title: 'Sailors on sandy seas: camels in Saharan rock art' slug: camels-in-saharan-rock-art lead_image: sys: id: 46X3vtG1faouSYYws0Aywu created_at: !ruby/object:DateTime 2015-11-26 16:07:51.521000000 Z updated_at: !ruby/object:DateTime 2019-02-12 02:30:35.572000000 Z title: View of camel salt caravan crossing the Ténéré desert. Niger. ©David Coulson/TARA description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3652083&partId=1&searchText=2013,2034.10379&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/46X3vtG1faouSYYws0Aywu/6ff8cc3f26c918c81157746e1b2b3131/Fig._1._Camel.jpg" chapters: - sys: id: 1Q7xHD856UsISuceGegaqI created_at: !ruby/object:DateTime 2015-11-26 16:19:29.618000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:19:29.618000000 Z content_type_id: chapter revision: 1 title_internal: 'Camels: thematic, chapter 1' body: 'If we were to choose a defining image for the Sahara Desert, it would probably depict an endless sea of yellow dunes under a blue sky and, off in the distance, a line of long-legged, humped animals whose profiles have become synonymous with deserts: the one-humped camel (or dromedary). Since its domestication, the camel’s resistance to heat and its ability to survive with small amounts of water and a diet of desert vegetation have made it a key animal for inhabitants of the Sahara, deeply bound to their economy, material culture and lifestyle.' - sys: id: 4p7wUbC6FyiEYsm8ukI0ES created_at: !ruby/object:DateTime 2015-11-26 16:09:23.136000000 Z updated_at: !ruby/object:DateTime 2019-02-12 02:30:19.986000000 Z content_type_id: image revision: 3 image: sys: id: 46X3vtG1faouSYYws0Aywu created_at: !ruby/object:DateTime 2015-11-26 16:07:51.521000000 Z updated_at: !ruby/object:DateTime 2019-02-12 02:30:35.572000000 Z title: View of camel salt caravan crossing the Ténéré desert. Niger. ©David Coulson/TARA description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3652083&partId=1&searchText=2013,2034.10379&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/46X3vtG1faouSYYws0Aywu/6ff8cc3f26c918c81157746e1b2b3131/Fig._1._Camel.jpg" caption: Camel salt caravan crossing the Ténéré desert in Niger. 2013,2034.10487 ©<NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3652360&partId=1&searchText=2013,2034.10487&page=1 - sys: id: 1LsXHHPAZaIoUksC2US08G created_at: !ruby/object:DateTime 2015-11-26 16:19:46.820000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:19:46.820000000 Z content_type_id: chapter revision: 1 title_internal: 'Camels: thematic, chapter 2' body: Yet, surprising as it seems, the camel is a relative newcomer to the Sahara – at least when compared to other domestic animals such as cattle, sheep, horses and donkeys. Although the process is not yet fully known, camels were domesticated in the Arabian Peninsula around the third millennium BC, and spread from there to the Middle East, North Africa and Somalia from the 1st century AD onwards. The steps of this process from Egypt to the Atlantic Ocean have been documented through many different historical sources, from Roman texts to sculptures or coins, but it is especially relevant in Saharan rock art, where camels became so abundant that they have given their name to a whole period. The depictions of camels provide an incredible amount of information about the life, culture and economy of the Berber and other nomadic communities from the beginnings of the Christian era to the Muslim conquest in the late years of the 7th century. - sys: id: j3q9XWFlMOMSK6kG2UWiG created_at: !ruby/object:DateTime 2015-11-26 16:10:00.029000000 Z updated_at: !ruby/object:DateTime 2018-05-17 14:21:07.255000000 Z content_type_id: image revision: 2 image: sys: id: 6afrRs4VLUS4iEG0iwEoua created_at: !ruby/object:DateTime 2015-11-26 16:07:34.273000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:34.273000000 Z title: EA26664 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6afrRs4VLUS4iEG0iwEoua/e00bb3c81c6c9b44b5e224f5a8ce33a2/EA26664.jpg" caption: Roman terracotta camel with harness, 1st – 3rd century AD, Egypt. British Museum 1891,0403.31 © Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?museumno=1891,0430.31&objectId=118725&partId=1 - sys: id: NxdAnazJaUkeMuyoSOy68 created_at: !ruby/object:DateTime 2015-11-26 16:20:03.948000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:20:03.948000000 Z content_type_id: chapter revision: 1 title_internal: 'Camels: thematic, chapter 3' body: 'What is it that makes camels so suited to deserts? It is not only their ability to transform the fat stored in their hump into water and energy, or their capacity to eat thorny bushes, acacia leaves and even fish and bones. Camels are also able to avoid perspiration by manipulating their core temperature, enduring fluctuations of up to six degrees that could be fatal for other mammals. They rehydrate very quickly, and some of their physical features (nostrils, eyebrows) have adapted to increase water conservation and protect the animals from dust and sand. All these capacities make camels uniquely suited to hot climates: in temperatures of 30-40 °C, they can spend up to 15 days without water. In addition, they are large animals, able to carry loads of up to 300kg, over long journeys across harsh environments. The pads on their feet have evolved so as to prevent them from sinking into the sand. It is not surprising that dromedaries are considered the ‘ships of the desert’, transporting people, commodities and goods through the vast territories of the Sahara.' - sys: id: 2KjIpAzb9Kw4O82Yi6kg2y created_at: !ruby/object:DateTime 2015-11-26 16:10:36.039000000 Z updated_at: !ruby/object:DateTime 2018-05-17 14:39:34.523000000 Z content_type_id: image revision: 2 image: sys: id: 6iaMmNK91YOU00S4gcgi6W created_at: !ruby/object:DateTime 2015-11-26 16:07:51.477000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:51.477000000 Z title: Af1937,0105.16 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6iaMmNK91YOU00S4gcgi6W/4a850695b34c1766d1ee5a06f61f2b36/Af1937_0105.16.jpg" caption: Clay female dromedary (possibly a toy), Somalia. British Museum Af1937,0105.16 © Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?assetId=1088379&objectId=590967&partId=1 - sys: id: 12mIwQ0wG2qWasw4wKQkO0 created_at: !ruby/object:DateTime 2015-11-26 16:11:00.578000000 Z updated_at: !ruby/object:DateTime 2018-05-17 14:45:29.810000000 Z content_type_id: image revision: 2 image: sys: id: 4jTR7LKYv6IiY8wkc2CIum created_at: !ruby/object:DateTime 2015-11-26 16:07:51.505000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:51.505000000 Z title: Fig. 4. Man description: url: "//images.ctfassets.net/xt8ne4gbbocd/4jTR7LKYv6IiY8wkc2CIum/3dbaa11c18703b33840a6cda2c2517f2/Fig._4._Man.jpg" caption: Man leading a camel train through the Ennedi Plateau, Chad. 2013,2034.6134 ©<NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3636989&partId=1&searchText=2013,2034.6134&page=1 - sys: id: 6UIdhB0rYsSQikE8Yom4G6 created_at: !ruby/object:DateTime 2015-11-26 16:20:29.219000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:20:29.219000000 Z content_type_id: chapter revision: 1 title_internal: 'Camels: thematic, chapter 4' body: As mentioned previously, camels came from the Arabian Peninsula through Egypt, where bone remains have been dated to the early 1st millennium BC. However, it took hundreds of years to move into the rest of North Africa due to the River Nile, which represented a major geographical and climatic barrier for these animals. The expansion began around the beginning of the Christian era, and probably took place both along the Mediterranean Sea and through the south of the Sahara. At this stage, it appears to have been very rapid, and during the following centuries camels became a key element in the North African societies. They were used mainly for riding, but also for transporting heavy goods and even for ploughing. Their milk, hair and meat were also used, improving the range of resources available to their herders. However, it seems that the large caravans that crossed the desert searching for gold, ivory or slaves came later, when the Muslim conquest of North Africa favoured the establishment of vast trade networks with the Sahel, the semi-arid region that lies south of the Sahara. - sys: id: YLb3uCAWcKm288oak4ukS created_at: !ruby/object:DateTime 2015-11-26 16:11:46.395000000 Z updated_at: !ruby/object:DateTime 2018-05-17 14:46:15.751000000 Z content_type_id: image revision: 2 image: sys: id: 5aJ9wYpcHe6SImauCSGoM8 created_at: !ruby/object:DateTime 2015-11-26 16:06:48.336000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:06:48.336000000 Z title: '1923,0401.850' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5aJ9wYpcHe6SImauCSGoM8/74efd37612ec798fd91c2a46c65587f7/1923_0401.850.jpg" caption: Glass paste gem imitating beryl, engraved with a short, bearded man leading a camel with a pack on its hump. Roman Empire, 1st – 3rd century AD. 1923,0401.850 ©Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=434529&partId=1&museumno=1923,0401.850&page=1 - sys: id: 3uitqbkcY8s8GCcicKkcI4 created_at: !ruby/object:DateTime 2015-11-26 16:20:45.582000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:20:45.582000000 Z content_type_id: chapter revision: 1 title_internal: 'Camels: thematic, chapter 5' body: Rock art can be extremely helpful in learning about the different ways in which camels were used in the first millennium AD. Images of camels are found in both engravings and paintings in red, white or – on rare occasions – black; sometimes the colours are combined to achieve a more impressive effect. They usually appear in groups, alongside humans, cattle and, occasionally, dogs and horses. Sometimes, even palm trees and houses are included to represent the oases where the animals were watered. Several of the scenes show female camels herded or taking care of their calves, showing the importance of camel-herding and breeding for the Libyan-Berber communities. - sys: id: 5OWosKxtUASWIO6IUii0EW created_at: !ruby/object:DateTime 2015-11-26 16:12:17.552000000 Z updated_at: !ruby/object:DateTime 2018-05-17 15:11:49.775000000 Z content_type_id: image revision: 2 image: sys: id: 3mY7XFQW6QY6KekSQm6SIu created_at: !ruby/object:DateTime 2015-11-26 16:06:48.343000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:06:48.343000000 Z title: '2013,2034.383' description: url: "//images.ctfassets.net/xt8ne4gbbocd/3mY7XFQW6QY6KekSQm6SIu/85c0b70ab40ead396c695fe493081801/2013_2034.383.jpg" caption: Painted scene of a village, depicting a herd or caravan of camels guided by riders and dogs. Wadi Teshuinat, Acacus Mountains, Libya. 2013,2034.383 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3579914&partId=1&museumno=2013,2034.383&page=1 - sys: id: 2Ocb7A3ig8OOkc2AAQIEmo created_at: !ruby/object:DateTime 2015-11-26 16:12:48.147000000 Z updated_at: !ruby/object:DateTime 2018-05-17 15:12:22.249000000 Z content_type_id: image revision: 2 image: sys: id: 2xR2nZml7mQAse8CgckCa created_at: !ruby/object:DateTime 2015-11-26 16:07:51.480000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:51.480000000 Z title: '2013,2034.5117' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2xR2nZml7mQAse8CgckCa/984e95b65ebdc647949d656cb08c0fc9/2013_2034.5117.jpg" caption: Engravings of a female camel with calves. Oued Djerat, Algeria. 2013,2034.5117 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3624292&partId=1&museumno=2013,2034.5117&page=1 - sys: id: 4iTHcZ38wwSyGK8UIqY2yQ created_at: !ruby/object:DateTime 2015-11-26 16:13:13.897000000 Z updated_at: !ruby/object:DateTime 2018-05-17 15:31:09.339000000 Z content_type_id: image revision: 2 image: sys: id: 1ecCbVeHUGa2CsYoYSQ4Sm created_at: !ruby/object:DateTime 2015-11-26 16:07:34.241000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:34.241000000 Z title: Fig. 8. Painted description: url: "//images.ctfassets.net/xt8ne4gbbocd/1ecCbVeHUGa2CsYoYSQ4Sm/21b2aebd215d0691482411608ad5682f/Fig._8._Painted.jpg" caption: " Painted scene of Libyan-Berber warriors riding camels, accompanied by infantry and cavalrymen. Kozen Pass, Chad. 2013,2034.7295 © <NAME>/TARA" col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3655154&partId=1&searchText=2013,2034.7295&page=1 - sys: id: 2zqiJv33OUM2eEMIK2042i created_at: !ruby/object:DateTime 2015-11-26 16:21:08.068000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:21:08.068000000 Z content_type_id: chapter revision: 1 title_internal: 'Camels: thematic, chapter 6' body: |- That camels were used to transport goods is obvious, and depictions of long lines of animals are common, sometimes with saddles on which to place the packs and ropes to tie the animals together. However, if rock art depictions are some indication of camel use, it seems that until the Muslim conquest the main function of one-humped camels was as mounts, often linked to war. The Sahara desert contains dozens of astonishingly detailed images of warriors riding camels, armed with spears, long swords and shields, sometimes accompanied by infantry soldiers and horsemen. Although camels are not as good as horses for use as war mounts (they are too tall and make insecure platforms for shooting arrows), they were undoubtedly very useful in raids – the most common type of war activity in the desert – as well as being a symbol of prestige, wealth and authority among the desert warriors, much as they still are today. Moreover, the extraordinary detail of some of the rock art paintings has provided inestimable help in understanding how (and why) camels were ridden in the 1st millennium AD. Unlike horses, donkeys or mules, one-humped camels present a major problem for riders: where to put the saddle. Although it might be assumed that the saddle should be placed over the hump, they can, in fact, also be positioned behind or in front of the hump, depending on the activity. It seems that the first saddles were placed behind the hump, but that position was unsuitable for fighting, quite uncomfortable, and unstable. Subsequently, a new saddle was invented in North Arabia around the 5th century BC: a framework of wood that rested over the hump and provided a stable platform on which to ride and fight more effectively. The North Arabian saddle led to a revolution in the domestication of one-humped camels, allowed a faster expansion of the use of these animals, and it is probably still the most used type of saddle today. - sys: id: 6dOm7ewqmA6oaM4cK4cy8c created_at: !ruby/object:DateTime 2015-11-26 16:14:25.900000000 Z updated_at: !ruby/object:DateTime 2018-05-17 15:31:33.078000000 Z content_type_id: image revision: 2 image: sys: id: 5qXuQrcnUQKm0qCqoCkuGI created_at: !ruby/object:DateTime 2015-11-26 16:06:48.345000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:06:48.345000000 Z title: As1974,29.17 description: url: "//images.ctfassets.net/xt8ne4gbbocd/5qXuQrcnUQKm0qCqoCkuGI/2b279eff2a6f42121ab0f6519d694a92/As1974_29.17.jpg" caption: North Arabian-style saddle, with a wooden framework designed to be put around the hump. Jordan. British Museum As1974,29.17 © Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3320111&partId=1&object=23696&page=1 - sys: id: 5jE9BeKCBUEK8Igg8kCkUO created_at: !ruby/object:DateTime 2015-11-26 16:21:27.156000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:21:27.156000000 Z content_type_id: chapter revision: 1 title_internal: 'Camels: thematic, chapter 7' body: 'Although North Arabian saddles are found throughout North Africa and are often depicted in rock art paintings, at some point a new kind of saddle was designed in North Africa: one placed in front of the hump, with the weight over the shoulders of the camel. This type of shoulder saddle allows the rider to control the camel with the feet and legs, thus improving the ride. Moreover, the rider is seated in a lower position and thus needs shorter spears and swords that can be brandished more easily, making warriors more efficient. This new kind of saddle, which is still used throughout North Africa today, appears only in the western half of the Sahara and is well represented in the rock art of Algeria, Niger and Mauritania. And it is not only saddles that are recognizable in Saharan rock art: harnesses, reins, whips or blankets are identifiable in the paintings and show astonishing similarities to those still used today by desert peoples.' - sys: id: 6yZaDQMr1Sc0sWgOG6MGQ8 created_at: !ruby/object:DateTime 2015-11-26 16:14:46.560000000 Z updated_at: !ruby/object:DateTime 2018-05-17 15:33:25.754000000 Z content_type_id: image revision: 2 image: sys: id: 40zIycUaTuIG06mgyaE20K created_at: !ruby/object:DateTime 2015-11-26 16:07:51.466000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:51.466000000 Z title: Fig. 10. Painting description: url: "//images.ctfassets.net/xt8ne4gbbocd/40zIycUaTuIG06mgyaE20K/1736927ffb5e2fc71d1f1ab04310a73f/Fig._10._Painting.jpg" caption: Painting of rider on a one-humped camel. Note the North Arabian saddle on the hump, similar to the example from Jordan above. Terkei, Ennedi plateau, Chad. 2013,2034.6568 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3640623&partId=1&searchText=2013,2034.6568&page=1 - sys: id: 5jHyVlfWXugI2acowekUGg created_at: !ruby/object:DateTime 2015-11-26 16:15:13.926000000 Z updated_at: !ruby/object:DateTime 2018-05-17 15:36:07.603000000 Z content_type_id: image revision: 2 image: sys: id: 6EvwTsiMO4qoiIY4gGCgIK created_at: !ruby/object:DateTime 2015-11-26 16:07:34.249000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:34.249000000 Z title: '2013,2034.4471' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6EvwTsiMO4qoiIY4gGCgIK/1db47ae083ff605b9533898d9d9fb10d/2013_2034.4471.jpg" caption: Camel-rider using a North African saddle (in front of the hump), surrounded by warriors with spears and swords, with Libyan-Berber graffiti. <NAME>, <NAME>. 2013,2034.4471 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3602860&partId=1&museumno=2013,2034.4471&page=1 - sys: id: 57goC8PzUs6G4UqeG0AgmW created_at: !ruby/object:DateTime 2015-11-26 16:16:51.920000000 Z updated_at: !ruby/object:DateTime 2019-02-12 02:33:53.275000000 Z content_type_id: image revision: 3 image: sys: id: 5JDO7LrdKMcSEOMEG8qsS8 created_at: !ruby/object:DateTime 2015-11-26 16:07:34.250000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:34.250000000 Z title: Fig. 12. Tuaregs description: url: "//images.ctfassets.net/xt8ne4gbbocd/5JDO7LrdKMcSEOMEG8qsS8/76cbecd637724d549db8a7a101553280/Fig._12._Tuaregs.jpg" caption: Tuaregs at Cura Salee, an annual meeting of desert peoples. Note the saddles in front of the hump and the camels' harnesses, similar to the rock paintings above such as the image from Terkei. Ingal, Northern Niger. 2013,2034.10523 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3652377&partId=1&searchText=2013,2034.10523&page=1 - sys: id: 3QPr46gQP6sQWswuSA2wog created_at: !ruby/object:DateTime 2015-11-26 16:21:50.767000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:21:50.767000000 Z content_type_id: chapter revision: 1 title_internal: 'Camels: thematic, chapter 8' body: Since their introduction to the Sahara during the first centuries of the Christian era, camels have become indispensable for desert communities, providing a method of transport for people and commodities, but also for their milk, meat and hair for weaving. They allowed the improvement of wide cultural and economic networks, transforming the Sahara into a key node linking the Mediterranean Sea with Sub-Saharan Africa. A symbol of wealth and prestige, the Libyan-Berber peoples recognized camels’ importance and expressed it through paintings and engravings across the desert, leaving a wonderful document of their societies. The painted images of camel-riders crossing the desert not only have an evocative presence, they are also perfect snapshots of a history that started two thousand years ago and seems as eternal as the Sahara. - sys: id: 54fiYzKXEQw0ggSyo0mk44 created_at: !ruby/object:DateTime 2015-11-26 16:17:13.884000000 Z updated_at: !ruby/object:DateTime 2018-05-17 16:01:13.379000000 Z content_type_id: image revision: 2 image: sys: id: 3idPZkkIKAOWCiKouQ8c8i created_at: !ruby/object:DateTime 2015-11-26 16:07:34.244000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:34.244000000 Z title: Fig. 13. Camel-riders description: url: "//images.ctfassets.net/xt8ne4gbbocd/3idPZkkIKAOWCiKouQ8c8i/4527b1eebe112ef9c38da1026e7540b3/Fig._13._Camel-riders.jpg" caption: Camel-riders galloping. Butress cave, Archael Guelta, Chad. 2013,2034.6077 ©<NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3637992&partId=1&searchText=2013,2034.6077&page=1 - sys: id: 1ymik3z5wMUEway6omqKQy created_at: !ruby/object:DateTime 2015-11-26 16:17:32.501000000 Z updated_at: !ruby/object:DateTime 2018-05-17 16:02:41.679000000 Z content_type_id: image revision: 2 image: sys: id: 4Y85f5QkVGQiuYEaA2OSUC created_at: !ruby/object:DateTime 2015-11-26 16:07:06.194000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:06.194000000 Z title: Fig. 14. Tuareg description: url: "//images.ctfassets.net/xt8ne4gbbocd/4Y85f5QkVGQiuYEaA2OSUC/4fbca027ed170b221daefdff0ae7d754/Fig._14._Tuareg.jpg" caption: Tuareg rider galloping at the Cure Salee meeting. Ingal, northern Niger. 2013,2034.10528 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3652371&partId=1&searchText=2013,2034.10528&page=1 background_images: - sys: id: 3mhr7uvrpesmaUeI4Aiwau created_at: !ruby/object:DateTime 2015-12-07 18:13:48.396000000 Z updated_at: !ruby/object:DateTime 2015-12-07 18:13:48.396000000 Z title: CHAENP0340003 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3mhr7uvrpesmaUeI4Aiwau/65c691f09cd60bb7aa08457e18eaa624/CHAENP0340003_1_.JPG" - sys: id: BPzulf3QNqMC4Iqs4EoCG created_at: !ruby/object:DateTime 2015-12-07 18:13:31.094000000 Z updated_at: !ruby/object:DateTime 2015-12-07 18:13:31.094000000 Z title: CHAENP0340001 description: url: "//images.ctfassets.net/xt8ne4gbbocd/BPzulf3QNqMC4Iqs4EoCG/356b921099bfccf59008b69060d20d75/CHAENP0340001_1_.JPG" - sys: id: 7oNFGUa6g8qSweyAyyiCAe created_at: !ruby/object:DateTime 2015-11-26 18:11:30.861000000 Z updated_at: !ruby/object:DateTime 2015-12-07 20:51:34.879000000 Z content_type_id: thematic revision: 4 title: The domesticated horse in northern African rock art slug: the-domesticated-horse lead_image: sys: id: n2MxgdjbMW2gm0IoOKkCU created_at: !ruby/object:DateTime 2015-11-26 17:51:43.133000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:43.133000000 Z title: Fig. 1. Painted horse description: url: "//images.ctfassets.net/xt8ne4gbbocd/n2MxgdjbMW2gm0IoOKkCU/e2c7369ef1e4ab11c71023a769f8fe0d/Fig._1._Painted_horse.jpg" chapters: - sys: id: 27bcd1mylKoMWiCQ2KuKMa created_at: !ruby/object:DateTime 2015-11-26 18:00:19.777000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:00:19.777000000 Z content_type_id: chapter revision: 1 title_internal: 'Thematic: horse, chapter 1' body: Throughout northern Africa, there is a wealth of rock art depicting the domestic horse and its various uses, providing valuable evidence for the uses of horses at various times in history, as well as a testament to their importance to Saharan peoples. - sys: id: 2EbfpTN9L6E0sYmuGyiaec created_at: !ruby/object:DateTime 2015-11-26 17:52:26.605000000 Z updated_at: !ruby/object:DateTime 2018-05-15 16:39:29.412000000 Z content_type_id: image revision: 2 image: sys: id: n2MxgdjbMW2gm0IoOKkCU created_at: !ruby/object:DateTime 2015-11-26 17:51:43.133000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:43.133000000 Z title: Fig. 1. Painted horse description: url: "//images.ctfassets.net/xt8ne4gbbocd/n2MxgdjbMW2gm0IoOKkCU/e2c7369ef1e4ab11c71023a769f8fe0d/Fig._1._Painted_horse.jpg" caption: 'Painted horse and rider, Ennedi Plateau, Chad. 2013,2034.6406 © TARA/David Coulson. ' col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3641775&partId=1&searchText=2013,2034.6406&page=1 - sys: id: 4QexWBEVXiAksikIK6g2S4 created_at: !ruby/object:DateTime 2015-11-26 18:00:49.116000000 Z updated_at: !ruby/object:DateTime 2018-05-15 16:40:28.446000000 Z content_type_id: chapter revision: 2 title: Horses and chariots title_internal: 'Thematic: horse, chapter 2' body: The first introduction of the domestic horse to Ancient Egypt- and thereby to Africa- is usually cited at around 1600 BC, linked with the arrival in Egypt of the Hyksos, a group from the Levant who ruled much of Northern Egypt during the Second Intermediate Period. By this point, horses had probably only been domesticated for about 2,000 years, but with the advent of the chariot after the 3rd millennium BC in Mesopotamia, the horse proved to be a valuable martial asset in the ancient world. One of the first clear records of the use of horses and chariots in battle in Africa is found in depictions from the mortuary complex of the Pharaoh Ahmose at Abydos from around 1525 BC, showing their use by Egyptians in defeating the Hyksos, and horses feature prominently in later Egyptian art. - sys: id: 22x06a7DteI0C2U6w6oKes created_at: !ruby/object:DateTime 2015-11-26 17:52:52.323000000 Z updated_at: !ruby/object:DateTime 2018-05-15 16:40:52.214000000 Z content_type_id: image revision: 2 image: sys: id: 1AZD3AxiUwwoYUWSWY8MGW created_at: !ruby/object:DateTime 2015-11-26 17:51:50.284000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:50.284000000 Z title: '2013,2034.1001' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1AZD3AxiUwwoYUWSWY8MGW/b68bd24c9b19c5c8c7752bfb75a5db0e/2013_2034.1001.jpg" caption: Painted two-horse chariot, Acacus Mountains, Libya. 2013,2034.1001 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3588526&partId=1&people=197356&museumno=2013,2034.1001&page=1 - sys: id: 1voXfvqIcQkgUYqq4w8isQ created_at: !ruby/object:DateTime 2015-11-26 18:01:15.173000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:01:15.173000000 Z content_type_id: chapter revision: 1 title_internal: 'Thematic: horse, chapter 3' body: 'Some of the most renowned images of horses in Saharan rock art are also those of chariot teams: in particular, those of the so-called ‘flying gallop’ style chariot pictures, from the Tassili n’Ajjer and Acacus mountains in modern Algeria and Libya. These distinctive images are characterised by depictions of one or more horses pulling a chariot with their legs outstretched in a stylised manner and are sometimes attributed to the Garamantes, a group who were a local power in the central Sahara from about 500 BC-700 AD. But the Ajjer Plateau is over a thousand miles from the Nile- how and when did the horse and chariot first make their way across the Western Desert to the rest of North Africa in the first place? Egyptian accounts indicate that by the 11th century BC Libyans (people living on the north African coast around the border of modern Egypt and Libya) were using chariots in war. Classical sources later write about the chariots of the Garamantes and of chariot use by peoples of the far western Sahara continuing into the 1st century BC, by which time the chariot horse had largely been eclipsed in war by the cavalry mount.' - sys: id: LWROS2FhUkywWI60eQYIy created_at: !ruby/object:DateTime 2015-11-26 17:53:42.845000000 Z updated_at: !ruby/object:DateTime 2018-05-15 16:41:33.841000000 Z content_type_id: image revision: 2 image: sys: id: 6N6BF79qk8EUygwkIgwcce created_at: !ruby/object:DateTime 2015-11-26 17:51:44.708000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:44.708000000 Z title: '2013,2034.4574' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6N6BF79qk8EUygwkIgwcce/ac95a5214a326794542e0707c0d819d7/2013_2034.4574.jpg" caption: Painted human figure and horse. Tarssed Jebest, Tassili n’Ajjer, Algeria. Horse displays Arabian breed-type characteristics such as dished face and high tail carriage. 2013,2034.4574 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3603790&partId=1&people=197356&museumno=2013,2034.4574+&page=1 - sys: id: 6eaH84QdUs46sEQoSmAG2u created_at: !ruby/object:DateTime 2015-11-26 18:01:48.835000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:01:48.835000000 Z content_type_id: chapter revision: 1 title: Horse Riding title_internal: 'Thematic: horse, chapter 4' body: As well as the unique iconography of rock art chariot depictions, there are also numerous paintings and engravings across northern Africa of people riding horses. Riding may have been practiced since the earliest times of horse domestication, though the earliest definitive depictions of horses being ridden come from the Middle East in the late 3rd and early 2nd millennia BC. Images of horses and riders in rock art occur in various areas of Morocco, Egypt and Sudan and are particularly notable in the Ennedi region of Chad and the Adrar and Tagant plateaus in Mauritania (interestingly, however, no definite images of horses are known in the Gilf Kebir/Jebel Uweinat area at the border of Egypt, Sudan and Libya). - sys: id: 6LTzLWMCTSak4IIukAAQMa created_at: !ruby/object:DateTime 2015-11-26 17:54:23.846000000 Z updated_at: !ruby/object:DateTime 2018-05-15 16:41:52.743000000 Z content_type_id: image revision: 2 image: sys: id: 4NdhGNLc9yEck4My4uQwIo created_at: !ruby/object:DateTime 2015-11-26 17:51:43.495000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:43.495000000 Z title: ME22958 description: url: "//images.ctfassets.net/xt8ne4gbbocd/4NdhGNLc9yEck4My4uQwIo/703945afad6a8e3c97d10b09c487381c/ME22958.jpg" caption: Terracotta mould of man on horseback, Old Babylonian, Mesopotamia 2000-1600 BC. One of the oldest known depictions of horse riding in the world. British Museum ME22958 © Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=388860&partId=1&people=197356&museumno=22958&page=1 - sys: id: 5YkSCzujy8o08yuomIu6Ei created_at: !ruby/object:DateTime 2015-11-26 17:54:43.227000000 Z updated_at: !ruby/object:DateTime 2018-05-16 11:12:34.068000000 Z content_type_id: image revision: 2 image: sys: id: 1tpjS4kZZ6YoeiWeIi8I4C created_at: !ruby/object:DateTime 2015-11-26 17:51:43.188000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:43.188000000 Z title: Fig. 5. Painted ‘bitriangular’ description: url: "//images.ctfassets.net/xt8ne4gbbocd/1tpjS4kZZ6YoeiWeIi8I4C/c798c1afb41006855c34363ec2b54557/Fig._5._Painted____bitriangular___.jpg" caption: Painted ‘bi-triangular’ horse and rider with saddle. Oued Jrid, Assaba, Mauritania. 2013,2034.12285 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3645983&partId=1&searchText=2013,2034.12285&page=1 - sys: id: 1vZDFfKXU0US2qkuaikG8m created_at: !ruby/object:DateTime 2015-11-26 18:02:13.433000000 Z updated_at: !ruby/object:DateTime 2018-05-16 11:14:56.468000000 Z content_type_id: chapter revision: 2 title_internal: 'Thematic: horse, chapter 5' body: Traditional chronologies for Saharan rock art areas tend to place depictions of ridden horses chronologically after those of horses and chariots, and in general use horse depictions to categorise regional stylistic periods of rock art according to broad date boundaries. As such, in most places, the ‘horse’ rock art period is usually said to cover about a thousand years from the end of the 2nd millennium BC. It is then considered to be succeeded by a ‘camel’ period, where the appearance of images of dromedaries – known only to have been introduced to the eastern Sahara from Arabia at the end of the 1st century BC – reflects the next momentous influx of a beast of burden to the area and thus a new dating parameter ([read more about depictions of camels in the Sahara](https://africanrockart.britishmuseum.org/thematic/camels-in-saharan-rock-art/)). However, such simplistic categorisation can be misleading. For one thing, although mounting horses certainly gained popularity over driving them, it is not always clear that depictions of ridden horses are not contemporary with those of chariots. Further, the horse remained an important martial tool after the use of war-chariots declined. Even after the introduction of the camel, there are several apparently contemporary depictions featuring both horse and camel riders. - sys: id: 2gaHPgtyEwsyQcUqEIaGaq created_at: !ruby/object:DateTime 2015-11-26 17:55:29.704000000 Z updated_at: !ruby/object:DateTime 2018-05-16 11:32:44.364000000 Z content_type_id: image revision: 3 image: sys: id: 6quML2y0nuYgSaeG0GGYy4 created_at: !ruby/object:DateTime 2015-11-26 17:51:50.292000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:50.292000000 Z title: '2013,2034.5739' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6quML2y0nuYgSaeG0GGYy4/7f48ae9c550dd6b4f0e80b8da10a3da6/2013_2034.5739.jpg" caption: Engraved ridden horse and camel. Draa Valley, Morocco. 2013,2034.5739 ©TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3619780&partId=1&people=197356&museumno=2013,2034.5739+&page=1 - sys: id: 583LKSbz9SSg00uwsqquAG created_at: !ruby/object:DateTime 2015-11-26 18:02:41.576000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:02:41.576000000 Z content_type_id: chapter revision: 1 title: Berber Horses title_internal: 'Thematic: horse, chapter 6' body: As the more manoeuvrable rider rose in popularity against the chariot as a weapon of war, historical reports from classical authors like Strabo tell us of the prowess of African horsemen such as the cavalry of the Numidians, a Berber group that allied with Carthage against the Romans in the 3rd century BC. Berber peoples would remain heavily associated with horse breeding and riding, and the later rock art of Mauritania has been attributed to Berber horsemen, or the sight of them. Although horses may already have reached the areas of modern Mauritania and Mali by this point, archaeological evidence does not confirm their presence in these south-westerly regions of the Sahara until much later, in the mid-1st millennium AD, and it has been suggested that some of the horse paintings in Mauritania may be as recent as 16th century. - sys: id: 7zrBlvCEGkW86Qm8k2GQAK created_at: !ruby/object:DateTime 2015-11-26 17:56:24.617000000 Z updated_at: !ruby/object:DateTime 2018-05-16 11:16:52.557000000 Z content_type_id: image revision: 2 image: sys: id: uOFcng0Q0gU8WG8kI2kyy created_at: !ruby/object:DateTime 2015-11-26 17:51:44.717000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:44.717000000 Z title: '2013,2034.5202' description: url: "//images.ctfassets.net/xt8ne4gbbocd/uOFcng0Q0gU8WG8kI2kyy/7fba0330e151fc416d62333f3093d950/2013_2034.5202.jpg" caption: Engraved horses and riders surrounded by Libyan-Berber script. Oued Djerat, Algeria. These images appear to depict riders using Arab-style saddles and stirrups, thus making them probably no older than 7th c. AD. 2013,2034.5202 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3624404&partId=1&people=197356&museumno=2013,2034.5202&page=1 - sys: id: 45vpX8SP7aGeOS0qGaoo4a created_at: !ruby/object:DateTime 2015-11-26 18:03:14.279000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:03:14.279000000 Z content_type_id: chapter revision: 1 title_internal: 'Thematic: horse, chapter 7' body: 'Certainly, from the 14th century AD, horses became a key commodity in trans-Saharan trade routes and became items of great military value in West Africa following the introduction of equipment such as saddles with structured trees (frames). Indeed, discernible images of such accoutrements in Saharan rock art can help to date it following the likely introduction of the equipment to the area: for example, the clear depiction of saddles suggests an image to be no older than the 1st century AD; images including stirrups are even more recent.' - sys: id: 7GeTQBofPamw0GeEAuGGee created_at: !ruby/object:DateTime 2015-11-26 17:56:57.851000000 Z updated_at: !ruby/object:DateTime 2018-05-16 11:29:02.520000000 Z content_type_id: image revision: 2 image: sys: id: 5MaSKooQvYssI4us8G0MyO created_at: !ruby/object:DateTime 2015-11-26 17:51:43.501000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:43.501000000 Z title: RRM12824 description: url: "//images.ctfassets.net/xt8ne4gbbocd/5MaSKooQvYssI4us8G0MyO/8c3a7c2d372f2c48a868d60201909932/RRM12824.jpg" caption: 19th-century Moroccan stirrups with typical curved base of the type possibly visible in the image above. 1939,0311.7-8 © Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=217451&partId=1&page=1 - sys: id: 6mNtqnqaEE2geSkU0IiYYe created_at: !ruby/object:DateTime 2015-11-26 18:03:32.195000000 Z updated_at: !ruby/object:DateTime 2018-05-16 11:29:50.228000000 Z content_type_id: chapter revision: 2 title_internal: 'Thematic: horse, chapter 8' body: 'Another intriguing possibility is that of gaining clues on the origins of modern horse breeds from rock art, in particular the ancient Barb breed native to the Maghreb, where it is still bred. Ancient Mesopotamian horses were generally depicted as heavily-built, and it has been suggested that the basic type for the delicate Arabian horse, with its dished (concave) facial profile and high-set tail, may have been developed in north-east Africa prior to its subsequent appearance and cultivation in Arabia, and that these features may be observed in Ancient Egyptian images from the New Kingdom. Likewise, there is the possibility that some of the more naturalistic paintings from the central Sahara show the similarly gracile features of the progenitors of the Barb, distinguishable from the Arab by its straight profile and low-set tail. Like the Arab, the Barb is a desert horse: hardy, sure-footed and able to withstand great heat; it is recognised as an ancient breed with an important genetic legacy, both in the ancestry of the Iberian horses later used throughout the Americas, and that of the modern racing thoroughbred.' - sys: id: 3OM1XJI6ruwGOwwmkKOKaY created_at: !ruby/object:DateTime 2015-11-26 17:57:25.145000000 Z updated_at: !ruby/object:DateTime 2018-05-16 11:30:30.915000000 Z content_type_id: image revision: 2 image: sys: id: 6ZmNhZjLCoQSEIYKIYUUuk created_at: !ruby/object:DateTime 2015-11-26 17:51:50.293000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:50.293000000 Z title: '2013,2034.1452' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6ZmNhZjLCoQSEIYKIYUUuk/45bbff5b29985eb19679e1e513499d6b/2013_2034.1452.jpg" caption: Engraved horses and riders, Awis, Acacus Mountains, Libya. High head carriage and full rumps suggest Arabian/Barb breed type features. Riders have been obscured. 2013,2034.1452 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3592678&partId=1&people=197356&museumno=2013,2034.1452&page=1 - sys: id: 40E0pTCrUIkk00uGWsus4M created_at: !ruby/object:DateTime 2015-11-26 17:57:49.497000000 Z updated_at: !ruby/object:DateTime 2018-05-16 11:33:55.443000000 Z content_type_id: image revision: 2 image: sys: id: 5mbJWrbZV6aQQOyamKMqIa created_at: !ruby/object:DateTime 2015-11-26 17:51:43.468000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:43.468000000 Z title: Fig. 10. Barb horses description: url: "//images.ctfassets.net/xt8ne4gbbocd/5mbJWrbZV6aQQOyamKMqIa/87f29480513be0a531e0a93b51f9eae5/Fig._10._Barb_horses.jpg" caption: Barb horses ridden at a festival in Agadir, Morocco. ©Notwist (Wikimedia Commons) col_link: https://commons.wikimedia.org/wiki/File:Berber_warriors_show.JPG - sys: id: 3z5YSVu9y8caY6AoYWge2q created_at: !ruby/object:DateTime 2015-11-26 18:04:02.770000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:04:02.770000000 Z content_type_id: chapter revision: 1 title: The symbolism of the horse title_internal: 'Thematic: horse, chapter 9' body: However, caution must be taken in drawing such comparisons based on morphology alone, especially given the gulf of time that has elapsed and the relative paucity of ‘naturalistic’ rock art images. Indeed, there is huge diversity of horse depictions throughout northern Africa, with some forms highly schematic. This variation is not only in style – and, as previously noted, in time period and geography – but also in context, as of course images of one subject cannot be divorced from the other images around them, on whichever surface has been chosen, and are integral to these surroundings. - sys: id: 1FRP1Z2hyQEWUSOoKqgic2 created_at: !ruby/object:DateTime 2015-11-26 17:58:21.234000000 Z updated_at: !ruby/object:DateTime 2019-02-21 15:41:39.821000000 Z content_type_id: image revision: 2 image: sys: id: 4EatwZfN72waIquQqWEeOs created_at: !ruby/object:DateTime 2015-11-26 17:51:43.121000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:43.121000000 Z title: '2013,2034.11147' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4EatwZfN72waIquQqWEeOs/d793f6266f2ff486e0e99256c2c0ca39/2013_2034.11147.jpg" caption: Engraved ‘Libyan Warrior-style’ figure with horse. Indakatte, Western Aïr Mountains, Niger. 2013,2034.11147 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3637713&partId=1&people=197356&museumno=2013,2034.11147+&page=1 - sys: id: 45pI4ivRk4IM6gaG40gUU0 created_at: !ruby/object:DateTime 2015-11-26 17:58:41.308000000 Z updated_at: !ruby/object:DateTime 2019-02-21 15:41:59.784000000 Z content_type_id: image revision: 2 image: sys: id: 2FcYImmyd2YuqMKQMwAM0s created_at: !ruby/object:DateTime 2015-11-26 17:51:43.117000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:43.117000000 Z title: Fig. 12. Human figure description: url: "//images.ctfassets.net/xt8ne4gbbocd/2FcYImmyd2YuqMKQMwAM0s/e48fda8e2a23b12e6afde5c560c3f164/Fig._12._Human_figure.jpg" caption: Human figure painted over by horse to appear mounted (digitally enhanced image). © TARA/<NAME> - sys: id: 54hoc6Htwck8eyewsa6kA8 created_at: !ruby/object:DateTime 2015-11-26 18:04:26.929000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:04:26.929000000 Z content_type_id: chapter revision: 1 title_internal: 'Thematic: horse, chapter 10' body: The nature of the depictions in this sense speaks intriguingly of the apparent symbolism and implied value of the horse image in different cultural contexts. Where some Tassilian horses are delicately painted in lifelike detail, the stockier images of horses associated with the so-called ‘Libyan Warrior’ style petroglyphs of the Aïr mountains and Adrar des Ifoghas in Niger and Mali appear more as symbolic accoutrements to the central human figures and tend not to be shown as ridden. By contrast, there are paintings in the Ennedi plateau of Chad where galloping horse figures have clearly been painted over existing walking human figures to make them appear as if riding. - sys: id: 4XMm1Mdm7Y0QacMuy44EKa created_at: !ruby/object:DateTime 2015-11-26 17:59:06.184000000 Z updated_at: !ruby/object:DateTime 2019-02-21 15:42:27.444000000 Z content_type_id: image revision: 2 image: sys: id: 21xnJrk3dKwW6uSSkGumMS created_at: !ruby/object:DateTime 2015-11-26 17:51:44.697000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:44.697000000 Z title: '2013,2034.6297' description: url: "//images.ctfassets.net/xt8ne4gbbocd/21xnJrk3dKwW6uSSkGumMS/698c254a9a10c5a9a56d69e0525bca83/2013_2034.6297.jpg" caption: Engraved horse, <NAME>, Ennedi Plateau, Chad. 2013,2034.6297 © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3637529&partId=1&people=197356&museumno=2013,2034.6297&page=1 - sys: id: 4rB9FCopjOCC4iA2wOG48w created_at: !ruby/object:DateTime 2015-11-26 17:59:26.549000000 Z updated_at: !ruby/object:DateTime 2019-02-21 15:43:34.211000000 Z content_type_id: image revision: 2 image: sys: id: 3PfHuSbYGcqeo2U4AEKsmM created_at: !ruby/object:DateTime 2015-11-26 17:51:43.196000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:43.196000000 Z title: Fig. 14. Engraved horse description: url: "//images.ctfassets.net/xt8ne4gbbocd/3PfHuSbYGcqeo2U4AEKsmM/33a068fa954954fd3b9b446c943e0791/Fig._14._Engraved_horse.jpg" caption: Engraved horse, Eastern Aïr Mountains. 2013,2034.9421 ©TARA/David Coulson. col_link: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3640574&partId=1&searchText=2013,2034.9421&page=1 - sys: id: 6tFSQzFupywiK6aESCgCia created_at: !ruby/object:DateTime 2015-11-26 18:04:56.612000000 Z updated_at: !ruby/object:DateTime 2019-02-21 15:47:26.838000000 Z content_type_id: chapter revision: 2 title_internal: 'Thematic: horse, chapter 11' body: |- In each of these cases, the original symbolic intent of the artists have been lost to time, but with these horse depictions, as with so much African rock art imagery, there is great scope for further future analysis. Particularly intriguing, for example, are the striking stylistic similarities in horse depictions across great distances, such the horse depictions with bi-triangular bodies (see above), or with fishbone-style tails which may be found almost two thousand miles apart in Chad and Mauritania. Whatever the myriad circumstances and significances of the images, it is clear that following its introduction to the continent, the hardy and surefooted desert horse’s usefulness for draught, transport and fighting purposes transformed the societies which used it and gave it a powerful symbolic value. - sys: id: 2P6ERbclfOIcGEgI6e0IUq created_at: !ruby/object:DateTime 2015-11-26 17:59:46.042000000 Z updated_at: !ruby/object:DateTime 2019-02-21 15:45:12.419000000 Z content_type_id: image revision: 2 image: sys: id: 3UXc5NiGTYQcmu2yuU42g created_at: !ruby/object:DateTime 2015-11-26 17:51:43.128000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:43.128000000 Z title: Fig. 15. Painted horse, Terkei description: url: "//images.ctfassets.net/xt8ne4gbbocd/3UXc5NiGTYQcmu2yuU42g/7586f05e83f708ca9d9fca693ae0cd83/Fig._15._Painted_horse__Terkei.jpg" caption: Painted horse, Terkei, En<NAME>, Chad. 2013,2034.6537 © TARA/David Coulson col_link: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3640682&partId=1&searchText=2013,2034.6537&page=1 citations: - sys: id: 32AXGC1EcoSi4KcogoY2qu created_at: !ruby/object:DateTime 2015-11-26 17:51:20.602000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:20.602000000 Z content_type_id: citation revision: 1 citation_line: "<NAME>. & <NAME>. 2000, *The Origins and Development of African Livestock: archaeology, genetics, linguistics and ethnography*. London; New York, NY: UCL Press\n \n<NAME>., <NAME>., <NAME>., 2012. *The Horse: From Arabia to Royal Ascot*. London: British Museum Press\n \nLaw, R., 1980. *The Horse in West African History*. Oxford: Oxford University Press\n \nHachid, M. 2000. *Les Premieres Berbères*. Aix-en-Provence: Edisud\n \nLhote, H. 1952. 'Le cheval et le chameau dans les peintures et gravures rupestres du Sahara', *Bulletin de l'Institut franç ais de l'Afrique noire* 15: 1138-228\n \nOlsen, <NAME>. & Culbertson, C. 2010, *A gift from the desert: the art, history, and culture of the Arabian horse*. Lexington, KY: Kentucky Horse Park\n\n" background_images: - sys: id: 2avgKlHUm8CauWie6sKecA created_at: !ruby/object:DateTime 2015-12-07 18:44:31.346000000 Z updated_at: !ruby/object:DateTime 2015-12-07 18:44:31.346000000 Z title: EAF 141485 description: url: "//images.ctfassets.net/xt8ne4gbbocd/2avgKlHUm8CauWie6sKecA/cf02168ca83c922f27eca33f16e8cc90/EAF_141485.jpg" - sys: id: 1wtaUDwbSk4MiyGiISE6i8 created_at: !ruby/object:DateTime 2015-12-07 18:43:51.804000000 Z updated_at: !ruby/object:DateTime 2015-12-07 18:43:51.804000000 Z title: 01522751 001 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1wtaUDwbSk4MiyGiISE6i8/5918544d0289f9c4b2b4724f4cda7a2d/01522751_001.jpg" country_introduction: sys: id: 9vW3Qgse2siOmgwqC80ia created_at: !ruby/object:DateTime 2015-11-26 15:14:49.211000000 Z updated_at: !ruby/object:DateTime 2015-12-07 13:40:13.544000000 Z content_type_id: country_information revision: 2 title: 'Chad: country introduction' chapters: - sys: id: 3mkFTqLZTO0WuMMQkIiAyy created_at: !ruby/object:DateTime 2015-11-26 15:05:47.745000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:05:47.745000000 Z content_type_id: chapter revision: 1 title: Introduction title_internal: 'Chad: country, chapter 1' body: 'Located in the centre of North Africa, landlocked Chad stretches from the Sahara Desert in the north to the savannah in the south. The country boasts thousands of rock engravings and paintings located in two main areas: the Ennedi Plateau and the Tibesti Mountains, both to the north. The depictions – the oldest of which date back to the fifth millennium BC – represent wild animals, cattle and human figures. Paintings of highly detailed riders on camels and horses are especially numerous, as are groups of people around huts. Chadian rock art is particularly well known for its variety of local styles, and it includes some of the richest examples of Saharan rock art.' - sys: id: 1BFShW54yQI6k6ksQcuYSE created_at: !ruby/object:DateTime 2015-11-26 14:55:32.628000000 Z updated_at: !ruby/object:DateTime 2015-11-26 14:55:32.628000000 Z content_type_id: image revision: 1 image: sys: id: 47ocQmZwI8iOE4Sskq8IeE created_at: !ruby/object:DateTime 2015-11-26 13:20:23.164000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:11:47.535000000 Z title: '2013,2034.6155' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3637041&partId=1&searchText=2013,2034.6155&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/47ocQmZwI8iOE4Sskq8IeE/8ce5836027971e7b02317274015177ac/2013_2034.6155.jpg" caption: Engravings of human figures from <NAME>. Ennedi Plateau, Chad. 2013,2034.6155 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3637041&partId=1&people=197356&page=1 - sys: id: 6PPrV1eMH6u0scIwUiGGS2 created_at: !ruby/object:DateTime 2015-11-26 14:58:20.362000000 Z updated_at: !ruby/object:DateTime 2015-11-26 14:58:20.362000000 Z content_type_id: image revision: 1 image: sys: id: V66nfuesIoQGsMw2ugcwk created_at: !ruby/object:DateTime 2015-11-26 13:20:23.561000000 Z updated_at: !ruby/object:DateTime 2015-11-26 13:20:23.561000000 Z title: '2013,2034.6451' description: url: "//images.ctfassets.net/xt8ne4gbbocd/V66nfuesIoQGsMw2ugcwk/feb663001d1372a237275aa64bc471ed/2013_2034.6451.jpg" caption: Rider on a camel holding spear, dagger and shield. Camel Period, Ennedi Plateau, Chad. 2013,2034.6451 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3641488&partId=1&searchText=2013,2034.6451&page=1 - sys: id: 7vX4pbFT3iCsEuQIqiq0gY created_at: !ruby/object:DateTime 2015-11-26 15:08:11.474000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:08:11.474000000 Z content_type_id: chapter revision: 1 title: Geography and rock art distribution title_internal: 'Chad: country, chapter 2' body: 'The north-south orientation of Chad''s elongated shape means it is divided into several different climatic zones: the northern part belongs to the Sahara Desert, while the central area is included in the Sahel border (the semi-arid region south of the Sahara). The southern third of the country is characterized by a more fertile savannah. The Ennedi Plateau and Tibesti mountains contain thousands of pieces of rock art, including some of the most famous examples in the Sahara. The Ennedi Plateau is located at the north-eastern corner of Chad, on the southern edge of the Sahara Desert. It is a sandstone massif carved by erosion in a series of superimposed terraces, alternating plains and ragged cliffs crossed by wadis (seasonal rivers). Unlike other areas in the Sahara with rock art engravings or paintings, the Ennedi Plateau receives rain regularly – if sparsely – during the summer, making it a more benign environment for human life than other areas with significant rock art to the north, such as the Messak plateau or the Tassili Mountains in Libya and Algeria.' - sys: id: h6vM4an4K42COIiQG8A6y created_at: !ruby/object:DateTime 2015-11-26 14:59:35.937000000 Z updated_at: !ruby/object:DateTime 2017-01-09 17:10:44.651000000 Z content_type_id: image revision: 2 image: sys: id: 401K6ww8asemkaCySqeci created_at: !ruby/object:DateTime 2015-11-26 13:20:23.173000000 Z updated_at: !ruby/object:DateTime 2015-11-26 13:20:23.173000000 Z title: '2013,2034.6322' description: url: "//images.ctfassets.net/xt8ne4gbbocd/401K6ww8asemkaCySqeci/9c64bd46729be1bcc2c4a0a8fdd61a1c/2013_2034.6322.jpg" caption: View of the semi-desert plain surrounding the Ennedi Plateau (seen in the background). 2013,2034.6770 © TARA/<NAME> col_link: http://bit.ly/2jvhIgV - sys: id: 31nXCnwZBC0EcoEAuUyOqG created_at: !ruby/object:DateTime 2015-11-26 15:08:48.316000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:08:48.316000000 Z content_type_id: chapter revision: 1 title_internal: 'Chad: country, chapter 3' body: 'The Tibesti Mountains are situated at the north-western corner of Chad, and partly extend into Libya. The central area of the Tibesti Mountains is volcanic in origin, with one third of the range covered by five volcanoes. This has resulted in vast plateaux as well as fumaroles, sulphur and natron deposits and other geological formations. The erosion has shaped large canyons where wadis flow irregularly, and where most of the rock art depictions are situated. Paintings and engravings are common in both regions: the former are more often found in the Ennedi Plateau; the latter are predominant in the Tibesti Mountains.' - sys: id: 5g8chby9ugKc6igkYYyW6q created_at: !ruby/object:DateTime 2015-11-26 15:00:20.104000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:00:20.104000000 Z content_type_id: image revision: 1 image: sys: id: 1AS5ngxVRGWeAaKemYyOyo created_at: !ruby/object:DateTime 2015-11-26 13:20:23.225000000 Z updated_at: !ruby/object:DateTime 2015-11-26 13:20:23.225000000 Z title: '2013,2034.7259' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1AS5ngxVRGWeAaKemYyOyo/ab561407686a2a37d59602f6b05978d3/2013_2034.7259.jpg" caption: View of the Tibesti Mountains. 2013,2034.7259 © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3655202&partId=1&searchText=2013,2034.7259&page=1 - sys: id: 1YrTJ2zm4ow64uAMcWUI4c created_at: !ruby/object:DateTime 2015-11-26 15:10:44.568000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:10:44.568000000 Z content_type_id: chapter revision: 1 title: Research history title_internal: 'Chad: country, chapter 4' body: |- Different areas of Chad have been subject to varying trajectories of research. In the Tibesti Mountains, rock art was known to Europeans as early as 1869, although it was between the 1910s and 1930s that the first studies started to be carried out, by <NAME>. However, the main boost in research came in the 1950s and 1960s thanks to the work of <NAME>. Over the last 50 years, researchers have found thousands of depictions throughout the region, most of them engravings, although paintings are also well represented. In the case of the Ennedi Plateau, its isolated position far from the main trade routes made its rock art unknown outside the area until the 1930s. During this decade, Burthe d’Annelet brought attention to the art, and De Saint-Floris published the first paper on the subject. The main effort to document this rock art came in 1956-1957, when <NAME> recorded more than 500 sites in only a sixth of the plateau's entire area. - sys: id: 7jc13ulbagcQmq0YKUQqwu created_at: !ruby/object:DateTime 2015-11-26 15:11:09.168000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:11:09.168000000 Z content_type_id: chapter revision: 1 title: Themes title_internal: 'Chad: country, chapter 5' body: As in the rest of the Sahara, the main themes in Chadian rock art are directly linked to the chronology. The oldest depictions are of wild animals, but most common are later scenes with cattle, huts and people. As in other areas of the Sahara, the most recent depictions correspond to battle scenes of riders on horses and camels. Along with these main subjects, both areas have examples of very detailed scenes of daily life and human activities, including people playing music, visiting the sick or dancing. The rock art of both the Ennedi Plateau and the Tibesti regions is characterized by the existence of a variety of local styles, such as the so-called ‘Flying Gallop style’, sometimes simultaneous, sometimes successive. This variability means an enormous richness of techniques, themes and artistic conventions, with some of the most original styles in Saharan rock art. - sys: id: 5h4CpUNMty4WiYiK0uOu2g created_at: !ruby/object:DateTime 2015-11-26 15:00:58.853000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:00:58.853000000 Z content_type_id: image revision: 1 image: sys: id: Z50lrTE2EUM0egk4Mk482 created_at: !ruby/object:DateTime 2015-11-26 13:20:23.161000000 Z updated_at: !ruby/object:DateTime 2015-11-26 13:20:23.161000000 Z title: '2013,2034.6732' description: url: "//images.ctfassets.net/xt8ne4gbbocd/Z50lrTE2EUM0egk4Mk482/ddfe4ed0c368ef757168f583aac8bb4b/2013_2034.6732.jpg" caption: Village scene showing people, cattle and huts or tents. To the right, three women are seated around a fourth (possibly sick) woman lying on a blanket or mattress. Ennedi Plateau. 2013,2034.6732 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3639846&partId=1&searchText=2013,2034.6732&page=1 - sys: id: 4mRjWNwKj6myyi8GGG06uC created_at: !ruby/object:DateTime 2015-11-26 15:01:28.260000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:01:28.260000000 Z content_type_id: image revision: 1 image: sys: id: 6uYaJrzaMgAwK42CSgwcMW created_at: !ruby/object:DateTime 2015-11-26 13:20:23.253000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:12:19.070000000 Z title: '2013,2034.6595' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3640375&partId=1&searchText=2013,2034.6595&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/6uYaJrzaMgAwK42CSgwcMW/b71fe481a99fa36b16f32265828a440e/2013_2034.6595.jpg" caption: Raiding scene with horses in the so-called ‘Flying gallop’ style. Camel Period. 2013,2034.6595 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3640375&partId=1&searchText=2013,2034.6595&page=1 - sys: id: 1KHUsTtlL64uMK48KsySek created_at: !ruby/object:DateTime 2015-11-26 15:11:36.258000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:11:36.258000000 Z content_type_id: chapter revision: 1 title: Chronology title_internal: 'Chad: country, chapter 6' body: |- The oldest engravings in Chad are more recent than those to the north, having started to appear in the 5th to 4th millennia BC, and can be broadly divided into three main periods: The oldest is the so-called Archaic Period, characterized by wild animals in the Ennedi Plateau and Round Head-style figures in the Tibesti Mountains, similar to those found in the Central Sahara. The second phase is named the Bovine or Pastoral Period, when domestic cattle are the predominant animals, and a third, late period named the Dromedary or Camel Period. Unlike other areas in the Sahara, horse and camel depictions appear to be from roughly the same period (although horses were introduced to the Sahara first), so they are included in a generic Camel Period. The end of the rock art tradition in both areas is difficult to establish, but it seems to have lasted at least until the seventeenth century in the Ennedi Plateau, much longer than in other areas of the Sahara. - sys: id: gzoaZ2DMHegIuqy4e84cO created_at: !ruby/object:DateTime 2015-11-26 15:01:55.122000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:01:55.122000000 Z content_type_id: image revision: 1 image: sys: id: 4tdnKRONuECgKUm66woS2M created_at: !ruby/object:DateTime 2015-11-26 13:20:23.585000000 Z updated_at: !ruby/object:DateTime 2015-11-26 13:20:23.585000000 Z title: '2013,2034.6807' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4tdnKRONuECgKUm66woS2M/07c3ea3b18caacafd79db6f2ea6c2c88/2013_2034.6807.jpg" caption: Depiction of human figures infilled with dots. Another human figure infilled in white and facing forwards is depicted at the top right of the tableau. Archaic Period, Ennedi Plateau. 2013,2034.6807 © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3642807&partId=1&searchText=2013,2034.6807&page=1 - sys: id: Pgpnd2dYiqqS2yQkookMm created_at: !ruby/object:DateTime 2015-11-26 15:02:31.184000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:02:31.184000000 Z content_type_id: image revision: 1 image: sys: id: 5PmKmAsIH6OO8eyuOYgUa2 created_at: !ruby/object:DateTime 2015-11-26 13:20:27.673000000 Z updated_at: !ruby/object:DateTime 2015-11-26 13:20:27.673000000 Z title: '2013,2034.7610' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5PmKmAsIH6OO8eyuOYgUa2/650f01d3f303f5f062321384b36c9943/2013_2034.7610.jpg" caption: Frieze of engraved cattle. Tibesti Mountains, Pastoral Period. 2013,2034.7610 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3654657&partId=1&searchText=2013,2034.7610&page=1 - sys: id: 7MvpMnChjiKIwgSC0kgiEW created_at: !ruby/object:DateTime 2015-11-26 15:03:01.760000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:03:01.760000000 Z content_type_id: image revision: 1 image: sys: id: 6weCWSE3EkyIcyWW4S8QAc created_at: !ruby/object:DateTime 2015-11-26 13:20:23.260000000 Z updated_at: !ruby/object:DateTime 2015-11-26 13:20:23.260000000 Z title: '2013,2034.6373' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6weCWSE3EkyIcyWW4S8QAc/a469e0c984f2824f23cefa7773ffc075/2013_2034.6373.jpg" caption: White rider on a horse from the latest period of the Ennedi Plateau rock art. The figure is superimposed on several red cows of the previous Pastoral Period. Ennedi Plateau. 2013,2034.6373 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3639421&partId=1&searchText=2013,2034.6373&page=1 citations: - sys: id: 4I9BcFZSWsesgIMUwwoQ2k created_at: !ruby/object:DateTime 2015-11-26 13:21:04.168000000 Z updated_at: !ruby/object:DateTime 2015-11-26 13:21:04.168000000 Z content_type_id: citation revision: 1 citation_line: |- <NAME> (1997). *Art rupestre en Ennedi. Looking for rock paintings and engravings in the Ennedi Hills* Sépia, Saint-Maur <NAME>., <NAME>. and <NAME>. (1994). *Niola Doa, ‘il luogo delle fanciulle’ (Ennedi, Ciad)* Sahara 6: pp.51-63 background_images: - sys: id: 1AS5ngxVRGWeAaKemYyOyo created_at: !ruby/object:DateTime 2015-11-26 13:20:23.225000000 Z updated_at: !ruby/object:DateTime 2015-11-26 13:20:23.225000000 Z title: '2013,2034.7259' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1AS5ngxVRGWeAaKemYyOyo/ab561407686a2a37d59602f6b05978d3/2013_2034.7259.jpg" - sys: id: V66nfuesIoQGsMw2ugcwk created_at: !ruby/object:DateTime 2015-11-26 13:20:23.561000000 Z updated_at: !ruby/object:DateTime 2015-11-26 13:20:23.561000000 Z title: '2013,2034.6451' description: url: "//images.ctfassets.net/xt8ne4gbbocd/V66nfuesIoQGsMw2ugcwk/feb663001d1372a237275aa64bc471ed/2013_2034.6451.jpg" - sys: id: Z50lrTE2EUM0egk4Mk482 created_at: !ruby/object:DateTime 2015-11-26 13:20:23.161000000 Z updated_at: !ruby/object:DateTime 2015-11-26 13:20:23.161000000 Z title: '2013,2034.6732' description: url: "//images.ctfassets.net/xt8ne4gbbocd/Z50lrTE2EUM0egk4Mk482/ddfe4ed0c368ef757168f583aac8bb4b/2013_2034.6732.jpg" region: Northern / Saharan Africa ---<file_sep>/_coll_country/botswana/tsodilo.md --- breadcrumbs: - label: Countries url: "../../" - label: Botswana url: "../" layout: featured_site contentful: sys: id: 4LLcZZwsVO2SOacCKoc2Ku created_at: !ruby/object:DateTime 2016-09-12 11:02:35.091000000 Z updated_at: !ruby/object:DateTime 2016-09-13 13:32:13.193000000 Z content_type_id: featured_site revision: 7 title: Tsodilo Hills, Botswana slug: tsodilo chapters: - sys: id: 28cyW9T0iUqYugWyq8cmWc created_at: !ruby/object:DateTime 2016-09-12 11:30:29.590000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:30:29.590000000 Z content_type_id: chapter revision: 1 title: Introduction title_internal: 'Botswana: featured site, chapter 1' body: 'Tsodilo Hills, located in north-west Botswana, contains around 400 rock art sites with more than 4,000 individual paintings, and has been termed the “The Louvre of the Desert”. Designated a World Heritage Site by UNESCO in 2001, Tsodilo comprises four main hill: Male Hill, Female Hill, Child Hill and North Hill with paintings occurring on all four. This region shows human occupation going back 100,000 years. At sunset the western cliffs of the Hills radiate a glowing light that can be seen for miles around, for which the local Juc’hoansi call them the “Copper Bracelet of the Evening”.' - sys: id: BUqVZ44T2Cw0oguCqa0Ui created_at: !ruby/object:DateTime 2016-09-12 11:31:14.266000000 Z updated_at: !ruby/object:DateTime 2018-05-11 16:05:40.114000000 Z content_type_id: image revision: 2 image: sys: id: 1sR7vldVp2WgiY8MUyWI8E created_at: !ruby/object:DateTime 2016-09-12 11:40:46.655000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:40:46.655000000 Z title: BOTTSDNAS0010008 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1sR7vldVp2WgiY8MUyWI8E/3ee38dc4339bc8831fbc27c32789652b/BOTTSDNAS0010008_jpeg.jpg" caption: The evening light falls on the cliffs of Female Hill causing them to glow like burnished copper, and giving the Hills the name 'Copper Bracelet of the Evening'. 2013,2034.21153 © TARA/ <NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3762166&partId=1&searchText=2013,2034.21153&page=1 - sys: id: Yer3GOpD8siKgO0iwcaSo created_at: !ruby/object:DateTime 2016-09-12 11:30:29.644000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:30:29.644000000 Z content_type_id: chapter revision: 1 title: Rock Art title_internal: 'Botswana: featured site, chapter 2' body: The paintings at Tsodilo are unique in comparison to other San&#124;Bushmen rock art in both techniques and subject matter. San&#124;Bushmen paintings are well-known throughout southern Africa for their fine-line detail because they were brush painted, but those at Tsodilo are finger painted. In addition, 160 depictions of cattle are portrayed in the same style as wild animals, and more geometric designs appear here than anywhere else. Tsodilo animal drawings are larger and the geometric designs simpler than those found elsewhere. In comparison to human figures elsewhere in southern Africa, those at Tsodilo appear without bows and arrows, clothing or any forms of personal ornamentation. In addition, numerous cupules and grooves are incised and ground into rock surfaces, sometimes close to painted rock art sites and some on their own. For the residents of Tsodilo, the hills are a sacred place inhabited by spirits of the ancestors. - sys: id: 43rtUm8qI8KmCcYYMSOgmq created_at: !ruby/object:DateTime 2016-09-12 11:30:29.677000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:30:29.677000000 Z content_type_id: chapter revision: 1 title: The Red Paintings title_internal: 'Botswana: featured site, chapter 3' body: 'The subject matter of red finger-painted depictions can be divided into animals, human figures and geometric designs. Unusually, animals, mainly large mammals and cattle have been depicted in twisted perspective with two horns and two or four legs displayed in silhouette. ' - sys: id: 3ImTBIKi2I6UKK0kOU6QuI created_at: !ruby/object:DateTime 2016-09-12 11:31:54.679000000 Z updated_at: !ruby/object:DateTime 2018-05-11 16:06:23.440000000 Z content_type_id: image revision: 2 image: sys: id: 1ciquTlk7CuacgoUmGW4ko created_at: !ruby/object:DateTime 2016-09-12 11:40:59.662000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:40:59.662000000 Z title: BOTTSD0100011 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1ciquTlk7CuacgoUmGW4ko/e1c26a2555f8949c83f4f3075453266f/BOTTSD0100011_jpeg.jpg" caption: An eland with a calf. Gubekho Gorge, <NAME> 2013,2034.20700. © TARA/ <NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3758016&partId=1&searchText=2013,2034.20700&page=1 - sys: id: 4erJYWZNlCKAQwwmIGCMMK created_at: !ruby/object:DateTime 2016-09-12 11:30:29.705000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:30:29.705000000 Z content_type_id: chapter revision: 1 title_internal: 'Botswana: featured site, chapter 4' body: 'Human figures are schematic and depicted by two intersecting lines, a vertical line which thickens at the middle to indicate hips and buttocks, and the other a horizontal shorter line joined at the middle to represent a penis. Female figures are depicted with two legs and show two projections near the top indicating breasts. ' - sys: id: 3z6hr5zWeA8uiwQuIOU4Me created_at: !ruby/object:DateTime 2016-09-12 11:32:03.882000000 Z updated_at: !ruby/object:DateTime 2018-05-11 16:07:16.062000000 Z content_type_id: image revision: 2 image: sys: id: 3o0or3SkLeYGGUoAY0eesW created_at: !ruby/object:DateTime 2016-09-12 11:41:14.546000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:41:14.546000000 Z title: BOTTSD0350003 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3o0or3SkLeYGGUoAY0eesW/76825491efe27f5d7281812cf374f201/BOTTSD0350003_jpeg.jpg" caption: This panel of figures shows men with penises and women with breasts appearing to perform a ceremony with a domestic cow. Female Hill, Tsodilo Hills. 2013,2034.20891 © TARA/ <NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3761502&partId=1&searchText=2013,2034.20891&page=1 - sys: id: 2sRPLGg0x20QMQWwoSgKAa created_at: !ruby/object:DateTime 2016-09-12 11:30:29.552000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:30:29.552000000 Z content_type_id: chapter revision: 1 title_internal: 'Botswana: featured site, chapter 5' body: 'Geometric designs include circles and ovals with internal grid patterns, rectilinear motifs termed “shields”, some handprints and rows of finger impressions. In addition, there are a number of rectangular motifs that have been called “stretched skins”. Similar designs have been found in Zambia, Angola, Namibia, northern South Africa and Malawi. ' - sys: id: 2hIErx8hcciSyMwOKKSqiY created_at: !ruby/object:DateTime 2016-09-12 11:32:11.837000000 Z updated_at: !ruby/object:DateTime 2018-05-11 16:11:48.100000000 Z content_type_id: image revision: 2 image: sys: id: 6vCru3T4QwO8kSOSSUwOsG created_at: !ruby/object:DateTime 2016-09-12 11:41:29.254000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:41:29.254000000 Z title: BOTTSD0100003 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6vCru3T4QwO8kSOSSUwOsG/9fa827f96116559169a415bb2abe204f/BOTTSD0100003_jpeg.jpg" caption: Rectangular motif known as a “stretched skin”. <NAME>, Tsodilo Hills. 2013,2034.20692 © TARA/ <NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3758002&partId=1&searchText=2013,2034.20692&page=1 - sys: id: 28VhGOdi2A2sKIG20Wcsua created_at: !ruby/object:DateTime 2016-09-12 11:30:29.799000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:30:29.799000000 Z content_type_id: chapter revision: 1 title_internal: 'Botswana: featured site, chapter 6' body: While most of the images in the Tsodilo Hills seem to be discrete depictions, some sites show figures. Some of these figures are with cattle as well as women standing in rows in connection with animal groups, possibly showing some relationship with each other. Additionally, some of the rock art in the Tsodilo Hills shows superimposition, but this occurs infrequently. In some cases red geometric designs superimpose animals, but geometric designs and animals never superimpose human figures, nor do images of cattle ever superimpose other images – which may suggest some kind of relationship or hierarchy. - sys: id: 2W4qNU8IVWQAyuuoaaaYCE created_at: !ruby/object:DateTime 2016-09-12 11:30:29.588000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:30:29.588000000 Z content_type_id: chapter revision: 1 title: Late White Paintings title_internal: 'Botswana: featured site, chapter 7' body: White finger-painted images appear more crudely executed and are made from a powdery or greasy white pigment. More than 200 paintings at 20 different sites show paintings in this style, half of these depictions occur in White Paintings Shelter alone. Subject matter includes people facing forwards with their hands on hips, figures riding horses, a possible wagon wheel and a figure standing on a wagon, as well as an elephant, rhino, giraffe, eland, cows, antelope, snakes, unidentified animals and geometric designs, particularly “m” shapes. White paintings occur at sites with red paintings and often superimpose them. - sys: id: 3szVgL4Drqs2eicWcmKIaI created_at: !ruby/object:DateTime 2016-09-12 11:32:18.860000000 Z updated_at: !ruby/object:DateTime 2018-05-11 16:12:37.841000000 Z content_type_id: image revision: 2 image: sys: id: k0cOVVuRnUmcWEYUQsuiG created_at: !ruby/object:DateTime 2016-09-12 11:41:41.851000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:41:41.851000000 Z title: BOTTSD0590001 description: url: "//images.ctfassets.net/xt8ne4gbbocd/k0cOVVuRnUmcWEYUQsuiG/98eaf4781fbe7a6b0a4a7a395808f618/BOTTSD0590001_jpeg.jpg" caption: Painted white geometric designs on a protected rock face. Female Hill, Tsodilo Hills. © TARA/ <NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3761865&partId=1&searchText=2013,2034.20999&page=1 - sys: id: 6zm0EQehBCyEiWKIW8QkmC created_at: !ruby/object:DateTime 2016-09-12 11:30:30.484000000 Z updated_at: !ruby/object:DateTime 2018-05-15 12:43:48.178000000 Z content_type_id: chapter revision: 3 title: Cupules/Grooves title_internal: 'Botswana: featured site, chapter 8' body: There are no engravings at Tsodilo representing animals or human figures, but more than 25 sites show evidence of small round depressions ground into the rock, known as cupules, as well as various shaped grooves that have been chipped and ground into the rock. The majority of sites are found on Female Hill, with four on Male Hill and one site on Child Hill. Cupules tend to measure about 5cm or more wide and less than a 1cm deep, although larger examples occur. They can occur at painted rock art sites but also on their own. For the most part they are found in groups ranging from 5 to 100 and in three cases, considerably more. For example, in Rhino Cave there are 346 carved into a vertical wall and nearly 1,100 at Depression Shelter. The purpose or meaning of cupules is unknown; they may have denoted a special place or the number of times a site had been visited. However, we have no dates for any of the cupules and even if they are adjacent to a rock art site, they are not necessarily contemporaneous. From their patina and general wear it has been proposed that some cupules may date back tens of thousands of years to the Middle Stone Age. If paintings also existed at this time they have long since disappeared. - sys: id: 5xeXEU1FpS26IC0kg6SoIa created_at: !ruby/object:DateTime 2016-09-12 11:32:30.877000000 Z updated_at: !ruby/object:DateTime 2018-05-15 12:44:51.891000000 Z content_type_id: image revision: 2 image: sys: id: 65NOs0Iic0kGmCKyEQqSSO created_at: !ruby/object:DateTime 2016-09-12 11:41:57.790000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:41:57.790000000 Z title: BOTTSD0970003 description: url: "//images.ctfassets.net/xt8ne4gbbocd/65NOs0Iic0kGmCKyEQqSSO/b729ac2af7dfc16ba9355cd9c7578b29/BOTTSD0970003_jpeg.jpg" caption: Engraved boulder with numerous ground cupules. <NAME>, <NAME>. 2013,2034.21062 © TARA/ <NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3762004&partId=1&searchText=2013,2034.21062&page=1 - sys: id: RIKm0qhPO0CeIoommeWeO created_at: !ruby/object:DateTime 2016-09-12 11:30:30.503000000 Z updated_at: !ruby/object:DateTime 2016-10-17 11:07:04.906000000 Z content_type_id: chapter revision: 2 title_internal: 'Botswana: featured site, chapter 9' body: Grooves are less common than cupules, but are often easier to detect. They occur in small groups of 3 to 15 and are elongated oval or canoe-like in shape, and are found mostly on horizontal or near-horizontal surfaces. Their function is unknown, although a thin slab of stone with a curved round edge was excavated from Depression Shelter which matched one of the grooves in the shelter. - sys: id: 2rAlzTp1WMc4s8WiAESWcE created_at: !ruby/object:DateTime 2016-09-12 11:30:30.536000000 Z updated_at: !ruby/object:DateTime 2016-09-13 13:31:07.523000000 Z content_type_id: chapter revision: 5 title: Who were the artists? title_internal: 'Botswana: featured site, chapter 10' body: "It is a bit of a mystery about who actually created the paintings at Tsodilo, as the red images at Tsodilo do not fit neatly into other known styles of rock art in southern Africa. They do not show the fine brush work of San&#124;Bushmen¹ in other parts of southern Africa, nor the cruder style of white paintings attributed to later Bantu-speaking farmers.\n\nIt is possible that they were painted by the Khoesan during the first millennium AD, the original settlers in the area who made stone tools and herded livestock. A local Ncaekhoe man (a Central San people) claims his ancestors made the paintings and it is possible that some or many of the cattle images were painted by pastoral ancestors of Ncaekhoe. \n\nThe white paintings are more difficult to attribute authorship, although as they are comparable to the red paintings, comprising the same subject matter of elephant, rhino, giraffe and antelope as well as geometrics, they may reflect a later version of the red tradition.\n\n" - sys: id: 55nMUbiXCEequAa4egOUMS created_at: !ruby/object:DateTime 2016-09-12 11:30:30.558000000 Z updated_at: !ruby/object:DateTime 2016-10-17 11:10:22.009000000 Z content_type_id: chapter revision: 2 title: Dating title_internal: 'Botswana: featured site, chapter 11' body: The paintings at Tsodilo are often faded because they are located on rock faces exposed to the sun, wind and rain. As such, dating them scientifically is problematic as little or no suitable organic material remains. However, cattle paintings may help to date the art. There are about 160 depictions of cattle, which were common around the Tsodilo Hills between 800–1200 AD. As the cattle depictions are stylistically similar to other animal depictions it has been suggested that this seems to be a plausible date for most of the art (Coulson and Campbell, 2001:103) - sys: id: 6rU0fkhAasueAasEgyyg6S created_at: !ruby/object:DateTime 2016-09-12 11:32:40.775000000 Z updated_at: !ruby/object:DateTime 2018-05-15 12:49:05.907000000 Z content_type_id: image revision: 2 image: sys: id: Y7kLCRLHA2ciIS8eQOSyQ created_at: !ruby/object:DateTime 2016-09-12 11:42:17.633000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:42:17.633000000 Z title: BOTTSD1020001 description: url: "//images.ctfassets.net/xt8ne4gbbocd/Y7kLCRLHA2ciIS8eQOSyQ/f420a4f3e3f70bf173adffe97010596f/BOTTSD1020001_jpeg.jpg" caption: Red cow with upturned horns. Tsodilo Hills. 2013,2034.21070 © TARA/ David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3762014&partId=1&searchText=2013,2034.21070&page=1 - sys: id: 3kNt1aGj6wssQ0SEwCgIcA created_at: !ruby/object:DateTime 2016-09-12 11:30:30.552000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:30:30.552000000 Z content_type_id: chapter revision: 1 title_internal: 'Botswana: featured site, chapter 12' body: 'Similarly, the first horses known to reach Tsodilo belonged to a party of Griqua traders who passed nearby on their way to Andara in 1852, the earliest probable date for the paintings of figures on horseback (Campbell, Robbins and Taylor, 2010:103). It is not clear when the red painting tradition ceased but this could have occurred in the twelfth century when Tsodilo stopped being a major trade centre and seemingly the local cattle population collapsed. ' - sys: id: 4v5vfCbdLy2WGqOIKO24Om created_at: !ruby/object:DateTime 2016-09-12 11:32:49.588000000 Z updated_at: !ruby/object:DateTime 2018-05-15 13:32:39.837000000 Z content_type_id: image revision: 2 image: sys: id: 59TnAobO36C8wcEkwwq2Yq created_at: !ruby/object:DateTime 2016-09-12 11:42:47.829000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:42:47.829000000 Z title: BOTTSD0520003 description: url: "//images.ctfassets.net/xt8ne4gbbocd/59TnAobO36C8wcEkwwq2Yq/363ccd57abf9e193881c3c012c92feba/BOTTSD0520003_jpeg.jpg" caption: 'White painted rock art showing figure on horseback adjacent to figure with hands on hips. White Paintings Shelter, Tsodilo Hills. 2013,2034.20954 © TARA/ <NAME> ' col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3761768&partId=1&searchText=2013%2c2034.20954&page=1 - sys: id: 3eB1mi7ZIIq6WAguuucCSk created_at: !ruby/object:DateTime 2016-09-12 11:30:30.591000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:30:30.591000000 Z content_type_id: chapter revision: 1 title: Interpretation title_internal: 'Botswana: featured site, chapter 13' body: "Giraffe, eland and rhino are by far the most common species depicted at Tsodilo, followed by elephant, gemsbok and cattle. However, these images tend to be discretely rendered and there does not appear to be any relationship between images on the same rock. \n\nRepresentations of people are simply painted and generally stick-like, identified to gender by either penis or breasts. In some cases this may represent sexual virility and fertility, although in scenes where both occur it may merely indicate gender differences.\n\nCattle seem to appear in the rock art at the same time as human figures. In one scene, three figures, one leading a child, has been interpreted as either herding or stealing cattle (Campbell, Robbins and Taylor, 2010:106). Three other sites show cattle depicted with what may be mythical rain animals. \n" - sys: id: OhQoTZwtQ4c6824AkMeIw created_at: !ruby/object:DateTime 2016-09-12 11:32:56.778000000 Z updated_at: !ruby/object:DateTime 2018-05-15 13:35:20.813000000 Z content_type_id: image revision: 2 image: sys: id: y5jBKXYeoCcMusKuIcKeG created_at: !ruby/object:DateTime 2016-09-12 11:43:17.613000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:43:17.613000000 Z title: BOTTSD0580002 description: url: "//images.ctfassets.net/xt8ne4gbbocd/y5jBKXYeoCcMusKuIcKeG/6ee8df8512d8e7c55e06cb2292166936/BOTTSD0580002_A_jpeg.jpg" caption: 'Two cattle with four figures, one leading a child. The scene has been interpreted as possibly herding or stealing cattle. 2013,2034.20996 © TARA/ <NAME> ' col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3761852&partId=1&searchText=2013%2c2034.20996&page=1 - sys: id: 3FUszfSDUQ42g2kUsukuQi created_at: !ruby/object:DateTime 2016-09-12 11:30:30.775000000 Z updated_at: !ruby/object:DateTime 2018-05-15 13:36:08.602000000 Z content_type_id: chapter revision: 2 title_internal: 'Botswana: featured site, chapter 14' body: "Geometric designs are trickier to decipher. Square geometric designs, also known as “shields” possibly represent human forms. Circular designs sometimes partially superimpose an animal or be placed within its outline. This superimposition may enhance the symbolic meaning of the animal.\n\nEither singly or in groups, and sometimes depicted with animals or people, geometric motifs show stylistic consistency across a wide area and are likely to have had some symbolic meaning. In Zambia, geometric designs are thought to have been made by women and associated with the weather and fertility, while depictions of animals were made by men. The geometric rock art of Tsodilo fits into a pattern of similar imagery in central Africa and may be related to the same meanings of weather and fertility.\t\n" - sys: id: 1ImUVBlPTSQIG00wy6Y6QQ created_at: !ruby/object:DateTime 2016-09-13 13:31:24.274000000 Z updated_at: !ruby/object:DateTime 2016-09-13 13:31:38.744000000 Z content_type_id: chapter revision: 2 title_internal: Botswana Chapter 14 body: "¹ San&#124;Bushmen is a collective term used to describe the many different hunter-gatherer-fisher groups living in southern Africa who have related languages and cultural traditions. Both 'San' and 'Bushmen' are considered offensive terms by some members of these groups, although others have positively adopted them." citations: - sys: id: Pu7wGVJ7C6EIqoKCmUuCk created_at: !ruby/object:DateTime 2016-09-12 11:33:04.551000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:33:04.551000000 Z content_type_id: citation revision: 1 citation_line: |- <NAME>; <NAME> (2010) Tsodilo Hills: Copper Bracelet of the Kalahari. East Lansing: Michigan State University Press. Coulson and Campbell, (2001) background_images: - sys: id: 1sR7vldVp2WgiY8MUyWI8E created_at: !ruby/object:DateTime 2016-09-12 11:40:46.655000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:40:46.655000000 Z title: BOTTSDNAS0010008 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1sR7vldVp2WgiY8MUyWI8E/3ee38dc4339bc8831fbc27c32789652b/BOTTSDNAS0010008_jpeg.jpg" - sys: id: 6vCru3T4QwO8kSOSSUwOsG created_at: !ruby/object:DateTime 2016-09-12 11:41:29.254000000 Z updated_at: !ruby/object:DateTime 2016-09-12 11:41:29.254000000 Z title: BOTTSD0100003 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6vCru3T4QwO8kSOSSUwOsG/9fa827f96116559169a415bb2abe204f/BOTTSD0100003_jpeg.jpg" ---<file_sep>/_coll_country_information/south-africa-country-introduction.md --- contentful: sys: id: 3bwz5wde0EMm0iu06IOk0W created_at: !ruby/object:DateTime 2016-09-12 15:22:12.732000000 Z updated_at: !ruby/object:DateTime 2016-09-12 15:22:12.732000000 Z content_type_id: country_information revision: 1 title: 'South Africa: country introduction' chapters: - sys: id: 2LBn1DZ1m8gqQUMiKCSayA created_at: !ruby/object:DateTime 2016-09-12 15:16:12.647000000 Z updated_at: !ruby/object:DateTime 2016-09-12 22:01:59.313000000 Z content_type_id: chapter revision: 4 title: Introduction title_internal: 'South Africa: country, chapter 1' body: | The rock art of South Africa has probably been studied more extensively than that of any other African country. It is estimated that South Africa contains many thousands of rock art sites, with a great variety of styles and techniques. The most well-known rock art in South Africa is that created by the San&#124;Bushman¹ people (several culturally linked groups of indigenous people of southern Africa who were traditionally hunter-gatherers) and their ancestors, with the painted rock shelters of the Drakensberg mountains some of the most well-known rock art sites in the world. However, the range of South African rock art is wide, spanning great distances, many centuries, and different cultural traditions. ¹ San&#124;Bushmen is a collective term used to describe the many different hunter-gatherer-fisher groups living in southern Africa who have related languages and cultural traditions. Both 'San' and 'Bushmen' are considered offensive terms by some members of these groups, although others have positively adopted them. - sys: id: 6rGZi909xKeQSMcYmISMgA created_at: !ruby/object:DateTime 2016-09-12 15:16:31.433000000 Z updated_at: !ruby/object:DateTime 2018-05-15 13:46:10.737000000 Z content_type_id: image revision: 2 image: sys: id: 2bsw2WPaTKumMQ80maQ6iG created_at: !ruby/object:DateTime 2016-09-12 15:16:22.149000000 Z updated_at: !ruby/object:DateTime 2016-09-12 15:16:22.149000000 Z title: SOADRB0010004 description: url: "//images.ctfassets.net/xt8ne4gbbocd/2bsw2WPaTKumMQ80maQ6iG/1748f1d507b1e6e7b40b12621fcf06a4/SOADRB0010004.jpg" caption: Painted eland antelope, horses and riders. Drakensberg Mountains, South Africa. 2013,2034.18172 ©TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3738170&partId=1&searchText=2013,2034.18172&page=1 - sys: id: 3SiNGUuMNi4EQ6S6iEg6u created_at: !ruby/object:DateTime 2016-09-12 15:16:42.238000000 Z updated_at: !ruby/object:DateTime 2016-10-17 15:43:41.595000000 Z content_type_id: chapter revision: 4 title: Geography and rock art distribution title_internal: 'South Africa: country, chapter 2' body: South Africa covers around 1,213,090 km², encircling Lesotho and bordered in the north by Namibia, Botswana and Zimbabwe and in the west by Mozambique and Swaziland. Much of the interior of the country consists of a high central plateau bordered by the Great Escarpment, a rocky ridge which forms the bulk of the long Drakensberg mountain system in the east and several smaller ranges in the centre and west of the country, as well as the western border with Lesotho. Further to the south, the Cape Fold Mountains mirror the bend of the cape coast. Much of South Africa’s known engraved rock art is found on igneous or metamorphic formations in the semi-arid environments of the central plateau. In contrast, painted rock art sites are more commonly located in the sandstone and quartzite rock shelters of the mountain systems, which form the edges of the more temperate, low-lying coastal regions in the east and south of the country. - sys: id: DfGG3aLwUC26MWusakCaQ created_at: !ruby/object:DateTime 2016-09-12 15:16:52.597000000 Z updated_at: !ruby/object:DateTime 2016-10-24 12:32:11.801000000 Z content_type_id: chapter revision: 3 title: Hunter-gatherer rock art title_internal: 'South Africa: country, chapter 3' body: Much of both the painted and engraved rock art of South Africa is characterised by its naturalistic depictions of animals, as well as numerous images of people, ambiguous figures with mixtures of animal and human features, and certain ‘geometric’ or abstract shapes and patterns. These images are the work of San&#124;Bushman people and their ancestors. Although San&#124;Bushman communities now live mainly in Namibia, Botswana and north-western South Africa, historically San&#124;Bushman cultural groups lived more widely throughout southern Africa. Hunter-gatherer people are thought to have been the only inhabitants of what is now South Africa until the arrival of herding and farming people from the north from around 2,000 years ago. - sys: id: 71sZP8YT0A8Eg6SUEqQE0K created_at: !ruby/object:DateTime 2016-09-12 15:17:10.281000000 Z updated_at: !ruby/object:DateTime 2018-05-15 13:46:37.309000000 Z content_type_id: image revision: 2 image: sys: id: 2q8dJPCe2AKcAeogKWikue created_at: !ruby/object:DateTime 2016-09-12 15:17:06.782000000 Z updated_at: !ruby/object:DateTime 2016-09-12 15:17:06.782000000 Z title: SOASWC0130095 description: url: "//images.ctfassets.net/xt8ne4gbbocd/2q8dJPCe2AKcAeogKWikue/7edea03ab0a677b76edd11bda026ba2c/SOASWC0130095.jpg" caption: Human figures with bows and other items. Western Cape, South Africa. 2013,2034.19641 ©TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3740593&partId=1&searchText=2013,2034.19641&page=1 - sys: id: dbiRhTPqBamyEw8Wa8Am0 created_at: !ruby/object:DateTime 2016-09-12 15:17:21.602000000 Z updated_at: !ruby/object:DateTime 2016-09-12 19:41:29.750000000 Z content_type_id: chapter revision: 2 title: Farmer rock art title_internal: 'South Africa: country, chapter 4' body: "Some paintings and engravings in South Africa were made by Bantu language-speaking farming people. These include a distinct tradition of rock shelter paintings found in the north-west of the country, featuring mostly white finger-painted images of animals such as crocodiles and giraffes and other motifs. These paintings, located in remote areas, are known to have been created by Northern Sotho people. Further to the south and west, engraved designs showing conjoined circle motifs are found throughout KwaZulu Natal and some areas of Mpumalanga and Gauteng Provinces, and appear to have been made by the ancestors of Sotho-Tswana and Nguni language speakers, perhaps ancestors of modern Zulu people.\n\n" - sys: id: avwg4dFD5muMuGwi64OG8 created_at: !ruby/object:DateTime 2016-09-12 15:17:28.334000000 Z updated_at: !ruby/object:DateTime 2018-05-15 13:47:33.249000000 Z content_type_id: chapter revision: 4 title: Herder rock art and other traditions title_internal: 'South Africa: country, chapter 5' body: Some rock art styles and motifs elsewhere in South Africa seem to belong to other unique traditions. It has been proposed that engraved rock art patterns with particular features including circular, linear and oblong motifs found at sites across the country, particularly near watercourses, may be the work of the Khoekhoen people or their ancestors, herders culturally related to the San&#124;Bushmen. Some paintings also appear to reflect this tradition. Local rock art traditions specific to certain areas include, among others, conglomerations of handprints near the coast in the south-western part of the Western Cape and rows of engraved cupules in the north-east of the country. There are also several examples from different rock art traditions across South Africa, of depictions of European people, items or events (such as horses and firearms) which clearly date from the 17th century or later. In the Karoo region, rock gongs (natural rock formations with indentations indicating that they have been used as percussive instruments) are sometimes associated with engraving sites. - sys: id: 1mBBOrIKNWY4m20ywAQEG4 created_at: !ruby/object:DateTime 2016-09-12 15:17:42.557000000 Z updated_at: !ruby/object:DateTime 2018-05-15 13:48:06.147000000 Z content_type_id: image revision: 2 image: sys: id: afH4Qvv6OAAu6iW2sQumq created_at: !ruby/object:DateTime 2016-09-12 15:17:38.680000000 Z updated_at: !ruby/object:DateTime 2016-09-12 15:17:38.680000000 Z title: SOASWC0120007 description: url: "//images.ctfassets.net/xt8ne4gbbocd/afH4Qvv6OAAu6iW2sQumq/b1167a05a4746cff6df801f17a999b62/SOASWC0120007.jpg" caption: Paintings showing people in long skirts and hats, with wagons drawn by horses/mules. Swartruggens, Western Cape, South Africa. 2013,2034.19505 ©TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3734262&partId=1&searchText=2013,2034.19505&page=1 - sys: id: 2tA0V2wO16oKa8kgyOeACw created_at: !ruby/object:DateTime 2016-09-12 15:17:56.399000000 Z updated_at: !ruby/object:DateTime 2016-10-17 15:44:50.312000000 Z content_type_id: chapter revision: 2 title: Research history title_internal: 'South Africa: country, chapter 6' body: 'Rock art sites throughout what is now South Africa have likely always been known to local communities, even where the art''s creators were not from within them. The presence of rock art in the Cape region has been known to Europeans since at least the mid- 18th century AD, with one of the first known reports from the expedition of Ensign A. <NAME> in 1752, describing paintings near the Great Fish River in the Eastern Cape. Further written references to rock art from the area were made throughout the 18th and 19th centuries, with some of the earliest known reproductions of Southern African rock art made in the 1770s. During the 19th and early 20th centuries, painted copies were made of San&#124;Bushman rock art by amateur artists such as <NAME>, Mark and Graham Hutchinson and <NAME>. ' - sys: id: 19Up0IjuAa2c2WQuks6Qka created_at: !ruby/object:DateTime 2016-09-12 15:20:07.688000000 Z updated_at: !ruby/object:DateTime 2018-05-15 13:51:29.749000000 Z content_type_id: image revision: 2 image: sys: id: 5pQOdclMWsYUoiqUe6UWUk created_at: !ruby/object:DateTime 2015-11-30 10:16:55.281000000 Z updated_at: !ruby/object:DateTime 2015-11-30 10:16:55.281000000 Z title: SOANTC0050054 description: url: "//images.ctfassets.net/xt8ne4gbbocd/5pQOdclMWsYUoiqUe6UWUk/55b07efecee2210caec6f0fdbc227f60/SOANTC0050054.jpg" caption: "Engraved eland, Northern Cape, South Africa. 2013,2034.18803 ©TARA/David Coulson\t" col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3731055&partId=1&searchText=2013,2034.18803&page=1 - sys: id: 57UPgZOAQgOMC2YmuSUeUA created_at: !ruby/object:DateTime 2016-09-12 15:20:19.692000000 Z updated_at: !ruby/object:DateTime 2016-09-12 19:45:24.815000000 Z content_type_id: chapter revision: 2 title: title_internal: 'South Africa: country, chapter 7' body: "Scholarly interest in Southern African rock art increased in the early 20th century and pioneering efforts were made to record both painting and engraving assemblages. In 1928 renowned archaeologist and ethnologist <NAME> mounted an expedition to record sites in South Africa as well as Zimbabwe and Namibia, while in the interior regions over the previous twenty years, <NAME> had instigated the first systematic rock engraving recording work. This endeavor was built upon from the late 1950s onwards with the extensive work of Gerhard and Dora Fock. In the same decade <NAME> pioneered the practice of recording rock art through colour photography, and over the next twenty years, further recording and analysis projects were undertaken by researchers such as <NAME> in the Western Cape region and Harald Pager and Patricia Vinnicombe in the Drakensberg mountain area. \n" - sys: id: 3ji8ZxGSA0qEugGSKc4AiM created_at: !ruby/object:DateTime 2016-09-12 15:20:34.228000000 Z updated_at: !ruby/object:DateTime 2018-05-15 13:52:17.397000000 Z content_type_id: image revision: 3 image: sys: id: 49XE8B9AUwcsyuwKS4qIoS created_at: !ruby/object:DateTime 2016-09-12 15:20:29.384000000 Z updated_at: !ruby/object:DateTime 2016-09-12 15:20:29.384000000 Z title: SOADRB0040015 description: url: "//images.ctfassets.net/xt8ne4gbbocd/49XE8B9AUwcsyuwKS4qIoS/0497ecca68dfaaf3b2656a890cff67dd/SOADRB0040015.jpg" caption: "Multiple painted eland and other antelope, Eland Cave, Drakensberg Mountains, South Africa. 2013,2034.18216 ©TARA/<NAME>\t" col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3738339&partId=1&searchText=2013,2034.18216&page=1 - sys: id: 2JAfr47aaAUicKcoeSqiGu created_at: !ruby/object:DateTime 2016-09-12 15:20:41.600000000 Z updated_at: !ruby/object:DateTime 2016-10-24 12:33:33.820000000 Z content_type_id: chapter revision: 3 title_internal: 'South Africa: country, chapter 8' body: In 1976, Vinnicombe published the seminal work *"People of the Eland"*, analysing paintings from 150 Drakensberg sites and attempting to gain insight into their execution and significance through a combination of quantitative study and reference to San&#124;Bushman ethnography (written records of insights from San&#124;Bushman culture compiled by anthropologists). Through the 1980s, interpretation of rock art was further developed, perhaps most significantly by <NAME>, a collaborator of Vinnicombe's. Lewis-Williams originated an approach to understanding San&#124;Bushman rock art which posits that the motivation and meaning for most, if not all, San&#124;Bushman rock art is based on the centrality of the spiritual leader or'shaman' and the shaman’s actions in San&#124;Bushman life and belief. Over the past 30 years, the idea that much of San&#124;Bushman rock art is essentially ‘shamanistic’ in nature has been dominant in academic discourse. - sys: id: 21vXKwU4akskQ6YAsYIo0i created_at: !ruby/object:DateTime 2016-09-12 15:20:48.780000000 Z updated_at: !ruby/object:DateTime 2016-10-24 12:36:25.686000000 Z content_type_id: chapter revision: 4 title: Themes and interpretations title_internal: 'South Africa: country, chapter 9' body: "Shamanistic interpretations of San&#124;Bushman paintings and engravings draw on both past records of ‘Southern’ or /Xam San&#124;Bushman people living historically in South Africa and more recent ethnography based mainly on San&#124;Bushman communities in Namibia and Botswana, suggesting that their imagery illustrated and reinforced the power of the actions of shamans. Much of the imagery is proposed to reflect the shaman’s hallucinatory visions from the 'trance dance’, a tradition common to San&#124;Bushman groups where shamans enter a trance state during which they visit a 'spirit world' in which they may go on spiritual journeys or perform tasks on behalf of their communities. It is thought that the rock art panels may have acted as reservoirs for the 'potency' that shamans are considered to possess, with the rock face considered a veil between both worlds. The images are thought to reflect trance experiences including those of 'therianthropes’, images of figures with both human and animal features, explained as shamans who in a trance state feel themselves transformed into animals. Certain other poses and features found in San&#124;Bushman rock art, such as so-called 'entoptic' motifs—geometric shapes such as zigzags and dots—have also been interpreted as reflecting visions that shamans experience while in a trance state. \n\nDiscussion continues around the extent of the applicability of 'shamanist' interpretations for all aspects of San&#124;Bushman art, with research ongoing and scholars also exploring the potential roles of other elements in rock art production, such as mythology or gender and initiation rites. Other avenues of study include more regional foci, on specific cultural and temporal contexts and how the imagery may reflect local power dynamics through time.\n" - sys: id: 6PJbU7cpFYUUMSYqEgS0Am created_at: !ruby/object:DateTime 2016-09-12 15:21:09.071000000 Z updated_at: !ruby/object:DateTime 2018-05-15 13:52:56.704000000 Z content_type_id: image revision: 3 image: sys: id: 2hL4pRsxIkw224k00EKeqQ created_at: !ruby/object:DateTime 2016-09-12 15:21:03.996000000 Z updated_at: !ruby/object:DateTime 2016-09-12 15:21:03.996000000 Z title: SOADRB0110028 description: url: "//images.ctfassets.net/xt8ne4gbbocd/2hL4pRsxIkw224k00EKeqQ/a0c3c33b1a178f24852aec444656fe55/SOADRB0110028.jpg" caption: Three painted ‘therianthrope’ figures with antelopes’ heads. Giant’s Castle Main Caves, Drakensberg Mountains, South Africa. 2013,2034.18474 ©TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3738986&partId=1&searchText=2013,2034.18474&page=1 - sys: id: 3AxyfldmRa4wWoGSgc2cei created_at: !ruby/object:DateTime 2016-09-12 15:21:17.413000000 Z updated_at: !ruby/object:DateTime 2016-09-12 15:21:17.413000000 Z content_type_id: chapter revision: 1 title_internal: 'South Africa: country, chapter 10' body: 'Although the focus in South African rock art research has been on San&#124;Bushman art, research has also been done on other rock art traditions, suggesting different cultural origins. For example, investigation of Northern Sotho rock art has shown much of it to have been created in relation to boys''and girls'' initiation ceremonies, while Bantu-language speakers''engravings of interlinked circle patterns have been interpreted as images of idealised conceptualised homesteads. Work on attribution for some rock art of uncertain authorship also has been undertaken. Certain geometric forms of rock engraving may be of Khoekhoen origin, possibly showing influence from central African geometric traditions and tracing historical migrations southwards. It has also been suggested that some finger-painted images in the centre of the country are the early 19th century work of the Korana people, a group of mixed ancestry living as raiders on the Cape frontier and incorporating motifs from San&#124;Bushman and other traditions. ' - sys: id: 4uS7XV338ke8iiQQ6asKC4 created_at: !ruby/object:DateTime 2016-09-12 15:21:30.588000000 Z updated_at: !ruby/object:DateTime 2016-09-12 15:21:30.588000000 Z content_type_id: chapter revision: 1 title: Chronology title_internal: 'South Africa: country, chapter 11' body: "The earliest scientifically dated examples of clearly visible painted parietal art in South Africa comes from Steenbokfontein Cave in the Western Cape, where collapsed painted portions from the wall buried in sediment have been radiocarbon dated to at least 3,600 years ago, while in the Drakensberg, AMS dating carried out on the oxalate crust superimposing a painting of a human figure has suggested it to be at least 1,800 years old. While it is thought that the beginnings of the painting tradition in the Drakensberg region are probably older than this, the relative lack of durability in paint means that many of the existing paintings were probably made sometime within the past few hundred years. Sometimes it is apparent when this is the case - several painting sites in this region show images of both San&#124;Bushman people and Europeans riding horses and bearing firearms, which dates them to within the past 350 years and particularly the 19th century. Images of sheep and cattle also place images within the last 2,000 years. \n\nThe oldest reliably dated evidence for deliberate engraving in the country is several ochre pieces incised with abstract patterns found in a buried layer in Blombos cave in the Western Cape and dated through a number of methods to between 70 and 100,000 years ago. The earliest known figurative engraving date from the country comes from a slab with an image of a portion of an animal on it, excavated from Wonderwerk Cave in the Northern Cape and dating from around 10,200 years ago. Engravings remaining in the open are more difficult to date scientifically, and various attempts have been made to date and sequence both engravings and paintings based on style and superimposition, while recent years, work has been undertaken to apply the Harris Matrix (an archaeological sequencing technique for relative dating) method to painting chronologies in the Free State, Drakensberg and Western Cape. This involves using techniques originally conceived for charting chronology in stratigraphic layering to compare and sequence different superimposed motifs.\n" - sys: id: 2Qms4PsSqQiUMGg4c4CIaS created_at: !ruby/object:DateTime 2016-09-12 15:21:46.299000000 Z updated_at: !ruby/object:DateTime 2018-05-15 13:53:23.983000000 Z content_type_id: image revision: 2 image: sys: id: 3BojqKseXY0IQkcKOwoC6K created_at: !ruby/object:DateTime 2016-09-12 15:21:40.866000000 Z updated_at: !ruby/object:DateTime 2016-09-12 15:21:40.866000000 Z title: SOANTC0030005 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3BojqKseXY0IQkcKOwoC6K/8e3971b5cccf481e5485cab60d361961/SOANTC0030005.jpg" caption: Engraved rhinoceros. Wildebeest Kuil, Northern Cape, South Africa. 2013,2034.18669 ©TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3730722&partId=1&searchText=2013,2034.18669&page=1 citations: - sys: id: 1i9uCQ3wrss8UGuMQgC0oW created_at: !ruby/object:DateTime 2016-09-12 15:21:54.192000000 Z updated_at: !ruby/object:DateTime 2016-09-12 15:21:54.192000000 Z content_type_id: citation revision: 1 citation_line: "Eastwood, E. & Eastwood, C. 2006. Capturing the Spoor: An exploration of Southern African Rock Art. Cape Town, <NAME>\n\nLewis-Williams, J.D. & Challis, S. 2011. Deciphering Ancient Minds: The Mystery of San&#124;BushmanBushman Rock Art. London, Thames & Hudson \n\nLewis-Williams, J.D. 1981. Believing and Seeing: Symbolic Meanings in San&#124;BushmanRock Paintings. Johannesburg, University of Witwatersrand Press\n\nMaggs, T. 1995. Neglected Rock Art: The Rock Engravings of Agriculturist Communities in South Africa. South African Archaeological Bulletin. Vol. 50 No. 162 pp. 132.142\n\nMazel, A.D. 2009. Images in time: advances in the dating of Drakensberg rock art since the 1970s. In: <NAME> & <NAME>, eds., The eland’s people: new perspectives on the rock art of the Maloti/Drakensberg Bushmen. Essays in memory of Pat Vinnicombe. Johannesburg: Wits University Press, pp. 81–96\n\nOuzman, S. 2005. The Magical Arts of a Raider Nation: Central South Africa’s Korana Rock Art. South African Archaeological Society Goodwin Series 9 pp. 101-113\n\nParkington, J. 2003. Cederberg Rock Paintings. Cape Town, Krakadouw Trust\n\nParkington, <NAME>, D. & Rusch, N. 2008. Karoo rock engravings: Marking places in the landscape. Cape Town, Krakadouw Trust\n\nRussell, T. 2000. The application of the Harris Matrix to San rock art at Main Caves North, KwaZulu-Natal. South African Archaeological Bulletin 55. Pp. 60–70\n\nSmith, B. & Ouzman, S. Taking Stock: Identifying Khoekhoen Herder Rock Art in Southern Africa. Current Anthropology Vol. 45, No. 4. pp 499-52\n\nSolomon, A. 1994. “Mythic Women: A Study in Variability in San Rock Art and Narra-tive”. In: <NAME> & <NAME> (eds.) Contested Images: Diversity in Southern African Rock Art Research. Johannesburg, Witwatersrand University press\n \nVinnicombe, P. 1976. People of The Eland: Rock paintings of the Drakensberg Bushmen as a reflection of their life and thought. Pietermaritzburg, University of Natal Press\n\nWillcox. A. R. 1963 The Rock Art of Southern Africa. Johannesburg, <NAME> and Sons (Africa) Pty. Ltd\n\n\n\n" ---<file_sep>/_coll_country_information/algeria-country-introduction.md --- contentful: sys: id: 5XIlz0Mp6EQW0CaG4wYWoi created_at: !ruby/object:DateTime 2015-11-26 11:46:22.368000000 Z updated_at: !ruby/object:DateTime 2015-12-07 13:42:30.802000000 Z content_type_id: country_information revision: 3 title: 'Algeria: country introduction' chapters: - sys: id: 4oh7iTmoQ8WCE48sGCIkoG created_at: !ruby/object:DateTime 2015-11-26 11:37:15.701000000 Z updated_at: !ruby/object:DateTime 2015-11-26 11:37:15.701000000 Z content_type_id: chapter revision: 1 title: Introduction title_internal: 'Algeria: country, chapter 1' body: Algeria is Africa’s largest country geographically and has long been noted for its rich concentrations of rock art, particularly in the Tassili n’Ajjer, inscribed as a UNESCO World Heritage Site in 1986. More than 15,000 paintings and engravings, some of which date back up to 12,000 years, provide unique insights into the environmental, social, cultural and economic changes in the country across a period of 10,000 or more years. The area is particularly famous for its Round Head paintings, first described and published in the 1930s by French archaeologist <NAME>. - sys: id: KLxWuWwCkMWSuoA44EU8k created_at: !ruby/object:DateTime 2015-11-26 11:30:21.587000000 Z updated_at: !ruby/object:DateTime 2017-01-06 15:40:49.293000000 Z content_type_id: image revision: 2 image: sys: id: 3bBZIG7wBWQe2s06S4w0gE created_at: !ruby/object:DateTime 2015-11-26 11:29:42.872000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:58:02.758000000 Z title: '2013,2034.4248' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3601516&partId=1&searchText=2013,2034.4248&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/3bBZIG7wBWQe2s06S4w0gE/503eeec9a0aa84ff849de9d81dcd091e/2013_2034.4248.jpg" caption: Painted rock art depicting five red figures, from Jabbaren, Tassili n’Ajjer, Algeria. 2013,2034.4248 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3601516&partId=1&images=true&people=197356&museumno=2013,2034.4248&page=1 - sys: id: 5NCDKmpHVuime8uwqkKiMe created_at: !ruby/object:DateTime 2015-11-26 11:37:45.377000000 Z updated_at: !ruby/object:DateTime 2015-11-26 11:37:45.377000000 Z content_type_id: chapter revision: 1 title: Geography title_internal: 'Algeria: country, chapter 2' body: Algeria is situated in the Maghreb region of North Africa, bordered on the west by Morocco and on the east by Tunisia and Libya, with a long Mediterranean coastline to the north. The Atlas Mountains cross Algeria east to west along the Mediterranean coast. The northern portion of the country is an area of mountains, valleys, and plateaus, but more than 80% of the country falls within the Sahara Desert. Rock art is located in the Algerian Maghreb and the Hoggar Mountains but the richest zone of rock art is located in the mountain range of Tassili n'Ajjer, a vast plateau in the south-east of the country. Water and sand erosion have carved out a landscape of thin passageways, large arches, and high-pillared rocks, described by Lhote as 'forests of stone'. - sys: id: 1miMC9tEW0AqawCsYOO0co created_at: !ruby/object:DateTime 2015-11-26 11:30:59.823000000 Z updated_at: !ruby/object:DateTime 2015-11-26 11:30:59.823000000 Z content_type_id: image revision: 1 image: sys: id: 6T7rsl4ISssocM8K0O0g2U created_at: !ruby/object:DateTime 2015-11-26 11:29:42.909000000 Z updated_at: !ruby/object:DateTime 2015-11-26 11:29:42.909000000 Z title: '2013,2034.4551' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6T7rsl4ISssocM8K0O0g2U/ec87053980e76d10917feb28c045fa67/2013_2034.4551.jpg" caption: Tuareg looking over the Tassili n’Ajjer massif. 2013,2034.4551 © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3603812&partId=1&images=true&people=197356&museumno=2013,2034.4551&page=1 - sys: id: 6JVjGRQumAUaMIuMyOUwyM created_at: !ruby/object:DateTime 2015-11-26 11:42:31.967000000 Z updated_at: !ruby/object:DateTime 2015-11-26 11:42:31.967000000 Z content_type_id: chapter revision: 1 title: Research history title_internal: 'Algeria: country, chapter 3' body: |- Rock art in Algeria, notably the engravings in South Oran, has been the subject of European study since 1863. Notable surveys were made by <NAME> (1893-1898), <NAME> (1901-1927), <NAME>. Flamand (1892-1921), <NAME> and <NAME> (1925), <NAME> (1931-1957), <NAME> (1918-1938), and <NAME> (1935-1955). Henri Lhote visited the area in 1955 and 1964, completing previous research and adding new descriptions included in a major publication on the area in 1970. The rock art of the Tassili region was introduced to Western eyes as a result of visits and sketches made by French legionnaires, in particular a Lt. Brenans during the 1930s. On several of his expeditions, Lt. Brenans took French archaeologist Henri Lhote who went on to revisit sites in Algeria between 1956-1970 documenting and recording the images he found. Regrettably, some previous methods of recording and/or documenting have caused damage to the vibrancy and integrity of the images. - sys: id: 6ljYMZr61ieuSkgCI2sUCs created_at: !ruby/object:DateTime 2015-11-26 11:31:39.981000000 Z updated_at: !ruby/object:DateTime 2015-11-26 11:31:39.981000000 Z content_type_id: image revision: 1 image: sys: id: 6TFwgxGXtYy6OgA02aKUCC created_at: !ruby/object:DateTime 2015-11-26 11:29:47.274000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:58:43.476000000 Z title: '2013,2034.4098' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3595539&partId=1&searchText=2013,2034.4098&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/6TFwgxGXtYy6OgA02aKUCC/cf9adf1bdc99801fbf709fc87fd87acb/2013_2034.4098.jpg" caption: Experiment undertaken by Lhote with experimental varnishes. The dark rectangular patch is the remnant of this experiment. 2013,2034.4098 © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3595539&partId=1&images=true&people=197356&museumno=2013,2034.4098&page=1 - sys: id: 6yYmsmTCWQS88mMakgAOyu created_at: !ruby/object:DateTime 2015-11-26 11:43:01.493000000 Z updated_at: !ruby/object:DateTime 2015-11-26 11:43:01.493000000 Z content_type_id: chapter revision: 1 title: Early rock art title_internal: 'Algeria: country, chapter 4' body: The earliest pieces of rock art are engraved images reflecting a past vibrant fertile environment teeming with life and includes elephant, rhinoceros, hippopotamus and fish as well as numerous predators, giraffe, and plains animals such as antelope and gazelle. When human figures are depicted in this period they are very small in stature and hold throwing sticks or axes. More than simply hunting scenes, they are likely to reflect people’s own place within their environment and their relationship with it. - sys: id: 6ymgBr7UZiEeqcYIK8ESQw created_at: !ruby/object:DateTime 2015-11-26 11:32:15.331000000 Z updated_at: !ruby/object:DateTime 2017-01-06 15:41:43.326000000 Z content_type_id: image revision: 2 image: sys: id: faUxnSK2ookUW6UWyoCOa created_at: !ruby/object:DateTime 2015-11-26 11:29:42.884000000 Z updated_at: !ruby/object:DateTime 2015-11-26 11:29:42.884000000 Z title: '2013,2034.4685' description: url: "//images.ctfassets.net/xt8ne4gbbocd/faUxnSK2ookUW6UWyoCOa/ec94f329a011643a9f0eba672fd5fb6f/2013_2034.4685.jpg" caption: Engraved elephant, Tadrart, Algeria. 2013,2034.4685 © TARA/David Coulson col_link: http://bit.ly/2iMdChh - sys: id: 61Gb2N3umIC8cAAq2q8SWK created_at: !ruby/object:DateTime 2015-11-26 11:43:56.920000000 Z updated_at: !ruby/object:DateTime 2015-11-26 11:44:04.420000000 Z content_type_id: chapter revision: 2 title: Round Head Period title_internal: 'Algeria: country, chapter 5' body: The area is especially famous for its Round Head paintings. Thought to be up to 9,000 years old, some of these paintings are the largest found on the African continent, measuring up to 13 feet in height. The Round Head period comprises depictions of figures with round, featureless heads and formless bodies, often appearing to be ‘floating’. Some features or characteristics of Round Head paintings found on the Tassili plateau are unique to the area, and the depiction of certain motifs may have held special significance locally, making particular sites where they occur the locus of rites, ritual or ceremonial activity. The majority of animal depictions are mouflon (wild mountain sheep) and antelope, but they are represented only in static positions and not as part of a hunting scene. - sys: id: 14fYsLFiwaOeGqSscuI4eW created_at: !ruby/object:DateTime 2015-11-26 11:32:46.062000000 Z updated_at: !ruby/object:DateTime 2015-11-26 11:32:46.062000000 Z content_type_id: image revision: 1 image: sys: id: 79I1hxTRDyYiqcMG02kgE8 created_at: !ruby/object:DateTime 2015-11-26 11:29:47.295000000 Z updated_at: !ruby/object:DateTime 2015-11-26 11:29:47.295000000 Z title: '2013,2034.4173' description: url: "//images.ctfassets.net/xt8ne4gbbocd/79I1hxTRDyYiqcMG02kgE8/0fa8b92cad626f5dfe083c814b30fdfb/2013_2034.4173.jpg" caption: Round Head Period painting, <NAME>’Ajjer, Algeria. 2013,2034.4173 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3595624&partId=1&images=true&people=197356&museumno=2013,2034.4173&page=1 - sys: id: 4SqZjJi0EoeEIKuywW8eqM created_at: !ruby/object:DateTime 2015-11-26 11:44:33.802000000 Z updated_at: !ruby/object:DateTime 2015-11-26 11:44:33.802000000 Z content_type_id: chapter revision: 1 title: Pastoral Period title_internal: 'Algeria: country, chapter 6' body: The subsequent Pastoral Period, from around 7,500-4,000 years ago, portrays a very different world to the preceding ethereal Round Head period and coincides with the transition from a temperate Sahara towards aridification. Images are stylistically varied, which may attest to the movement of different cultural groups. Depictions now include domesticated animals such as cattle, sheep, goats and dogs; scenes portray herders, men hunting with bows, and representations of camp life with women and children – in essence, scenes that reference more settled communities. - sys: id: 3VIsvEgqPSMMumIgAaO8WG created_at: !ruby/object:DateTime 2015-11-26 11:33:24.713000000 Z updated_at: !ruby/object:DateTime 2015-11-26 11:33:24.713000000 Z content_type_id: image revision: 1 image: sys: id: 2E7xpiKWhe6YEOymWI4W2U created_at: !ruby/object:DateTime 2015-11-26 11:29:42.877000000 Z updated_at: !ruby/object:DateTime 2015-11-26 11:29:42.877000000 Z title: '2013,2034.4193' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2E7xpiKWhe6YEOymWI4W2U/97b35a4e1f3bfaa5184d701c43f0457f/2013_2034.4193.jpg" caption: "‘The Archers Of Tin Aboteka’, Tassili n’Ajjer, Algeria. 2013,2034.4193 © TARA/<NAME>" col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3601339&partId=1&images=true&people=197356&museumno=2013,2034.4193&page=1 - sys: id: 40HLnbmrO8uqoewYai0IwM created_at: !ruby/object:DateTime 2015-11-26 11:44:57.711000000 Z updated_at: !ruby/object:DateTime 2015-11-26 11:44:57.711000000 Z content_type_id: chapter revision: 1 title: Horse Period title_internal: 'Algeria: country, chapter 7' body: |- Desertification across the Sahara required new methods of traversing and utilising the landscape; depictions of horses (often with riders) and of chariots indicate this change. Horse-drawn chariots are often depicted at a ‘flying’ gallop and are likely to have been used for hunting rather than warfare. Libyan-Berber script, used by ancestral Berber peoples, started to appear in association with images. However, the meaning of this juxtaposition of text and image remains an enigma, as it is indecipherable to modern day Tuareg. - sys: id: 19xQJunRyCWOOOMKScgcqA created_at: !ruby/object:DateTime 2015-11-26 11:34:00.220000000 Z updated_at: !ruby/object:DateTime 2015-11-26 11:34:00.220000000 Z content_type_id: image revision: 1 image: sys: id: czVoXzqkG4KUm2A4QcWUO created_at: !ruby/object:DateTime 2015-11-26 11:29:42.885000000 Z updated_at: !ruby/object:DateTime 2015-11-26 11:29:42.885000000 Z title: '2013,2034.4567' description: url: "//images.ctfassets.net/xt8ne4gbbocd/czVoXzqkG4KUm2A4QcWUO/d463d9da38652be56e35908b2bde6659/2013_2034.4567.jpg" caption: Horse-drawn chariot, <NAME>, Tassili n’Ajjer, Algeria. 2013,2034.4567 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3603797&partId=1&images=true&people=197356&museumno=2013,2034.4567&page=1 - sys: id: 46nmFnhwM8uuaWOwceYYku created_at: !ruby/object:DateTime 2015-11-26 11:45:24.076000000 Z updated_at: !ruby/object:DateTime 2015-11-26 11:45:24.076000000 Z content_type_id: chapter revision: 1 title: Camel Period title_internal: 'Algeria: country, chapter 8' body: The last defined period stylistically is characterised by the depiction of camels, representing an alternative method of negotiating this arid and harsh landscape. Camels can travel for days without water and were used extensively in caravans transporting trade goods and salt. Depictions in this period continue to include domestic animals and armed figures. - sys: id: 22za3qNw1SqCCSMKiQ4ose created_at: !ruby/object:DateTime 2015-11-26 11:34:35.045000000 Z updated_at: !ruby/object:DateTime 2015-11-26 11:34:35.045000000 Z content_type_id: image revision: 1 image: sys: id: 2F8RnTvFpKGUaYYcaY2YUS created_at: !ruby/object:DateTime 2015-11-26 11:29:42.916000000 Z updated_at: !ruby/object:DateTime 2015-11-26 11:29:42.916000000 Z title: '2013,2034.4469' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2F8RnTvFpKGUaYYcaY2YUS/c940797f40d292f5d2691f43c9a974b4/2013_2034.4469.jpg" caption: Camel train Tassili n’Ajjer, Algeria. 2013,2034.4469 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3602862&partId=1&images=true&people=197356&museumno=2013,2034.4469&page=1 citations: - sys: id: 6rWROpK4k8wIAwAY8aMKo6 created_at: !ruby/object:DateTime 2015-11-26 11:35:36.510000000 Z updated_at: !ruby/object:DateTime 2015-11-26 11:35:36.510000000 Z content_type_id: citation revision: 1 citation_line: |- <NAME>. 2001. *Saharan Africa* in (ed) <NAME>, Handbook of Rock Art Research, pp 605-636. AltaMira Press, Walnut Creek Soukopova, J. 2012. *Round Heads: The Earliest Rock Paintings in the Sahara*. Newcastle upon Tyne: Cambridge Scholars Publishing [T<NAME>’Ajjer, UNESCO](http://whc.unesco.org/en/list/179/) ---<file_sep>/_coll_country/tanzania.md --- contentful: sys: id: e93mTnDufeoCyY4WeQakC created_at: !ruby/object:DateTime 2015-12-08 11:21:49.949000000 Z updated_at: !ruby/object:DateTime 2018-05-17 16:55:14.153000000 Z content_type_id: country revision: 11 name: 'Tanzania ' slug: tanzania col_url: http://www.britishmuseum.org/research/collection_online/search.aspx?searchText=Tanzania&people=197356 map_progress: true intro_progress: true image_carousel: - sys: id: 3XdtbwVgRGI2SGkC8uS6cw created_at: !ruby/object:DateTime 2016-07-27 07:42:07.278000000 Z updated_at: !ruby/object:DateTime 2019-02-12 00:53:56.681000000 Z title: TANKON0110009 description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3710252&partId=1&searchText=TANKON0110009&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/3XdtbwVgRGI2SGkC8uS6cw/8e67319576714f34f7521ad753a9b527/TANKON0110009.jpg" - sys: id: 1RjX12dAti0ESuUCG82kEW created_at: !ruby/object:DateTime 2016-07-27 07:46:32.284000000 Z updated_at: !ruby/object:DateTime 2019-02-12 00:54:54.920000000 Z title: TANKON0080019 description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3710459&partId=1&searchText=TANKON0080019&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/1RjX12dAti0ESuUCG82kEW/f7a29fec634955ae8342f913f28e5b3f/TANKON0080019.jpg" - sys: id: 3bvuMI9mP6yG26E0y4qSwa created_at: !ruby/object:DateTime 2016-07-27 07:46:32.191000000 Z updated_at: !ruby/object:DateTime 2019-02-12 00:55:28.289000000 Z title: TANKON0200004 description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3711145&partId=1&searchText=TANKON0200004&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/3bvuMI9mP6yG26E0y4qSwa/dd9e04ac6f933f74f0388d0d24a373e0/TANKON0200004.jpg" - sys: id: 3iSBoZ2eLKcMmOmGQKsK44 created_at: !ruby/object:DateTime 2016-07-27 07:46:33.052000000 Z updated_at: !ruby/object:DateTime 2019-02-12 00:56:01.910000000 Z title: TANKON0230015 description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3711246&partId=1&searchText=TANKON0230015&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/3iSBoZ2eLKcMmOmGQKsK44/bb5707d637bebe6591d2b449ee06998e/TANKON0230015.jpg" - sys: id: ghoJUHQwggGi6uuKKggcA created_at: !ruby/object:DateTime 2016-07-27 07:46:33.061000000 Z updated_at: !ruby/object:DateTime 2019-02-12 00:56:49.589000000 Z title: TANLEY0020024 description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3713196&partId=1&searchText=TANLEY0020024&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/ghoJUHQwggGi6uuKKggcA/65471af284c79e1b5548309b005cb2ac/TANLEY0020024.jpg" - sys: id: 420eZ8MlbOwq2G6iqy8Eq0 created_at: !ruby/object:DateTime 2016-07-27 07:46:33.183000000 Z updated_at: !ruby/object:DateTime 2019-02-12 00:57:25.467000000 Z title: TANKON0220001 description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3711189&partId=1&searchText=TANKON0220001&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/420eZ8MlbOwq2G6iqy8Eq0/ce10c3ffdd92d3c13ba8f3054a7ae3f9/TANKON0220001.jpg" featured_site: sys: id: 1MRBSR83yUwGoo8s4AKICk created_at: !ruby/object:DateTime 2016-07-27 07:45:12.791000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:45:12.791000000 Z content_type_id: featured_site revision: 1 title: Kolo, Tanzania slug: kolo chapters: - sys: id: 1NISbAVcjSMI4SEWE8WgAm created_at: !ruby/object:DateTime 2016-07-27 07:45:19.053000000 Z updated_at: !ruby/object:DateTime 2016-07-27 14:24:34.308000000 Z content_type_id: chapter revision: 2 title: '' title_internal: Kolo Chapter 1 body: The Kondoa rock art sites are located on the eastern slopes of the Maasai escarpment, which borders the western side of the Great Rift Valley in central Tanzania, covering an area of over 2,336 km². Stretching for around 18 km along the escarpment, the exact number of rock art sites in the Kondoa area is unknown but is estimated to be up to 450, the oldest of which are thought be more than 2,000 years old. The extensive and spectacular collection of rock paintings are attributable to both hunter-gatherer and pastoralist communities and the images are testament to the changing socio-economic environment in the region. The hunter-gatherer rock paintings of Kondoa are dominated by human figures and animals. While a dark reddish brown predominates, other colours include yellow, orange, red and white. Some of the shelters are still considered to have cultural associations with the people who live nearby, reflecting their beliefs, rituals and cosmological traditions. In 2006, Kondoa was nominated and listed as one of UNESCO’s World Heritage rock art sites in Africa. - sys: id: 2e0bNc68UUM0YKaM40Sm4C created_at: !ruby/object:DateTime 2016-07-27 07:45:11.871000000 Z updated_at: !ruby/object:DateTime 2017-01-24 15:57:32.216000000 Z content_type_id: image revision: 2 image: sys: id: 4qqgpg1KTmKwEA8kQsg8Qe created_at: !ruby/object:DateTime 2016-07-27 07:46:35.056000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:35.056000000 Z title: TANKON0030027 jpeg edited-1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/4qqgpg1KTmKwEA8kQsg8Qe/1d8fb417f4142acaf65be18c6c6b8ea0/TANKON0030027_jpeg_edited-1.jpg" caption: View looking out over Kondoa landscape. 2013,2034.16829 © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3709780&partId=1&searchText=2013,2034.16829&page=1 - sys: id: 5WqTYb2ohiCaseea44yMWg created_at: !ruby/object:DateTime 2016-07-27 07:45:19.050000000 Z updated_at: !ruby/object:DateTime 2016-07-27 14:22:52.499000000 Z content_type_id: chapter revision: 2 title: '' title_internal: 'Kolo Chapter 2 ' body: "The sites at Kolo are the most famous of the Kondoa paintings. Kolo comprises three rock art sites, known as Kolo 1, 2 and 3. The main site, Kolo 1 (known locally as Mongomi wa Kolo) is a large, imposing rock shelter that is only accessible by following a winding path at the end of a dirt road. This site contains many fine-line red paintings, some of which are very faded; but the site is still used by the local community for secret rituals. Kolo 2 is located south of the main site and includes human and animal figures, while Kolo 3 is north of Kolo1 and is characterised by human, animal and geometric figures. The renowned palaeontologist <NAME> surveyed and documented many of the paintings at Kolo in the 1950s. The examples we see here are thought to have been made by early hunter-gatherer groups, ancestors of the modern Sandawe, one of the first cultural groups to inhabit Kondoa. \n\n" - sys: id: 5JuWPWO5Z6w8aeeWMqQ8oK created_at: !ruby/object:DateTime 2016-07-27 07:45:11.850000000 Z updated_at: !ruby/object:DateTime 2017-01-24 15:58:56.845000000 Z content_type_id: image revision: 2 image: sys: id: 6hDS1W5bdSYICYEse20Wuw created_at: !ruby/object:DateTime 2016-07-27 07:46:35.991000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:35.991000000 Z title: TANKON0030032 jpeg edited-1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6hDS1W5bdSYICYEse20Wuw/48e981adce78ac63fc6ec12701fa5145/TANKON0030032_jpeg_edited-1.jpg" caption: Three slender figures with elongated bodies wearing elaborate curved feather-like headdresses. Kolo 1, Kondoa, Tanzania. 2013,2034.16832 © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3709777&partId=1&searchText=2013,2034.16832&page=1 - sys: id: 1o3g8TuJuc8MiGyQ6g6g42 created_at: !ruby/object:DateTime 2016-07-27 07:45:18.949000000 Z updated_at: !ruby/object:DateTime 2016-07-27 14:23:12.269000000 Z content_type_id: chapter revision: 2 title: '' title_internal: Kolo Chapter 3 body: "__Art__\n\nAmong the animals depicted are elephants, giraffes, antelopes, eland, rhinoceros and wildebeest; while human figures are represented as slender and elongated, often with elaborate hairstyles or headdresses, holding bows and arrows. Groups of figures are also shown bent at the waist, with some appearing to take on animal characteristics. These paintings have been associated with Sandawe cultural beliefs. \n\nThe Sandawe communicate with the spirits by taking on the power of an animal and some features at Mongomi wa Kolo can be understood by reference to the Sandawe traditional practice known as simbó (Ten Raa 1971, 1974). Developing Ten Raa’s observations, Lewis-Williams (1986) proposed that simbó is the ritual of being a lion, and that simbó dancers are believed to turn into lions. Lim (1992, 1996) adopted a site-specific approach to the rock art and has suggested that the importance of place is as important as the images themselves. According to Lim the potency of a place is produced through ritual activities, so that meaning resides in the process of painting in a particular location, rather than in the painted image itself. \ \n" - sys: id: 2H6WyW8gaISq2KgkCGa2k0 created_at: !ruby/object:DateTime 2016-07-27 07:45:18.861000000 Z updated_at: !ruby/object:DateTime 2017-01-24 16:05:45.603000000 Z content_type_id: chapter revision: 5 title_internal: Kolo chapter 4 body: |+ Ritual Practices Ritual sites are generally located near fig and baobab trees, and springs. However, about 3 m south of the main Kolo shelter, a cavity underneath a huge boulder is used, even today, by local diviners, healers and rainmakers to invoke visions and communicate with the spirits. Oral traditions indicate that Mongomi wa Kolo is considered more powerful than other ritual places in Kondoa, and its unusual location may contribute to its efficacy. The other two shelters of Kolo 2 and 3 are also used for ritual ceremonies. - sys: id: 5gBuZ4nsoo4M2QOoCOs8Cs created_at: !ruby/object:DateTime 2016-07-27 07:45:14.737000000 Z updated_at: !ruby/object:DateTime 2017-01-24 16:06:33.160000000 Z content_type_id: image revision: 3 image: sys: id: 6HJM4veidyg8KAO6WsaOcc created_at: !ruby/object:DateTime 2016-07-27 07:46:35.269000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:35.269000000 Z title: TANKON0030008 jpeg edited-1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6HJM4veidyg8KAO6WsaOcc/85bf74728415037376fb5eca97f3f527/TANKON0030008_jpeg_edited-1.jpg" caption: Group of five figures, one with animal-like head and grazing antelope on the left. Kolo 1, Kondoa, Tanzania. 2013,2034.16820 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3709705&partId=1&searchText=2013,2034.20311+&images=true&people=197356&museumno=2013,2034.16819&page=1 - sys: id: 4dRHbbM4IU0MQog4kuOCGY created_at: !ruby/object:DateTime 2016-07-27 07:45:18.820000000 Z updated_at: !ruby/object:DateTime 2016-07-27 14:23:50.727000000 Z content_type_id: chapter revision: 2 title: '' title_internal: Kolo chapter 5 body: |- __Conservation__ When <NAME> was surveying the Kondoa rock paintings in 1983 she predicted that if serious preservation and conservation measures were not put in place the paintings would be destroyed by 2020. Although inscribed onto the UNESCO World Heritage List in 2006, it has been noted paintings are being destroyed by the dust from the ground and in some cases rainwater is causing the paintings to deteriorate. - sys: id: 5SJRvFQ6NasOKwWYogwWqM created_at: !ruby/object:DateTime 2016-07-27 07:45:11.820000000 Z updated_at: !ruby/object:DateTime 2017-01-24 16:07:01.378000000 Z content_type_id: image revision: 2 image: sys: id: 27ttIF1VA4e8ekcAcea4G6 created_at: !ruby/object:DateTime 2016-07-27 07:46:35.042000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:35.042000000 Z title: TANKON0030014 jpeg edited-1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/27ttIF1VA4e8ekcAcea4G6/d705e5dbf518d996376eed7193eb1ae2/TANKON0030014_jpeg_edited-1.jpg" caption: Panel of slender red figures with elongated bodies, showing large figure bent at waist. Kolo 1, Kondoa, Tanzania. 2013,2034.16824 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3709771&partId=1&searchText=2013,2034.16824&page=1 - sys: id: 2O7PwT55ZmSSgsWkeEAQsq created_at: !ruby/object:DateTime 2016-07-27 07:45:18.796000000 Z updated_at: !ruby/object:DateTime 2016-07-27 09:51:08.628000000 Z content_type_id: chapter revision: 3 title: '' title_internal: Kolo Chapter 6 body: |+ Moreover, the documentation of paintings at Kondoa is incomplete, and some areas have not been surveyed at all. Bwasiri (2008) advocates an urgent need to collate all existing information in this region and implement a sites and monuments record that also takes into account living heritage values. - sys: id: 4xFpVDUn2EA8c0k2WWGaaK created_at: !ruby/object:DateTime 2016-07-27 07:45:11.820000000 Z updated_at: !ruby/object:DateTime 2017-01-24 16:07:17.252000000 Z content_type_id: image revision: 2 image: sys: id: 4eWYwHYojCu0EIYyoQGgMI created_at: !ruby/object:DateTime 2016-07-27 07:46:37.039000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:37.039000000 Z title: TANKON0030085 jpeg description: url: "//images.ctfassets.net/xt8ne4gbbocd/4eWYwHYojCu0EIYyoQGgMI/4b39bad47efe37b9e6d0ab830c823649/TANKON0030085_jpeg.jpg" caption: Painted panel damaged by water seepage. Kolo 1, Kondoa, Tanzania. 2013,2034.16876 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3709830&partId=1&searchText=2013,2034.16876&page=1 citations: - sys: id: 4khc2F5ABWm0kyKoUooa80 created_at: !ruby/object:DateTime 2016-07-27 07:45:18.097000000 Z updated_at: !ruby/object:DateTime 2016-07-27 09:56:15.212000000 Z content_type_id: citation revision: 3 citation_line: "<NAME> 2008. 'The Management of Indigenous Heritage: A Case Study of Mongomi wa Kolo Rock Shelter, Central Tanzania'. MA Dissertation, University of the\nWitwatersrand \n\nLeakey, M. 1983. *Africa’s Vanishing Art – The Rock Paintings of Tanzania.* London, Hamish Hamilton Ltd.\n\nLewis-Williams, J.D. 1986. ‘Beyond Style and Portrait: A Comparison of Tanzanian\nand Southern African Rock Art’. *Contemporary Studies on Khoisan 2*. Hamburg, Helmut Buske Verlag\n\nLim, I.L. 1992. ‘A Site-Oriented Approach to Rock Art: a Study from Usandawe, Central Tanzania’. PhD Thesis, University of Michigan\n\nTen Raa, E. 1971. ‘Dead Art and Living Society: A Study of Rock paintings in a Social Context’. *Mankind* 8:42-58\n\nTen Raa, E. 1974. ‘A record of some prehistoric and some recent Sandawe rock paintings’. *Tanzania Notes and Records* 75:9-27\n" background_images: - sys: id: 6cqE0uH6mswkKcOkWA6waC created_at: !ruby/object:DateTime 2016-07-27 07:46:32.004000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:32.004000000 Z title: TANKON0030029 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6cqE0uH6mswkKcOkWA6waC/7e3e2d492733456ba58f56ccbf8e5bac/TANKON0030029.jpg" - sys: id: DiswAHlgIgmsgEMUiQYm4 created_at: !ruby/object:DateTime 2016-07-27 07:46:32.111000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:32.111000000 Z title: TANKON0030077 description: url: "//images.ctfassets.net/xt8ne4gbbocd/DiswAHlgIgmsgEMUiQYm4/a68c86b9a0f96c2c658570a581af71f3/TANKON0030077.jpg" key_facts: sys: id: 3FRwoODqnSE2umUAesqOgm created_at: !ruby/object:DateTime 2016-07-27 07:45:14.756000000 Z updated_at: !ruby/object:DateTime 2016-07-27 09:48:46.210000000 Z content_type_id: country_key_facts revision: 3 title_internal: 'Tanzania: Key Facts' image_count: '1447' date_range: 10,000-3,000 years - a few hundred years ago main_areas: Kondoa region and Lake Eyasi basin techniques: Predominantly paintings with some engravings main_themes: Stylised human figures, animals, geometric motifs thematic_articles: - sys: id: 6h9anIEQRGmu8ASywMeqwc created_at: !ruby/object:DateTime 2015-11-25 17:07:20.920000000 Z updated_at: !ruby/object:DateTime 2015-12-07 20:49:54.244000000 Z content_type_id: thematic revision: 4 title: Geometric motifs and cattle brands slug: geometric-motifs lead_image: sys: id: 5yD7fOuAdU4cemkewCqCMO created_at: !ruby/object:DateTime 2015-11-25 16:56:44.778000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:56:44.778000000 Z title: '2013,2034.12976' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5yD7fOuAdU4cemkewCqCMO/4d203afb0318bee69decb23327864c79/2013_2034.12976.jpg" chapters: - sys: id: 5plObOxqdq6MuC0k4YkCQ8 created_at: !ruby/object:DateTime 2015-11-25 17:02:35.234000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:05:34.964000000 Z content_type_id: chapter revision: 3 title_internal: 'Geometric motifs: thematic, chapter 1' body: |- The rock art of eastern Africa is characterised by a wide range of non-figurative images, broadly defined as geometric. Occurring in a number of different patterns or designs, they are thought to have been in existence in this region for thousands of years, although often it is difficult to attribute the art to particular cultural groups. Geometric rock art is difficult to interpret, and designs have been variously associated with sympathetic magic, symbols of climate or fertility and altered states of consciousness (Coulson and Campbell, 2010:220). However, in some cases the motifs painted or engraved on the rock face resemble the same designs used for branding livestock and are intimately related to people’s lives and world views in this region. First observed in Kenya in the 1970s with the work of Gramly (1975) at <NAME> and Lynch and Robbins (1977) at Namoratung’a, some geometric motifs seen in the rock art of the region were observed to have had their counterparts on the hides of cattle of local communities. Although cattle branding is known to be practised by several Kenyan groups, Gramly concluded that “drawing cattle brands on the walls of rock shelters appears to be confined to the regions formerly inhabited by the Maa-speaking pastoralists or presently occupied by them”&dagger;(Gramly, 1977:117). - sys: id: 71cjHu2xrOC8O6IwSmMSS2 created_at: !ruby/object:DateTime 2015-11-25 16:57:39.559000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:06:07.592000000 Z content_type_id: image revision: 2 image: sys: id: 5yD7fOuAdU4cemkewCqCMO created_at: !ruby/object:DateTime 2015-11-25 16:56:44.778000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:56:44.778000000 Z title: '2013,2034.12976' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5yD7fOuAdU4cemkewCqCMO/4d203afb0318bee69decb23327864c79/2013_2034.12976.jpg" caption: White symbolic designs possibly representing Maa clans and livestock brands, Laikipia, Kenya. 2013,2034.12976 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3693276&partId=1&searchText=2013,2034.12976&page=1 - sys: id: 36QhSWVHKgOeMQmSMcGeWs created_at: !ruby/object:DateTime 2015-11-25 17:03:05.920000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:03:05.920000000 Z content_type_id: chapter revision: 1 title: title_internal: 'Geometric motifs: thematic, chapter 2' body: In the case of Lukenya Hill, the rock shelters on whose walls these geometric symbols occur are associated with meat-feasting ceremonies. Meat-feasting shelters exist from northern Tanzania through Kenya to Lake Turkana, and are places where Maa-speaking initiated men, who are not permitted to eat meat in their homes, gather to kill and feast on animals, predominantly cattle. During or after feasting, symbols of the animals that had been eaten were painted on the shelter ceiling in white or less often red. Maa speakers brand their cattle and camels with symbols that signify the lineage of their owners, but may also indicate if an animal has been treated for a particular disease. Different symbols may be used for male and female animals. - sys: id: 4t76LZy5zaSMGM4cUAsYOq created_at: !ruby/object:DateTime 2015-11-25 16:58:35.447000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:07:35.181000000 Z content_type_id: image revision: 2 image: sys: id: 1lBqQePHxK2Iw8wW8S8Ygw created_at: !ruby/object:DateTime 2015-11-25 16:56:44.764000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:56:44.764000000 Z title: '2013,2034.12846' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1lBqQePHxK2Iw8wW8S8Ygw/68fffb37b845614214e96ce78879c0b0/2013_2034.12846.jpg" caption: View of the long rock shelter below the waterfall showing white abstract Maasai paintings made probably quite recently during meat feasting ceremonies, Enkinyoi, Kenya. 2013,2034.12846 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3694558&partId=1&searchText=2013,2034.12846&page=1 - sys: id: 3HGWtlhoS424kQCMo6soOe created_at: !ruby/object:DateTime 2015-11-25 17:03:28.158000000 Z updated_at: !ruby/object:DateTime 2016-05-19 07:35:38.155000000 Z content_type_id: chapter revision: 2 title_internal: 'Geometric motifs: thematic, chapter 3' body: The sites of Namoratung’a near Lake Turkana in northern Kenya showed a similar visible relationship. The southernmost site is well known for its 167 megalithic stones marking male burials on which are engraved hundreds of geometric motifs. Some of these motifs bear a striking resemblance to the brand marks that the Turkana mark on their cattle, camels, donkeys and other livestock in the area, although local people claim no authorship for the funerary engravings (Russell, 2013:4). - sys: id: kgoyTkeS0oQIoaOaaWwwm created_at: !ruby/object:DateTime 2015-11-25 16:59:05.484000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:08:12.169000000 Z content_type_id: image revision: 2 image: sys: id: 19lqDiCw7UOomiMmYagQmq created_at: !ruby/object:DateTime 2015-11-25 16:56:44.756000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:56:44.756000000 Z title: '2013,2034.13006' description: url: "//images.ctfassets.net/xt8ne4gbbocd/19lqDiCw7UOomiMmYagQmq/6f54d106aaec53ed9a055dc7bf3ac014/2013_2034.13006.jpg" caption: Ndorobo man with bow and quiver of arrows kneels at a rock shelter adorned with white symbolic paintings suggesting meat-feasting rituals. Laikipia, Kenya. 2013,2034.13006 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3700172&partId=1&searchText=2013,2034.13006&page=1 - sys: id: 2JZ8EjHqi4U8kWae8oEOEw created_at: !ruby/object:DateTime 2015-11-25 17:03:56.190000000 Z updated_at: !ruby/object:DateTime 2016-05-19 07:35:15.319000000 Z content_type_id: chapter revision: 2 title_internal: 'Geometric motifs: thematic, chapter 4' body: Recent research (Russell, 2013) has shown that at Namoratung’a the branding of animals signifies a sense of belonging rather than a mark of ownership as we understand it in a modern farming context; all livestock, cattle, camel, goats, sheep and donkeys are branded according to species and sex (Russell, 2013:7). Ethnographic accounts document that clan membership can only be determined by observing someone with their livestock (Russell, 2013:9). The symbol itself is not as important as the act of placing it on the animal’s skin, and local people have confirmed that they never mark rock with brand marks. Thus, the geometric motifs on the grave markers may have been borrowed by local Turkana to serve as identity markers, but in a different context. In the Horn of Africa, some geometric rock art is located in the open landscape and on graves. It has been suggested that these too are brand or clan marks, possibly made by camel keeping pastoralists to mark achievement, territory or ownership (Russell, 2013:18). Some nomadic pastoralists, further afield, such as the Tuareg, place their clan marks along the routes they travel, carved onto salt blocks, trees and wells (Mohamed, 1990; Landais, 2001). - sys: id: 3sW37nPBleC8WSwA8SEEQM created_at: !ruby/object:DateTime 2015-11-25 16:59:47.649000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:59:47.649000000 Z content_type_id: image revision: 1 image: sys: id: 5yUlpG85GMuW2IiMeYCgyy created_at: !ruby/object:DateTime 2015-11-25 16:56:44.766000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:56:44.766000000 Z title: '2013,2034.13451' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5yUlpG85GMuW2IiMeYCgyy/a234f96f9931ec3fdddcf1ab54a33cd9/2013_2034.13451.jpg" caption: Borana cattle brands. Namoratung’a, Kenya. 2013,2034.13451. © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3660359&partId=1&searchText=2013,2034.13451&page=1 - sys: id: 6zBkbWkTaEoMAugoiuAwuK created_at: !ruby/object:DateTime 2015-11-25 17:04:38.446000000 Z updated_at: !ruby/object:DateTime 2016-05-19 07:34:17.646000000 Z content_type_id: chapter revision: 3 title_internal: 'Geometric motifs: thematic, chapter 5' body: "However, not all pastoralist geometric motifs can be associated with meat-feasting or livestock branding; they may have wider symbolism or be symbolic of something else (Russell, 2013:17). For example, informants from the Samburu people reported that while some of the painted motifs found at Samburu meat-feasting shelters were of cattle brands, others represented female headdresses or were made to mark an initiation, and in some Masai shelters there are also clear representations of warriors’ shields. In Uganda, a ceremonial rock in Karamoja, shows a dung painting consisting of large circles bisected by a cross which is said to represent cattle enclosures (Robbins, 1972). Geometric symbols, painted in fat and red ochre, on large phallic-shaped fertility stones on the Mesakin and Korongo Hills in south Sudan indicate the sex of the child to whom prayers are offered (Bell, 1936). A circle bisected by a line or circles bisected by two crosses represent boys. Girls are represented by a cross (drawn diagonally) or a slanting line (like a forward slash)(Russell, 2013: 17).\n\nAlthough pastoralist geometric motifs are widespread in the rock art of eastern Africa, attempting to find the meaning behind geometric designs is problematic. The examples discussed here demonstrate that motifs can have multiple authors, even in the same location, and that identical symbols can be the products of very different behaviours. \n" citations: - sys: id: 2oNK384LbeCqEuSIWWSGwc created_at: !ruby/object:DateTime 2015-11-25 17:01:10.748000000 Z updated_at: !ruby/object:DateTime 2016-05-19 07:33:26.748000000 Z content_type_id: citation revision: 3 citation_line: |- <NAME>. 1936. ‘Nuba fertility stones’, in *Sudan Notes and Records* 19(2), pp.313–314. Gramly R 1975. ‘Meat-feasting sites and cattle brands: Patterns of rock-shelter utilization in East Africa’ in *Azania*, 10, pp.107–121. <NAME>. 2001. ‘The marking of livestock in traditional pastoral societies’, *Scientific and Technical Review of the Office International des Epizooties* (Paris), 20 (2), pp.463–479. <NAME>. and <NAME>. 1977. ‘Animal brands and the interpretation of rock art in East Africa’ in *Current Anthropology *18, pp.538–539. Robbins LH (1972) Archaeology in the Turkana district, Kenya. Science 176(4033): 359–366 <NAME>. 2013. ‘Through the skin: exploring pastoralist marks and their meanings to understand parts of East African rock art’, in *Journal of Social Archaeology* 13:1, pp.3-30 &dagger; The term Maa relates to a group of closely related Eastern Nilotic languages, which historically dominated the east African hinterland; and today is spoken by around a million people. background_images: - sys: id: 1TDQd4TutiKwIAE8mOkYEU created_at: !ruby/object:DateTime 2015-12-07 19:16:42.825000000 Z updated_at: !ruby/object:DateTime 2015-12-07 19:16:42.825000000 Z title: KENLOK0030053 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1TDQd4TutiKwIAE8mOkYEU/718ff84615930ddafb1f1fdc67b5e479/KENLOK0030053.JPG" - sys: id: 2SCvEkDjAcIewkiu6iSGC4 created_at: !ruby/object:DateTime 2015-12-07 19:16:42.845000000 Z updated_at: !ruby/object:DateTime 2015-12-07 19:16:42.845000000 Z title: KENKAJ0030008 description: url: "//images.ctfassets.net/xt8ne4gbbocd/2SCvEkDjAcIewkiu6iSGC4/b2e2e928e5d9a6a25aca5c99058dfd76/KENKAJ0030008.jpg" - sys: id: 5HZTuIVN8AASS4ikIea6m6 created_at: !ruby/object:DateTime 2017-12-19 12:27:08.508000000 Z updated_at: !ruby/object:DateTime 2017-12-19 12:27:08.508000000 Z content_type_id: thematic revision: 1 title: Introduction to rock art in central and eastern Africa slug: rock-art-in-central-and-east-africa lead_image: sys: id: 3esXNapo5GOWIKSImcY4QW created_at: !ruby/object:DateTime 2015-11-25 18:56:43.836000000 Z updated_at: !ruby/object:DateTime 2017-12-15 17:01:05.082000000 Z title: '2013,2034.12982' description: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3776396 url: "//images.ctfassets.net/xt8ne4gbbocd/3esXNapo5GOWIKSImcY4QW/6436b2034659eccb953844b21a400070/2013_2034.12982.jpg" chapters: - sys: id: 4ln5fQLq2saMKsOA4WSAgc created_at: !ruby/object:DateTime 2015-11-25 19:09:33.580000000 Z updated_at: !ruby/object:DateTime 2015-12-11 11:17:25.155000000 Z content_type_id: chapter revision: 4 title: Central and East Africa title_internal: 'East Africa: regional, chapter 1' body: |- Central Africa is dominated by vast river systems and lakes, particularly the Congo River Basin. Characterised by hot and wet weather on both sides of the equator, central Africa has no regular dry season, but aridity increases in intensity both north and south of the equator. Covered with a forest of about 400,000 m² (1,035,920 km²), it is one of the greenest parts of the continent. The rock art of central Africa stretches from the Zambezi River to the Angolan Atlantic coast and reaches as far north as Cameroon and Uganda. Termed the ‘schematic rock art zone’ by <NAME> (1959), it is dominated by finger-painted geometric motifs and designs, thought to extend back many thousands of years. Eastern Africa, from the Zambezi River Valley to Lake Turkana, consists largely of a vast inland plateau with the highest elevations on the continent, such as Mount Kilimanjaro (5,895m above sea level) and Mount Kenya (5,199 m above sea level). Twin parallel rift valleys run through the region, which includes the world’s second largest freshwater lake, Lake Victoria. The climate is atypical of an equatorial region, being cool and dry due to the high altitude and monsoon winds created by the Ethiopian Highlands. The rock art of eastern Africa is concentrated on this plateau and consists mainly of paintings that include animal and human representations. Found mostly in central Tanzania, eastern Zambia and Malawi; in comparison to the widespread distribution of geometric rock art, this figurative tradition is much more localised, and found at just a few hundred sites in a region of less than 100km in diameter. - sys: id: 4nyZGLwHTO2CK8a2uc2q6U created_at: !ruby/object:DateTime 2015-11-25 18:57:48.121000000 Z updated_at: !ruby/object:DateTime 2017-12-15 17:05:00.916000000 Z content_type_id: image revision: 2 image: sys: id: 3esXNapo5GOWIKSImcY4QW created_at: !ruby/object:DateTime 2015-11-25 18:56:43.836000000 Z updated_at: !ruby/object:DateTime 2017-12-15 17:01:05.082000000 Z title: '2013,2034.12982' description: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3776396 url: "//images.ctfassets.net/xt8ne4gbbocd/3esXNapo5GOWIKSImcY4QW/6436b2034659eccb953844b21a400070/2013_2034.12982.jpg" caption: Laikipia, Kenya. 2013,2034.12982 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3776396 - sys: id: 1OvIWDPyXaCO2gCWw04s06 created_at: !ruby/object:DateTime 2015-11-25 19:10:23.723000000 Z updated_at: !ruby/object:DateTime 2015-12-11 11:18:19.325000000 Z content_type_id: chapter revision: 2 title_internal: 'East Africa: regional, chapter 2' body: This collection from Central and East Africa comprises rock art from Kenya, Uganda and Tanzania, as well as the Horn of Africa; although predominantly paintings, engravings can be found in most countries. - sys: id: 4JqI2c7CnYCe8Wy2SmesCi created_at: !ruby/object:DateTime 2015-11-25 19:10:59.991000000 Z updated_at: !ruby/object:DateTime 2016-10-17 13:34:14.653000000 Z content_type_id: chapter revision: 3 title: History of research title_internal: 'East Africa: regional, chapter 3' body: |- The rock art of East Africa, in particular the red paintings from Tanzania, was extensively studied by Mary and <NAME> in the 1930s and 1950s. <NAME> observed Sandawe people of Tanzania making rock paintings in the mid-20th century, and on the basis of oral traditions argued that the rock art was made for three main purposes: casual art; magic art (for hunting purposes or connected to health and fertility) and sacrificial art (to appease ancestral spirits). Subsequently, during the 1970s Fidelis Masao and <NAME> recorded numerous sites, classifying the art in broad chronological and stylistic categories, proposing tentative interpretations with regard to meaning. There has much debate and uncertainty about Central African rock art. The history of the region has seen much mobility and interaction of cultural groups and understanding how the rock art relates to particular groups has been problematic. Pioneering work in this region was undertaken by <NAME> in central Malawi in the early 1920s, <NAME> visited Zambia in 1936 and attempted to provide a chronological sequence and some insight into the meaning of the rock art. Since the 1950s (Clarke, 1959), archaeologists have attempted to situate rock art within broader archaeological frameworks in order to resolve chronologies, and to categorise the art with reference to style, colour, superimposition, subject matter, weathering, and positioning of depictions within the panel (Phillipson, 1976). Building on this work, our current understanding of rock in this region has been advanced by <NAME> (1995, 1997, 2001) with his work in Zambia and Malawi. - sys: id: 35HMFoiKViegWSY044QY8K created_at: !ruby/object:DateTime 2015-11-25 18:59:25.796000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:51:25.789000000 Z content_type_id: image revision: 5 image: sys: id: 6KOxC43Z9mYCuIuqcC8Qw0 created_at: !ruby/object:DateTime 2015-11-25 18:57:00.077000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:57:00.077000000 Z title: '2013,2034.17450' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6KOxC43Z9mYCuIuqcC8Qw0/e25141d07f483d0100c4cf5604e3e525/2013_2034.17450.jpg" caption: This painting of a large antelope is possibly one of the earliest extant paintings. <NAME> believes similar paintings could be more than 28,000 years old. 2013,2034.17450 © TARA/<NAME>oulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3711689 - sys: id: 1dSBI9UNs86G66UGSEOOkS created_at: !ruby/object:DateTime 2015-12-09 11:56:31.754000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:50:18.203000000 Z content_type_id: chapter revision: 5 title: East African Rock Art title_internal: Intro to east africa, chapter 3.5 body: "Rock art of East Africa consists mainly of paintings, most of which are found in central Tanzania, and are fewer in number in eastern Zambia and Malawi; scholars have categorised them as follows:\n\n*__Red Paintings__*: \nRed paintings can be sub-divided into those found in central Tanzania and those found stretching from Zambia to the Indian Ocean.\nTanzanian red paintings include large, naturalistic animals with occasional geometric motifs. The giraffe is the most frequently painted animal, but antelope, zebra, elephant, rhino, felines and ostrich are also depicted. Later images show figures with highly distinctive stylised human head forms or hairstyles and body decoration, sometimes in apparent hunting and domestic scenes. The Sandawe and Hadza, hunter-gatherer groups, indigenous to north-central and central Tanzania respectively, claim their ancestors were responsible for some of the later art.\n\nThe area in which Sandawe rock art is found is less than 100km in diameter and occurs at just a few hundred sites, but corresponds closely to the known distribution of this group. There have been some suggestions that Sandawe were making rock art early into the 20th century, linking the art to particular rituals, in particular simbo; a trance dance in which the Sandawe communicate with the spirit world by taking on the power of an animal. The art displays a range of motifs and postures, features that can be understood by reference to simbo and to trance experiences; such as groups of human figures bending at the waist (which occurs during the *simbo* dance), taking on animal features such as ears and tails, and floating or flying; reflecting the experiences of those possessed in the dance." - sys: id: 7dIhjtbR5Y6u0yceG6y8c0 created_at: !ruby/object:DateTime 2015-11-25 19:00:07.434000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:51:51.887000000 Z content_type_id: image revision: 5 image: sys: id: 1fy9DD4BWwugeqkakqWiUA created_at: !ruby/object:DateTime 2015-11-25 18:57:11.188000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:57:11.188000000 Z title: '2013,2034.16849' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1fy9DD4BWwugeqkakqWiUA/9f8f1330c6c0bc0ff46d744488daa152/2013_2034.16849.jpg" caption: Three schematic figures formed by the use of multiple thin parallel lines. The shape and composition of the heads suggests either headdresses or elaborate hairstyles. Kondoa, Tanzania. 2013,2034.16849 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3709812 - sys: id: 1W573pi2Paks0iA8uaiImy created_at: !ruby/object:DateTime 2015-11-25 19:12:00.544000000 Z updated_at: !ruby/object:DateTime 2015-12-11 11:21:09.647000000 Z content_type_id: chapter revision: 8 title_internal: 'East Africa: regional, chapter 4' body: "Zambian rock art does not share any similarities with Tanzanian rock art and can be divided into two categories; animals (with a few depictions of humans), and geometric motifs. Animals are often highly stylised and superimposed with rows of dots. Geometric designs include, circles, some of which have radiating lines, concentric circles, parallel lines and ladder shapes. Predominantly painted in red, the remains of white pigment is still often visible. David Phillipson (1976) proposed that the naturalistic animals were earlier in date than geometric designs. Building on Phillipson’s work, <NAME> studied ethnographic records and demonstrated that geometric motifs were made by women or controlling the weather.\n\n*__Pastoralist paintings__*: \nPastoralist paintings are rare, with only a few known sites in Kenya and other possible sites in Malawi. Usually painted in black, white and grey, but also in other colours, they include small outlines, often infilled, of cattle and are occasional accompanied by geometric motifs. Made during the period from 3,200 to 1,800 years ago the practice ceased after Bantu language speaking people had settled in eastern Africa. Similar paintings are found in Ethiopia but not in southern Africa, and it has been assumed that these were made by Cushitic or Nilotic speaking groups, but their precise attribution remains unclear (Smith, 2013:154).\n" - sys: id: 5jReHrdk4okicG0kyCsS6w created_at: !ruby/object:DateTime 2015-11-25 19:00:41.789000000 Z updated_at: !ruby/object:DateTime 2017-12-15 17:10:04.890000000 Z content_type_id: image revision: 3 image: sys: id: 1hoZEK3d2Oi8iiWqoWACo created_at: !ruby/object:DateTime 2015-11-25 18:56:43.848000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:56:43.848000000 Z title: '2013,2034.13653' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1hoZEK3d2Oi8iiWqoWACo/1a1adcfad5d5a1cf0a341316725d61c4/2013_2034.13653.jpg" caption: Two red bulls face right. Mt Elgon, Kenya. 2013,2034.13653. © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3700058 - sys: id: 7rFAK9YoBqYs0u0EmCiY64 created_at: !ruby/object:DateTime 2015-11-25 19:00:58.494000000 Z updated_at: !ruby/object:DateTime 2017-12-15 17:11:37.760000000 Z content_type_id: image revision: 3 image: sys: id: 3bqDVyvXlS0S6AeY2yEmS8 created_at: !ruby/object:DateTime 2015-11-25 18:56:43.880000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:56:43.880000000 Z title: '2013,2034.13635' description: url: "//images.ctfassets.net/xt8ne4gbbocd/3bqDVyvXlS0S6AeY2yEmS8/c9921f3d8080bcef03c96c6b8f1b0323/2013_2034.13635.jpg" caption: Two cattle with horns in twisted perspective. Mt Elgon, Kenya. 2013,2034.13635. © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3698905 - sys: id: 1tX4nhIUgAGmyQ4yoG6WEY created_at: !ruby/object:DateTime 2015-11-25 19:14:33.823000000 Z updated_at: !ruby/object:DateTime 2015-11-25 19:14:33.823000000 Z content_type_id: chapter revision: 1 title_internal: 'East Africa: regional, chapter 5' body: |- *__Late White Paintings__*: Commonly painted in white, or off-white with the fingers, so-called ‘Late White’ depictions include quite large crudely rendered representations of wild animals, mythical animals, human figures and numerous geometric motifs. These paintings are attributed to Bantu language speaking, iron-working farmers who entered eastern Africa about 2,000 years ago from the west on the border of Nigeria and Cameroon. Moving through areas occupied by the Batwa it is thought they learned the use of symbols painted on rock, skin, bark cloth and in sand. Chewa peoples, Bantu language speakers who live in modern day Zambia and Malawi claim their ancestors made many of the more recent paintings which they used in rites of passage ceremonies. - sys: id: 35dNvNmIxaKoUwCMeSEO2Y created_at: !ruby/object:DateTime 2015-11-25 19:01:26.458000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:52:15.838000000 Z content_type_id: image revision: 4 image: sys: id: 6RGZZQ13qMQwmGI86Ey8ei created_at: !ruby/object:DateTime 2015-11-25 18:57:11.188000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:57:11.188000000 Z title: '2013,2034.16786' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6RGZZQ13qMQwmGI86Ey8ei/6d37a5bed439caf7a1223aca27dc27f8/2013_2034.16786.jpg" caption: Under a long narrow granite overhang, Late White designs including rectangular grids, concentric circles and various ‘square’ shapes. 2013,2034.16786 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3709608 - sys: id: 2XW0X9BzFCa8u2qiKu6ckK created_at: !ruby/object:DateTime 2015-11-25 19:01:57.959000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:53:21.559000000 Z content_type_id: image revision: 4 image: sys: id: 1UT4r6kWRiyiUIYSkGoACm created_at: !ruby/object:DateTime 2015-11-25 18:57:11.138000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:57:11.138000000 Z title: '2013,2034.16797' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1UT4r6kWRiyiUIYSkGoACm/fe915c6869b6c195d55b5ef805df7671/2013_2034.16797.jpg" caption: A monuments guard stands next to Late White paintings attributed to Bantu speaking farmers in Tanzania, probably made during the last 700 years. 2013,2034.16797 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3709628 - sys: id: 3z28O8A58AkgMUocSYEuWw created_at: !ruby/object:DateTime 2015-11-25 19:15:04.047000000 Z updated_at: !ruby/object:DateTime 2015-11-25 19:15:04.047000000 Z content_type_id: chapter revision: 1 title_internal: 'East Africa: regional, chapter 6' body: |- *__Meat-feasting paintings__*: Meat-feasting shelters exist from northern Tanzania through Kenya to Lake Turkana, and are places where Maa-speaking initiated men, who are not permitted to eat meat in their homes, gather to kill and feast on animals, predominantly cattle. The term Maa relates to a group of closely related Eastern Nilotic languages, which historically dominated the east African hinterland; and today is spoken by around a million people. During or after feasting, symbols of the animals that had been eaten were painted on the shelter ceiling in white or less often red. Maa speakers brand their cattle and camels with symbols that signify the lineage of their owners, but may also indicate if an animal has been treated for a particular disease. Different symbols may be used for male and female animals. Over the centuries, because the depictions are on the ceiling of meat feasting rock shelters, and because sites are used even today, a build-up of soot has obscured or obliterated the paintings. Unfortunately, few have been recorded or mapped. - sys: id: 1yjQJMFd3awKmGSakUqWGo created_at: !ruby/object:DateTime 2015-11-25 19:02:23.595000000 Z updated_at: !ruby/object:DateTime 2017-12-15 17:19:11.619000000 Z content_type_id: image revision: 3 image: sys: id: p4E0BRJzossaus6uUUkuG created_at: !ruby/object:DateTime 2015-11-25 18:56:49.743000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:56:49.743000000 Z title: '2013,2034.13004' description: url: "//images.ctfassets.net/xt8ne4gbbocd/p4E0BRJzossaus6uUUkuG/13562eee76ac2a9efe8c0d12e62fa23a/2013_2034.13004.jpg" caption: Huge granite boulder with Ndorobo man standing before a rock overhang used for meat-feasting. Laikipia, Kenya. 2013,2034. 13004. © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3700175 - sys: id: 6lgjLZVYrY606OwmwgcmG2 created_at: !ruby/object:DateTime 2015-11-25 19:02:45.427000000 Z updated_at: !ruby/object:DateTime 2017-12-15 17:20:14.877000000 Z content_type_id: image revision: 3 image: sys: id: 1RLyVKKV8MA4KEk4M28wqw created_at: !ruby/object:DateTime 2015-11-25 18:57:11.150000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:57:11.150000000 Z title: '2013,2034.13018' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1RLyVKKV8MA4KEk4M28wqw/044529be14a590fd1d0da7456630bb0b/2013_2034.13018.jpg" caption: This symbol is probably a ‘brand’ used on cattle that were killed and eaten at a Maa meat feast. Laikipia, Kenya. 2013,2034.13018 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3700193 - sys: id: 5UQc80DUBiqqm64akmCUYE created_at: !ruby/object:DateTime 2015-11-25 19:15:34.582000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:53:53.936000000 Z content_type_id: chapter revision: 4 title: Central African Rock Art title_internal: 'East Africa: regional, chapter 7' body: The rock art of central Africa is attributed to hunter-gatherers known as Batwa. This term is used widely in eastern central and southern Africa to denote any autochthonous hunter-gatherer people. The rock art of the Batwa can be divided into two categories which are quite distinctive stylistically from the Tanzanian depictions of the Sandawe and Hadza. Nearly 3,000 sites are currently known from within this area. The vast majority, around 90%, consist of finger-painted geometric designs; the remaining 10% include highly stylised animal forms (with a few human figures) and rows of finger dots. Both types are thought to date back many thousands of years. The two traditions co-occur over a vast area of eastern and central Africa and while often found in close proximity to each other are only found together at a few sites. However, it is the dominance of geometric motifs that make this rock art tradition very distinctive from other regions in Africa. - sys: id: 4m51rMBDX22msGmAcw8ESw created_at: !ruby/object:DateTime 2015-11-25 19:03:40.666000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:54:25.415000000 Z content_type_id: image revision: 4 image: sys: id: 2MOrR79hMcO2i8G2oAm2ik created_at: !ruby/object:DateTime 2015-11-25 18:56:49.737000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:56:49.737000000 Z title: '2013,2034.15306' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2MOrR79hMcO2i8G2oAm2ik/86179e84233956e34103566035c14b76/2013_2034.15306.jpg" caption: Paintings in red and originally in-filled in white cover the underside of a rock shelter roof. The art is attributed to central African Batwa; the age of the paintings is uncertain. Lake Victoria, Uganda. 2013,2034.15306 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3691242 - sys: id: 5rNOG3568geMmIEkIwOIac created_at: !ruby/object:DateTime 2015-11-25 19:16:07.130000000 Z updated_at: !ruby/object:DateTime 2015-11-25 19:16:19.722000000 Z content_type_id: chapter revision: 2 title_internal: 'East Africa: regional, chapter 8' body: "*__Engravings__*:\nThere are a few engravings occurring on inland plateaus but these have elicited little scientific interest and are not well documented. \ Those at the southern end of Lake Turkana have been categorised into two types: firstly, animals, human figures and geometric forms and also geometric forms thought to involve lineage symbols.\nIn southern Ethiopia, near the town of Dillo about 300 stelae, some of which stand up to two metres in height, are fixed into stones and mark grave sites. People living at the site ask its spirits for good harvests. \n" - sys: id: LrZuJZEH8OC2s402WQ0a6 created_at: !ruby/object:DateTime 2015-11-25 19:03:59.496000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:54:51.576000000 Z content_type_id: image revision: 5 image: sys: id: 1uc9hASXXeCIoeMgoOuO4e created_at: !ruby/object:DateTime 2015-11-25 18:57:11.176000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:57:11.176000000 Z title: '2013,2034.16206' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1uc9hASXXeCIoeMgoOuO4e/09a7504449897509778f3b9455a42f8d/2013_2034.16206.jpg" caption: Group of anthropomorphic stelae with carved faces. <NAME>, Southern Ethiopia. 2013,2034.16206 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3703754 - sys: id: 7EBTx1IjKw6y2AUgYUkAcm created_at: !ruby/object:DateTime 2015-11-25 19:16:37.210000000 Z updated_at: !ruby/object:DateTime 2015-12-11 11:22:04.007000000 Z content_type_id: chapter revision: 2 title_internal: 'East Africa: regional, chapter 9' body: In the Sidamo region of Ethiopia, around 50 images of cattle are engraved in bas-relief on the wall of a gorge. All the engravings face right and the cows’ udders are prominently displayed. Similar engravings of cattle, all close to flowing water, occur at five other sites in the area, although not in such large numbers. - sys: id: 6MUkxUNFW8oEK2aqIEcee created_at: !ruby/object:DateTime 2015-11-25 19:04:34.186000000 Z updated_at: !ruby/object:DateTime 2017-12-19 12:22:24.891000000 Z content_type_id: image revision: 3 image: sys: id: PlhtduNGSaOIOKU4iYu8A created_at: !ruby/object:DateTime 2015-11-25 18:56:43.849000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:56:43.849000000 Z title: '2013,2034.16235' description: url: "//images.ctfassets.net/xt8ne4gbbocd/PlhtduNGSaOIOKU4iYu8A/7625c8a21caf60046ea73f184e8b5c76/2013_2034.16235.jpg" caption: Around 50 images of cattle are engraved in bas-relief into the sandstone wall of a gorge in the Sidamo region of Ethiopia. 2013,2034.16235 © TARA/David Coulson col_link: http://bit.ly/2hMU0vm - sys: id: 6vT5DOy7JK2oqgGK8EOmCg created_at: !ruby/object:DateTime 2015-11-25 19:17:53.336000000 Z updated_at: !ruby/object:DateTime 2015-12-11 11:25:38.678000000 Z content_type_id: chapter revision: 3 title: Rock art in the Horn of Africa title_internal: 'East Africa: regional, chapter 10' body: "The Horn of Africa has historically been a crossroads area between the Eastern Sahara, the Subtropical regions to the South and the Arabic Peninsula. These mixed influences can be seen in many archaeological and historical features throughout the region, the rock art being no exception. Since the early stages of research in the 1930s, a strong relationship between the rock art in Ethiopia and the Arabian Peninsula was detected, leading to the establishment of the term *Ethiopian-Arabian* rock art by <NAME> in 1971. This research thread proposes a progressive evolution from naturalism to schematism, ranging from the 4th-3rd millennium BC to the near past. Although the *Ethiopian-Arabian* proposal is still widely accepted and stylistic similarities between the rock art of Somalia, Ethiopia, Yemen or Saudi Arabia are undeniable, recent voices have been raised against the term because of its excessive generalisation and lack of operability. In addition, recent research to the south of Ethiopia have started to discover new rock art sites related to those found in Uganda and Kenya.\n\nRegarding the main themes of the Horn of Africa rock art, cattle depictions seem to have been paramount, with cows and bulls depicted either isolated or in herds, frequently associated with ritual scenes which show their importance in these communities. Other animals – zebus, camels, felines, dogs, etc. – are also represented, as well as rows of human figures, and fighting scenes between warriors or against lions. Geometric symbols are also common, usually associated with other depictions; and in some places they have been interpreted as tribal or clan marks. Both engraving and painting is common in most regions, with many regional variations. \n" - sys: id: 4XIIE3lDZYeqCG6CUOYsIG created_at: !ruby/object:DateTime 2015-11-25 19:04:53.913000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:55:12.472000000 Z content_type_id: image revision: 4 image: sys: id: 3ylztNmm2cYU0GgQuW0yiM created_at: !ruby/object:DateTime 2015-11-25 18:57:11.155000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:57:11.155000000 Z title: '2013,2034.15749' description: url: "//images.ctfassets.net/xt8ne4gbbocd/3ylztNmm2cYU0GgQuW0yiM/3be240bf82adfb5affc0d653e353350b/2013_2034.15749.jpg" caption: Painted roof of rock shelter showing decorated cows and human figures. <NAME>, Somaliland. 2013,2034.15749 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3691391 - sys: id: 2IKYx0YIVOyMSwkU8mQQM created_at: !ruby/object:DateTime 2015-11-25 19:18:28.056000000 Z updated_at: !ruby/object:DateTime 2015-12-11 11:26:13.401000000 Z content_type_id: chapter revision: 2 title_internal: 'East Africa: regional, chapter 11' body: |- Rock art in the Horn of Africa faces several challenges. One of them is the lack of consolidated chronologies and absolute dating for the paintings and engravings. Another is the uneven knowledge of rock art throughout the region, with research often affected by political unrest. Therefore, distributions of rock art in the region are steadily growing as research is undertaken in one of the most interactive areas in East Africa. The rock art of Central and East Africa is one of the least documented and well understood of the corpus of African rock art. However, in recent years scholars have undertaken some comprehensive reviews of existing sites and surveys of new sites to open up the debates and more fully understand the complexities of this region. citations: - sys: id: 7d9bmwn5kccgO2gKC6W2Ys created_at: !ruby/object:DateTime 2015-11-25 19:08:04.014000000 Z updated_at: !ruby/object:DateTime 2017-12-19 12:24:18.659000000 Z content_type_id: citation revision: 2 citation_line: "<NAME>. 1996. ‘Cultural Patterns in the Rock Art of Central Tanzania.’ in *The Prehistory of Africa*. XIII International Congress of Prehistoric and Protohistoric Sciences Forli-Italia-8/14 September.\n\nČerviček, P. 1971. ‘Rock paintings of Laga Oda (Ethiopia)’ in *Paideuma*, 17, pp.121-136.\n\nClark, <NAME>. 1954. *The Prehistoric Cultures of the Horn of Africa*. New York: Octagon Press.\n\n<NAME>. 1959. ‘Rock Paintings of Northern Rhodesia and Nyasaland’, in Summers, R. (ed.) *Prehistoric Rock Art of the Federation of Rhodesia & Nyasaland*: Glasgow: National Publication Trust, pp.163- 220.\n\nJoussaume, R. (ed.) 1995. Tiya, *l’Ethiopie des mégalithes : du biface à l’art rupestre dans la Corne de l’Afrique*. Association des publications chauvinoises (A.P.C.), Chauvigny.\n\n<NAME>. 1983. *Africa’s Vanishing Art – The Rock Paintings of Tanzania*. London: Hamish Hamilton Ltd.\n\nMasao, F.T. 1979. *The Later Stone Age and the Rock Paintings of Central Tanzania*. Wiesbaden: Franz Steiner Verlag. \n\nNamono, Catherine. 2010. *A contextual interpretive approach to the rock art of Uganda*. Unpublished PhD Thesis. Johannesburg: University of Witwatersrand\n\nPhillipson, D.W. 1976. ‘The Rock Paintings of Eastern Zambia’, in *The Prehistory of Eastern Zambia: Memoir 6 of the british Institute in Eastern Africa*. Nairobi.\n\n<NAME>. (1995), Rock art in south-Central Africa: A study based on the pictographs of Dedza District, Malawi and Kasama District Zambia. dissertation. Cambridge: University of Cambridge, Unpublished Ph.D. dissertation.\n\n<NAME>. (1997), Zambia’s ancient rock art: The paintings of Kasama. Zambia: The National Heritage Conservation Commission of Zambia.\n\nSmith B.W. (2001), Forbidden images: Rock paintings and the Nyau secret society of Central Malaŵi and Eastern Zambia. *African Archaeological Review*18(4): 187–211.\n\n<NAME>. 2013, ‘Rock art research in Africa; in In: Lane, P. & Mitchell, P. (eds) *Handbook of African Archaeology*. Oxford: Oxford University Press, pp.145-162.\n\nTen Raa, E. 1974. ‘A record of some prehistoric and some recent Sandawe rock paintings’ in *Tanzania Notes and Records* 75, pp.9-27." background_images: - sys: id: 4aeKk2gBTiE6Es8qMC4eYq created_at: !ruby/object:DateTime 2015-12-07 19:42:27.348000000 Z updated_at: !ruby/object:DateTime 2017-12-19 12:25:55.914000000 Z title: '2013,2034.1298' description: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3592557 url: "//images.ctfassets.net/xt8ne4gbbocd/4aeKk2gBTiE6Es8qMC4eYq/31cde536c4abf1c0795761f8e35b255c/2013_2034.1298.jpg" - sys: id: 6DbMO4lEBOU06CeAsEE8aA created_at: !ruby/object:DateTime 2015-12-07 19:41:53.440000000 Z updated_at: !ruby/object:DateTime 2017-12-19 12:26:40.898000000 Z title: '2013,2034.15749' description: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3691391 url: "//images.ctfassets.net/xt8ne4gbbocd/6DbMO4lEBOU06CeAsEE8aA/9fc2e1d88f73a01852e1871f631bf4ff/2013_2034.15749.jpg" country_introduction: sys: id: 1LiwPCnyFKmciIOKysACI0 created_at: !ruby/object:DateTime 2016-07-27 07:44:27.856000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:44:27.856000000 Z content_type_id: country_information revision: 1 title: 'Tanzania: Country Introduction' chapters: - sys: id: 43gtar9Bd6iwSOOug8Ca2K created_at: !ruby/object:DateTime 2016-07-27 07:45:18.035000000 Z updated_at: !ruby/object:DateTime 2016-07-27 12:30:57.863000000 Z content_type_id: chapter revision: 3 title: Introduction title_internal: Tanzania Chapter 1 body: Containing some of the densest concentrations of rock art in East Africa, Tanzania includes many different styles and periods of rock art, the earliest of which may date back 10,000 years. Consisting mainly of paintings, rock art is found predominantly in the Kondoa region and the adjoining Lake Eyasi basin. Those at Kondoa were inscribed as a UNESCO World Heritage site in 2006, and were the first to be documented by missionaries in 1908. - sys: id: 3cunSLA63KsGEGIw0C8ki created_at: !ruby/object:DateTime 2016-07-27 07:45:11.825000000 Z updated_at: !ruby/object:DateTime 2017-01-24 15:37:31.932000000 Z content_type_id: image revision: 2 image: sys: id: 6jqxlKBK8ggSwAyOIWC2w created_at: !ruby/object:DateTime 2016-07-27 07:46:37.419000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:37.419000000 Z title: TANKON0130004 jpeg description: url: "//images.ctfassets.net/xt8ne4gbbocd/6jqxlKBK8ggSwAyOIWC2w/62820080f1ce2792a5bbc9c38ac89b50/TANKON0130004_jpeg.jpg" caption: Painted panel of fine-line paintings of kudu and human figures with bow and arrow. Msokia, Kondoa, Tanzania. 2013,2034.17086 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3710216&partId=1&searchText=2013,2034.17086&page=1 - sys: id: 3fuknu8MJiS2CEUo8c48Mm created_at: !ruby/object:DateTime 2016-07-27 07:45:16.738000000 Z updated_at: !ruby/object:DateTime 2016-07-27 08:44:49.657000000 Z content_type_id: chapter revision: 3 title: Geography and Rock Art distribution title_internal: Tanzania Chapter 2 body: |- Situated within the Great Lakes Region of East Africa, Tanzania is bordered by Kenya and Uganda to the north; Rwanda, Burundi, and the Democratic Republic of the Congo to the west; Zambia, Malawi, and Mozambique to the south; and the Indian Ocean to the east, with a coastline of approx. 800km. At 947,303 km², Tanzania is the largest country in East Africa and is home to Africa's highest mountain, Kilimanjaro (5,895 m, 19,340 feet), located in the north-east of the country. Central Tanzania is comprised largely of a plateau, which is mainly grassland and contains many national parks. The north of the country is predominantly arable and includes the national capital of Dodoma. The north-east of the country is mountainous and contains the eastern arm of the Great Rift Valley. Further north-west is Lake Victoria adjoining the Kenya–Uganda–Tanzania border. Concentrations of rock art are found mainly in the Kondoa province of central Tanzania and also the Lake Eyasi Basin in the north of the country. The rock art of the Lake Eyasi Basin and that of Kondoa share many similarities related to subject matter, styles, pigments and even types of sites. This may possibly reflect a shared art tradition among hunter-gatherers, which is feasible as there are no natural barriers preventing the movement of cultural ideas and techniques. - sys: id: 5bWgTlQsXCq2OQC0Koa8OU created_at: !ruby/object:DateTime 2016-07-27 07:45:10.912000000 Z updated_at: !ruby/object:DateTime 2017-01-24 15:38:18.560000000 Z content_type_id: image revision: 2 image: sys: id: 5XVIPjHq7K4MiWIm6i6qEk created_at: !ruby/object:DateTime 2016-07-27 07:46:38.051000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:38.051000000 Z title: TANKON0310006 jpeg description: url: "//images.ctfassets.net/xt8ne4gbbocd/5XVIPjHq7K4MiWIm6i6qEk/55d7e3497c0e2715ad2fe7605c49d533/TANKON0310006_jpeg.jpg" caption: Elongated red figure facing right with rounded head and holding a narrow rectangular object (shield?); the image has been damaged by white water seepage. Kondoa, Tanzania. 2013,2034.17497 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3712306&partId=1&searchText=2013,2034.17497&page=1 - sys: id: 2s5iBeDTAMk8Y2Awqc024i created_at: !ruby/object:DateTime 2016-07-27 07:45:18.020000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:45:18.020000000 Z content_type_id: chapter revision: 1 title: History of rock art research in Tanzania title_internal: Tanzania Chapter 3 body: 'The existence of painted rock art was first reported to Europeans in 1908 by missionaries, but the first scientific explorations date back to the 1930s. Early surveys were undertaken by <NAME> (1958), a German physician, amateur anthropologist and explorer, who traced images in more than 70 rock shelters in 1935. The renowned paleoanthropologists Mary and <NAME> (1983) were the first to extensively study the rock art of Tanzania during the 1930s and 1950s (having noted many sites in the 1920s), documenting over 1600 painted images at 186 sites north of Kondoa. In the late 1970s and during the 1980s Fidelis Masao (1979) surveyed 68 rock paintings sites and excavated four of them while <NAME> (1996) recorded 200 sites in Kondoa. Other researchers include <NAME> (1971, 1974), <NAME> (1986), <NAME> (1992), and <NAME> (2008, 2011); all of whom have recorded numerous sites, contributing to identifying chronologies, styles and possible interpretations. Conservation and preservation of the rock art has been of importance since the 1930s, and many of the paintings recorded by the Leakeys in the early 1950s are now severely deteriorated, or in some cases completely destroyed. ' - sys: id: MsqR1AiFOKQqiySkEIAwQ created_at: !ruby/object:DateTime 2016-07-27 07:45:10.806000000 Z updated_at: !ruby/object:DateTime 2017-01-24 15:41:21.774000000 Z content_type_id: image revision: 2 image: sys: id: 28qJxjtSOoC6Aa2IgQk06q created_at: !ruby/object:DateTime 2016-07-27 07:46:37.137000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:37.137000000 Z title: TANKON0050001 jpeg description: url: "//images.ctfassets.net/xt8ne4gbbocd/28qJxjtSOoC6Aa2IgQk06q/9d9b407dd70a62d06c4a95db72c0e9eb/TANKON0050001_jpeg.jpg" caption: View looking out of rock shelter over Kondoa region, Tanzania. 2013,2034.16942 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3709993&partId=1&searchText=2013,2034.16942&page=1 - sys: id: i9BKWyIrJeYSQICcciYGC created_at: !ruby/object:DateTime 2016-07-27 07:45:16.691000000 Z updated_at: !ruby/object:DateTime 2016-07-27 12:32:37.897000000 Z content_type_id: chapter revision: 4 title: Chronologies title_internal: Tanzania Chapter 4 body: "Scholars have classified the rock art in Tanzania into three main stylistic groups: Hunter-gatherer, also known as Sandawe, Pastoral, and Late Whites. Hunter-gatherer and Late White paintings are often found in the same rock shelters and in some instances, all three types occur at the same site. \n\nNo paintings have been scientifically dated, but some researchers have proposed the earliest dates for the art: Anati (1996) has suggested paintings at Kondoa may be up to 40,000 years old; Leakey (1985) and Coulson and Campbell (2001) up to 10,000 years old. Masao (1979) has estimated the earliest art at perhaps 3000 years old. These are estimates and not based on radiometric dating techniques, and as the paintings have been exposed to considerable weathering these very early dates currently cannot be substantiated.\n\n__Hunter-gatherer__\n\nHunter-gatherer or Sandawe rock art is characterised by fine-line paintings and includes images of animals, human figures, handprints and circular designs. These are the earliest paintings, thought to date to between 3,000-10,000 years ago, and are attributed to the ancestral Sandawe, a hunter-gatherer group indigenous to north-east Tanzania. \n\nThis tradition of rock art occurs in the Kondoa region, with just a few hundred sites in a concentration of less than a 100km in diameter and corresponding closely to the known distribution of the Sandawe people. Animals, such as giraffe, elephant, rhinoceros, antelope, plus a few birds and reptiles, dogs and possibly bees, make up more than half of the images depicted. In addition there are a few animal tracks depicted: cloven hooves, porcupine and aardvark. \n" - sys: id: 5yhqNSTj7USAE6224K28ce created_at: !ruby/object:DateTime 2016-07-27 07:45:11.089000000 Z updated_at: !ruby/object:DateTime 2017-01-24 15:41:54.311000000 Z content_type_id: image revision: 2 image: sys: id: 3fNBqZVcfK8k0Cgo4SsGs6 created_at: !ruby/object:DateTime 2016-07-27 07:46:37.182000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:37.182000000 Z title: TANKON0100004 jpeg description: url: "//images.ctfassets.net/xt8ne4gbbocd/3fNBqZVcfK8k0Cgo4SsGs6/1e5b30977d1a9f021e3eea07fca43f5a/TANKON0100004_jpeg.jpg" caption: Panel of fine-line red figures with rounded heads seated, standing and dancing. <NAME>, Tanzania. 2013,2034.17042 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3710340&partId=1&searchText=2013,2034.17042&page=1 - sys: id: 7w5bbsaHIcGU8U4KyyQ8W6 created_at: !ruby/object:DateTime 2016-07-27 07:45:17.860000000 Z updated_at: !ruby/object:DateTime 2017-01-24 15:45:13.087000000 Z content_type_id: chapter revision: 2 title_internal: Tanzania Chapter 5 body: |2 Typically, human figures are slender and elongated, wearing large elaborate coiffures or headdresses, and sometimes with animal heads. Occasionally they are bent at the waist but they always appear in groups or pairs. A few of the figures are painted with bows and arrows and occur with animals, although whether these represent a hunting scene is uncertain. Women are very scarce. The few handprints present are painted depictions rather than stencils and circular designs are made up of concentric circles sometimes with elaborate rays and occasional rectangles and finger dots. - sys: id: QLuzPXhKqOmMSm0weqOGG created_at: !ruby/object:DateTime 2016-07-27 07:45:10.897000000 Z updated_at: !ruby/object:DateTime 2019-02-12 00:37:50.613000000 Z content_type_id: image revision: 3 image: sys: id: 3zoMrANvf2SgUmuAu2Wa4W created_at: !ruby/object:DateTime 2016-07-27 07:46:38.115000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:38.115000000 Z title: TANKON0370007 jpeg description: url: "//images.ctfassets.net/xt8ne4gbbocd/3zoMrANvf2SgUmuAu2Wa4W/b759c5fe8747a6c19218f19bc693ab2e/TANKON0370007_jpeg.jpg" caption: Panel of Sandawe red, fine-line paintings showing elephants and slender elongated figures. Kondoa, Tanzania. 2013,2034.17702 © TARA/<NAME> col_link: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3712676&partId=1&searchText=2013,2034.17702&page=1 - sys: id: 55d7OVNn5YEii4KSYwE0wE created_at: !ruby/object:DateTime 2016-07-27 07:45:10.859000000 Z updated_at: !ruby/object:DateTime 2017-01-24 15:47:21.921000000 Z content_type_id: image revision: 2 image: sys: id: 4eRcBkspfOS2Ky4GE08qyC created_at: !ruby/object:DateTime 2016-07-27 07:46:38.051000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:38.051000000 Z title: TANKON0300005 jpeg description: url: "//images.ctfassets.net/xt8ne4gbbocd/4eRcBkspfOS2Ky4GE08qyC/5c0b8033c1328f01893ad54418b856ce/TANKON0300005_jpeg.jpg" caption: Seated figure wearing elaborate headdress which is possibly surrounded by bees. Thawi 1, Kondoa, Tanzania. 2013,2034. 17471 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3711764&partId=1&searchText=2013,2034.17471&page=1 - sys: id: 4OiTL2qHFeIEmGUE6OqUcA created_at: !ruby/object:DateTime 2016-07-27 07:45:16.827000000 Z updated_at: !ruby/object:DateTime 2017-01-24 15:45:27.688000000 Z content_type_id: chapter revision: 4 title: '' title_internal: Tanzania Chapter 6 body: | __Pastoral__ About 3,000 years ago, Cushitic herders from Ethiopia moved into the region, and were followed by Nilotic cattle pastoralists, ancestors of today’s Maasai. In comparison to hunter-gatherer rock art, Pastoral rock art yields many fewer paintings and generally depicts cattle in profile, and sometimes sheep and/or goats, a few dogs and figures holding sticks and bows. Predominantly painted in black and sometimes red and white, the colour of many images has now faded to a dull grey colour. - sys: id: 59cgwuXiu4EyiwGuIog0Wi created_at: !ruby/object:DateTime 2016-07-27 07:45:10.760000000 Z updated_at: !ruby/object:DateTime 2017-01-24 15:47:47.628000000 Z content_type_id: image revision: 2 image: sys: id: 1BwSSd5li0MUw4c4QYyAKA created_at: !ruby/object:DateTime 2016-07-27 07:46:38.208000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:38.208000000 Z title: TANLEY0020026 jpeg description: url: "//images.ctfassets.net/xt8ne4gbbocd/1BwSSd5li0MUw4c4QYyAKA/b8a08110079558a56d9ac1d7bfb813a9/TANLEY0020026_jpeg.jpg" caption: 'Top of this boulder: Red cow facing right superimposed on faded white cow facing left and figure facing forwards, Eshaw Hills, Tanzania. 2013,2034.17936 © TARA/<NAME>' col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3713196&partId=1&searchText=2013,2034.17936&page=1 - sys: id: 4zC1ndduCQa8YUSqii26C6 created_at: !ruby/object:DateTime 2016-07-27 07:45:15.874000000 Z updated_at: !ruby/object:DateTime 2017-01-24 15:45:36.649000000 Z content_type_id: chapter revision: 3 title: '' title_internal: Tanzania Chapter 7 body: | __Late White__ Late White paintings are crude, finger painted images and often superimpose older images. These were made by Bantu-speaking, iron-working farmers who moved into the region in the last 300-500 years. The most common type of depiction are designs and motifs that include circles, some of which have rays emanating outwards, concentric circles, patterns of dots and grids with outlines, what look like stick figures with multiple arms, as well as handprints. Animal depictions include giraffe, elephant, antelope, snakes, reptiles, baboons and domestic species. Human figures are less common, but when present are notably men facing forwards with hands on hips, sometimes holding weapons. - sys: id: 4zIzfG4WDKe6SYSimcaEqg created_at: !ruby/object:DateTime 2016-07-27 07:45:10.886000000 Z updated_at: !ruby/object:DateTime 2017-01-24 15:49:16.769000000 Z content_type_id: image revision: 3 image: sys: id: 2iqeQFLDE06A8MW0UcUm2k created_at: !ruby/object:DateTime 2016-07-27 07:46:37.131000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:37.131000000 Z title: TANKON0020039 jpeg description: url: "//images.ctfassets.net/xt8ne4gbbocd/2iqeQFLDE06A8MW0UcUm2k/12b31881421ef6d5f5ccebbc4ec1c009/TANKON0020039_jpeg.jpg" caption: Numerous finger painted geometric designs covering large granite boulder. Pahi, Tanzania. 2013,2034.16793 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3709639&partId=1&searchText=2013,2034.16793&page=1 citations: - sys: id: 5CTLCKcFag2yCMmCgoegE4 created_at: !ruby/object:DateTime 2016-07-27 07:45:15.786000000 Z updated_at: !ruby/object:DateTime 2016-07-27 12:42:00.048000000 Z content_type_id: citation revision: 6 citation_line: "Anati . E. (1996) ‘Cultural Patterns in the Rock Art of Central Tanzania.’ in *The Prehistory of Africa. XIII International Congress of Prehistoric and Protohistoric Sciences Forli-Italia-8/14* September 1996\n\nBwasiri, E.J (2008) 'The Management of Indigenous Heritage: A Case Study of Mongomi wa Kolo Rock Shelter, Central Tanzania'. MA Dissertation, University of the Witwatersrand \n\nBwasiri, E.J. (2011) ‘The implications of the management of indigenous living heritage: the case study of the Mongomi wa Kolo rock paintings World Heritage Site, Central Tanzania’, in *South African Archaeological Bulletin* 69-193:60-66\n\nCoulson, D. and <NAME> (2001) *African Rock Art: Paintings and Engravings on Stone* New York, Harry N. Abrams, Ltd.\n\nKohl-Larsen, L. (1958) *Die Bilderstrasse Ostafricas: Felsbilder in Tanganyika*. Kassel, Erich Roth-Verlag\n\nLeakey, M. (1983) *Africa’s Vanishing Art – The Rock Paintings of Tanzania.* London, Hamish Hamilton Ltd\n\nLewis-Williams, J.D. (1986) ‘Beyond Style and Portrait: A Comparison of Tanzanian and Southern African Rock Art’. *Contemporary Studies on Khoisan 2.* Hamburg, Helmut Buske Verlag\n\nLim, I.L. (1992) ‘A Site-Oriented Approach to Rock Art: a Study from Usandawe, Central Tanzania’. PhD Thesis, University of Michigan\n\nMasao, F.T. (1979)*The Later Stone Age and the Rock Paintings of Central Tanzania*. Wiesbaden, Franz Steiner Verlag\n\nTen Raa, E. (1971) ‘Dead Art and Living Society: A Study of Rock paintings in a Social Context’.*Mankind* 8:42-58\n\nTen Raa, E. (1974) ‘A record of some prehistoric and some recent Sandawe rock paintings’. *Tanzania Notes and Records* 75:9-27\n\n" background_images: - sys: id: 6mw7BovMXeWgMIywAIQgMy created_at: !ruby/object:DateTime 2016-07-27 07:46:31.987000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:31.987000000 Z title: TANKON0060006 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6mw7BovMXeWgMIywAIQgMy/a72b4e36d515fbce84384fbc3afed735/TANKON0060006.jpg" - sys: id: 1qQaW7WyUE22e0MWgsOw4m created_at: !ruby/object:DateTime 2015-12-08 17:14:12.180000000 Z updated_at: !ruby/object:DateTime 2015-12-08 17:14:12.181000000 Z title: TANKON0020020 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1qQaW7WyUE22e0MWgsOw4m/fdf480f97354073c2797254942bee8d6/TANKON0020020.jpg" - sys: id: ghoJUHQwggGi6uuKKggcA created_at: !ruby/object:DateTime 2016-07-27 07:46:33.061000000 Z updated_at: !ruby/object:DateTime 2019-02-12 00:56:49.589000000 Z title: TANLEY0020024 description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3713196&partId=1&searchText=TANLEY0020024&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/ghoJUHQwggGi6uuKKggcA/65471af284c79e1b5548309b005cb2ac/TANLEY0020024.jpg" region: Eastern and central Africa ---<file_sep>/_coll_country_information/uganda-country-introduction.md --- contentful: sys: id: 3DbhHAYYD6icYiuK62SY2w created_at: !ruby/object:DateTime 2015-11-26 18:47:24.211000000 Z updated_at: !ruby/object:DateTime 2015-12-07 13:43:10.697000000 Z content_type_id: country_information revision: 3 title: 'Uganda: country introduction' chapters: - sys: id: 5yJzv38jjG6o0u4Q4ISYeM created_at: !ruby/object:DateTime 2015-11-26 18:35:01.243000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:35:01.243000000 Z content_type_id: chapter revision: 1 title: Introduction title_internal: 'Uganda: country, chapter 1' body: Rock art in Uganda is mostly concentrated in the eastern part of the country, but more broadly sits within a regional belt of geometric rock art spanning East and Central Africa. It is mainly geometric in nature and includes both paintings (red and white being the most common pigment) and engravings; it comprises a basic and recurring repertoire of shapes including circular, rectangular, sausage, dot and lines. Concentric circles with rays emanating from them are a unique feature of Ugandan rock art. - sys: id: 4TrHjE4Umk8eoscoQUaMWC created_at: !ruby/object:DateTime 2015-11-27 14:21:57.842000000 Z updated_at: !ruby/object:DateTime 2017-01-24 15:05:24.474000000 Z content_type_id: image revision: 3 image: sys: id: 40ezg2Ddosc4yYM0Myes8U created_at: !ruby/object:DateTime 2015-12-11 15:53:35.421000000 Z updated_at: !ruby/object:DateTime 2015-12-11 15:53:35.421000000 Z title: UGANGO0020031 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/40ezg2Ddosc4yYM0Myes8U/7d118bce5cf73e7a0fd8b7953a604bcd/UGANGO0020031_1.jpg" caption: Circular motifs.Ngora, Eastern Province, Uganda. 2013,2034.14768 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3691105&partId=1&searchText=2013%2c2034.14768&page=1 - sys: id: 4fHCnfKB5Ymqg4gigEIm0g created_at: !ruby/object:DateTime 2015-11-26 18:35:36.716000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:35:36.716000000 Z content_type_id: chapter revision: 1 title_internal: 'Uganda: country, chapter 2' body: One of the most well-known sites is at Nyero, a large granite outcrop situated between Mbale and Soroti in the east of the country. Nyero consists of a cluster of six sites and is on the Tentative List of UNESCO World Heritage sites&dagger;. All of the paintings found here are geometric in design and have been attributed to the ancestral Batwa, and dated to before 1250 AD. - sys: id: 5BePUMaSPKsSiUweSq2yyG created_at: !ruby/object:DateTime 2015-11-26 18:36:04.177000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:36:04.177000000 Z content_type_id: chapter revision: 1 title: Geography title_internal: 'Uganda: country, chapter 3' body: Uganda is located in East Africa, comprises an area of 236,040 km² and shares borders with Kenya to the east, South Sudan in the north, Democratic Republic of Congo in the west, and Rwanda and Tanzania in the south. It sits in the heart of the Great Lakes region, flanked by Lake Edward, Lake Albert and Lake Victoria, the latter being the second largest inland freshwater lake in the world, containing numerous islands. While much of its border is lakeshore, the country is landlocked. Predominantly plateau, Uganda is cradled by mountains with Margherita peak (5,199m) on Mount Stanley the third highest point in Africa. - sys: id: 3IwOIf4phe6KkoEu24goAw created_at: !ruby/object:DateTime 2015-11-27 14:22:43.586000000 Z updated_at: !ruby/object:DateTime 2017-01-24 15:07:19.503000000 Z content_type_id: image revision: 3 image: sys: id: 6LAhyXtnagaeiiYcyqAUS8 created_at: !ruby/object:DateTime 2015-12-11 15:54:00.944000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:47:44.145000000 Z title: '2013,2034.15198' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3690931&partId=1&searchText=UGAVIC0010001&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/6LAhyXtnagaeiiYcyqAUS8/06fee85996cb2e9625cbfd6b7a6a07dc/UGAVIC0010001_1.jpg" caption: Large boulder containing painted rock art overlooking Lake Victoria. 2013,2034.15198 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3690931&partId=1&searchText=2013%2c2034.15198&page=1 - sys: id: xTETlLO8WkqiiuYO0cgym created_at: !ruby/object:DateTime 2015-11-26 18:36:58.092000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:36:58.092000000 Z content_type_id: chapter revision: 1 title: Research History title_internal: 'Uganda: country, chapter 4' body: |- The first documentation of rock art in Uganda occurred in 1913 (Teso Report) at Nyero, a painted rock shelter of the Later Iron Age period. After its initial recording the site was subsequently cited in a 1945 excavation report (Harwich, 1961) and meticulously noted by J.C.D Lawrance during the 1950s. Only a small number of studies of Ugandan rock art rock art have been published (Wayland 1938; Lawrance 1953; Posnansky 1961; Morton 1967; Chaplin 1974), with early analyses being predominantly descriptive and highly speculative. The first major publications on Ugandan rock art emerged in the 1960s (Posnansky 1961; Morton 1967; Chaplin 1974) with rock art researchers proposing that the geometric and non-representational depictions served a documentary purpose of identifying cultural groups such as hunter-gatherers, cultivators or pastoralists. During this decade researchers attempted to place the rock art in a chronological framework, tying it to broader archaeological sequences. Political instability greatly impeded research during the 1970s and 1980s, although Chaplin’s thesis and in-depth survey on prehistoric rock art of Lake Victoria was published posthumously in 1974. - sys: id: 3z8AAdZC2sEWOOqc4kcESq created_at: !ruby/object:DateTime 2015-11-27 14:24:00.757000000 Z updated_at: !ruby/object:DateTime 2017-01-24 15:09:06.452000000 Z content_type_id: image revision: 3 image: sys: id: 2FHA4qasM0YkYeY20OK20e created_at: !ruby/object:DateTime 2015-12-11 15:54:11.681000000 Z updated_at: !ruby/object:DateTime 2015-12-11 15:54:11.681000000 Z title: UGAVIC0060056 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/2FHA4qasM0YkYeY20OK20e/8dc76eadeb33620beaeedbba6b04399b/UGAVIC0060056_1.jpg" caption: Painted ceiling of a rock shelter attributed to the BaTwa. Lolui Island, Eastern Province, Uganda. 2013,2034.15306 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3691242&partId=1&searchText=2013%2c2034.15306&page=1 - sys: id: 17HHIh3cvwkm8eMqIaYi4e created_at: !ruby/object:DateTime 2015-11-26 18:37:14.262000000 Z updated_at: !ruby/object:DateTime 2015-12-11 12:43:31.000000000 Z content_type_id: chapter revision: 2 title_internal: 'Uganda: country, chapter 5' body: Much of the interpretation of the rock art in the region was based on the assumption that the art was attributable to the so-called “Bushmen” of southern Africa, using these explanations to understand the rock art of Uganda. Catherine Namono’s (2010) recent doctoral thesis on rock art in Uganda has opened up these debates, “tackling the more slippery issues of attribution, interpretation and understanding of rock art” (Namono, 2010:40). - sys: id: 49Hty9jIlWSeoOi2uckwwg created_at: !ruby/object:DateTime 2015-11-26 18:37:41.691000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:37:41.691000000 Z content_type_id: chapter revision: 1 title: Chronologies/Styles title_internal: 'Uganda: country, chapter 6' body: "__Paintings__\n\nThe geometric rock art that predominates in Uganda is attributed to the Batwa cultural group. Modern Batwa are descendants of ancient aboriginal forest-dwelling hunter-gatherer groups based in the Great Lakes region of central Africa. Their rock art has been divided into two traditions: firstly, the red animal tradition that comprises finely painted representations of animals in red pigment painted in a figurative style. These are all in the far north-eastern corner of Uganda. Antelope are the most common animals depicted, but this imagery also includes elephant, rhino, lion, leopard, giraffe, hyena, warthog, wild pig, ostrich and buffalo. \n" - sys: id: rehKUDcDviQGqmiwAikco created_at: !ruby/object:DateTime 2015-11-27 14:24:31.625000000 Z updated_at: !ruby/object:DateTime 2017-01-24 15:09:53.569000000 Z content_type_id: image revision: 3 image: sys: id: 6Rp8Jyx6Tu8CagewSGkKaG created_at: !ruby/object:DateTime 2015-12-11 15:53:35.413000000 Z updated_at: !ruby/object:DateTime 2015-12-11 15:53:35.413000000 Z title: UGAMOR0010021 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6Rp8Jyx6Tu8CagewSGkKaG/8425bc465938ddae5cfed284f96a6e6f/UGAMOR0010021_1.jpg" caption: Painted red cattle and figures holding bows. Kanamugeot, Northern Province, Uganda, 2013,2034.14633 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3690004&partId=1&searchText=2013%2c2034.14633&page=1 - sys: id: 2KG09KRWisSWmogUWA4sGQ created_at: !ruby/object:DateTime 2015-11-26 18:38:08.326000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:38:08.326000000 Z content_type_id: chapter revision: 1 title_internal: 'Uganda: country, chapter 7' body: "While some of the animals are remarkably naturalistic in their portrayal, the majority are highly distorted and difficult to identify to species level, and are associated with rows of dots superimposing the animal forms. The second tradition, the red geometrics include images painted in red and applied with the fingertip; the most common motifs comprise concentric circles, concentric circles with radiating lines, dots, U-shapes, dotted, straight, horizontal and vertical lines and interlinked lines. Other motifs and shapes are described as ‘acacia pod’, ‘canoes’, and ‘dumbbell’; a testament to the problems researchers face when attempting to use descriptive terms in identifying complex designs. \n\n__Engravings__\n\nGeometric engravings occur in and around Lake Victoria and also in north-eastern Uganda. Motifs comprise concentric circles, grids, concentric circles with internal radiating spokes, lines and dots. Proportionally, there are fewer engravings than paintings but as Namono (2010) has observed this may reflect a research bias rather than an actual disparity.\n" - sys: id: 6re1Gh7nxe4YK4MmumWu4m created_at: !ruby/object:DateTime 2015-11-27 14:25:05.494000000 Z updated_at: !ruby/object:DateTime 2017-01-24 15:10:31.191000000 Z content_type_id: image revision: 3 image: sys: id: 4TE2BAQkM8S0640ECkYayA created_at: !ruby/object:DateTime 2015-12-11 15:53:43.648000000 Z updated_at: !ruby/object:DateTime 2015-12-11 15:53:43.648000000 Z title: UGANAS0002 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/4TE2BAQkM8S0640ECkYayA/3a5a54bd23c2ecaa637d19e132e40263/UGANAS0002_1.jpg" caption: Engraved rock with concentric circle motif. Kampala, Uganda. 2013,2034.14710 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3690111&partId=1&searchText=2013%2c2034.14710&page=1 - sys: id: 6qgdyPfErKwIISIUuWEsMU created_at: !ruby/object:DateTime 2015-11-26 18:38:44.670000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:38:44.670000000 Z content_type_id: chapter revision: 1 title_internal: 'Uganda: country, chapter 8' body: Another common type of engraving is small cupules aligned in rows, found predominantly on hilltops or large rock slabs near water sources. None have been found on vertical rock faces or in rock shelters. They are known locally as *omweso* (a traditional board game of Uganda) as there are similarities between these and the traditional *mancala* game, originally introduced to Africa with the Indian Ocean trade. - sys: id: 2fzT5T0btesSgMyuyUqAu0 created_at: !ruby/object:DateTime 2015-11-27 14:25:46.047000000 Z updated_at: !ruby/object:DateTime 2017-01-24 15:11:49.658000000 Z content_type_id: image revision: 3 image: sys: id: 2kLCq0ponGEOemeycuauI2 created_at: !ruby/object:DateTime 2015-12-11 15:53:48.341000000 Z updated_at: !ruby/object:DateTime 2015-12-11 15:53:48.341000000 Z title: UGAMUK0050001 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/2kLCq0ponGEOemeycuauI2/55631bb48e53718bd799a7e8799f7439/UGAMUK0050001_1.jpg" caption: Large rock with grid of small carved cupules. Kimera, Central Province, Uganda. 2013,2034.14676 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3690085&partId=1&searchText=2013%2c2034.14676&page=1 - sys: id: 6waesLr6j6I24eySaQO2Q6 created_at: !ruby/object:DateTime 2015-11-26 18:39:35.319000000 Z updated_at: !ruby/object:DateTime 2015-12-11 12:44:11.747000000 Z content_type_id: chapter revision: 2 title: Dating title_internal: 'Uganda: country, chapter 9' body: |- Attempts to understand the chronology of Ugandan rock in the 1960s were based on sequences focusing on pigments used in paintings. Lawrance proposed that yellow paintings were the oldest; followed by orange, red, purple, red and white; white and dirty white were the latest in the sequence. It is highly problematic developing sequences based on pigments because of the ways in which they chemically react with particular surfaces, other pigments and the natural elements, which can compromise the integrity of the pigment. However, there appears to be a consistency (across East and Central Africa) that suggests red and white geometric paintings are the oldest and have been in existence for millennia. Initially thought to be the work of San Bushmen of southern Africa, archaeological, genetic and ethnographic evidence has subsequently attributed the paintings to the Batwa people, a cultural group who are today found in small groups near the Rwanda/Uganda border. If it is accepted that the geometric imagery was made by these hunter-gatherers then the rock art of Uganda probably dates from between 12,000 to 1,000 years ago. - sys: id: 5eNs55lpIWoiCM2W6iwGkM created_at: !ruby/object:DateTime 2015-11-27 14:26:33.741000000 Z updated_at: !ruby/object:DateTime 2017-01-24 15:12:35.188000000 Z content_type_id: image revision: 3 image: sys: id: 7awPQKadFK2k6mMegimuIE created_at: !ruby/object:DateTime 2015-12-11 15:53:43.661000000 Z updated_at: !ruby/object:DateTime 2015-12-11 15:53:43.661000000 Z title: UGATES0030003 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/7awPQKadFK2k6mMegimuIE/0b3a8c2a03bcc34f8821f30bf0cf1367/UGATES0030003_1.jpg" caption: Complex white motif comprising six concentric circles surrounded by curvilinear tentacles. Nyero, Eastern Province, Uganda. 2013,2034.14892 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3673779&partId=1&searchText=2013%2c2034.14892&page=1 - sys: id: UOkpq4WM6qoYMUky2Ws4e created_at: !ruby/object:DateTime 2015-11-26 18:39:56.176000000 Z updated_at: !ruby/object:DateTime 2015-12-11 12:44:55.317000000 Z content_type_id: chapter revision: 3 title_internal: 'Uganda: country, chapter 10' body: However, more recent studies have proposed that these were the work of settled human groups and not early hunter-gatherers. Radiocarbon dating at Nyero (and another site at Kakoro) has dated the paintings to between 5,000 and 1,600 years ago. It has been proposed that rock shelters were used by semi-nomadic peoples engaged in animal herding, which they used as reference points in the landscape. Generally positioned away from flat land, they may have served to direct herders of cattle and/or goats towards paths and water. - sys: id: 3HOpYjRGGciiYMS24EcSqO created_at: !ruby/object:DateTime 2015-11-26 18:40:20.558000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:40:20.558000000 Z content_type_id: chapter revision: 1 title: Interpretation title_internal: 'Uganda: country, chapter 11' body: A recent comprehensive study (Namono, 2010) of the potential meaning of geometric art in Uganda looked at the ways in which the geometric shapes in the rock art can be associated with the ethnographies of hunter-gatherers of the region. The approach proposed that the symbolism of geometric rock art derives from a gendered forest worldview. The forest is pivotal to hunter/gatherer cosmology in this region, whereby it plays a central role in cultural production and reproduction over time and is regarded as both male and female. The forest is not only a source of subsistence and well-being but informs their identity and the rock art reflects these complex concepts. - sys: id: 3qOC0kMyiQQOKgc2k2aICQ created_at: !ruby/object:DateTime 2015-11-27 14:27:14.840000000 Z updated_at: !ruby/object:DateTime 2017-01-24 15:13:32.803000000 Z content_type_id: image revision: 3 image: sys: id: 5gAcaHufAso60GKYiKsei2 created_at: !ruby/object:DateTime 2015-12-11 15:53:48.306000000 Z updated_at: !ruby/object:DateTime 2015-12-11 15:53:48.306000000 Z title: UGANGO0010001 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/5gAcaHufAso60GKYiKsei2/b93cc028065d4f5c5dbe953558d1a4bb/UGANGO0010001_1.jpg" caption: View looking towards the forested location of a painted rock art site. Ngora, Eastern Province, Uganda. 2013,2034.14711 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3690354&partId=1&searchText=2013,2034.14711&page=1 - sys: id: 4r8ruNjScUCigsS6kWe6Yg created_at: !ruby/object:DateTime 2015-11-26 18:40:41.970000000 Z updated_at: !ruby/object:DateTime 2015-12-11 12:45:09.119000000 Z content_type_id: chapter revision: 2 title_internal: 'Uganda: country, chapter 12' body: It is difficult to determine when rock art sites were last used, and in some cases, such as at Nyero, sites are still in use by local peoples with offerings being made and sites associated with rain-making rituals. However, the advent of colonialism influenced such traditions bringing a change in the way the forest was venerated, used and conceptualised. citations: - sys: id: R9NAlFnoYuGyywYgIccK created_at: !ruby/object:DateTime 2015-11-26 18:42:30.538000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:42:30.538000000 Z content_type_id: citation revision: 1 citation_line: | &dagger; A Tentative List is an inventory of those properties considered to be of cultural and/or natural heritage of outstanding universal value and therefore suitable for inscription on the World Heritage List. <NAME>. 1974. ‘The Prehistoric Art of the Lake Victoria Region’, in *Azania* 9, pp: 1-50. <NAME>. 1961. *Red Dust: Memories of the Uganda Police* 1935-1955. London: Vincent Stuart Ltd. <NAME>. 1953. ‘Rock Paintings in Teso’, in *Uganda Journal* 17, pp: 8-13. <NAME>. 1967. ‘Rock Engravings from Loteteleit, Karamoja’, in *Uganda Journal* 19, p:90. <NAME>. 2010. Surrogate Surfaces: *A contextual interpretive approach to the rock art of Uganda*. Unpublished PhD Thesis. Johannesburg: University of Witwatersrand <NAME>. 1961. ‘Rock Paintings on Lolui Island, Lake Victoria’ in *Uganda Journal*, 25, pp: 105-11. <NAME>. 1938. ‘Note on Prehistoric Inscription in Ankole Uganda’, in *Uganda Journal* 5, pp: 252 – 53. ---<file_sep>/_coll_country/uganda/nyero.md --- breadcrumbs: - label: Countries url: "../../" - label: Uganda url: "../" layout: featured_site contentful: sys: id: 3crZmFK8Vyy0MGMoEwEaMS created_at: !ruby/object:DateTime 2015-11-25 14:47:12.403000000 Z updated_at: !ruby/object:DateTime 2015-12-07 20:52:00.749000000 Z content_type_id: featured_site revision: 3 title: Nyero, Uganda slug: nyero chapters: - sys: id: 2qMVT4qlruk8WAAWEwaC6u created_at: !ruby/object:DateTime 2015-11-25 14:38:38.847000000 Z updated_at: !ruby/object:DateTime 2017-01-24 15:16:47.887000000 Z content_type_id: chapter revision: 3 title_internal: 'Uganda: featured site, chapter 1' body: |- First documented in 1913 (in the Teso Report&dagger;), the geometric paintings at Nyero are among the most important and well documented rock art sites in Uganda, and are on the Tentative list of UNESCO World Heritage sites&Dagger;. Nyero is located in eastern Uganda in the Kumi District, about 200 km from the capital city Kampala. It comprises six rock shelters in total, but initially only three were recorded and referred to as shrines by local communities, who had no knowledge of the origins of the paintings. The authorship of the paintings remains in some debate. Initially, the rock art was thought to be the work of San&#124;Bushmen of southern Africa. However, archaeological, genetic and ethnographic evidence has subsequently attributed the paintings to the ancestors of Batwa people, hunter-gatherers who are descendants of ancient aboriginal groups once spread across East and Central Africa and most probably the original inhabitants of this landscape. Today they live in small groups near the Rwanda/Uganda border. - sys: id: 37xiS8FWYwgqYYscQg24OW created_at: !ruby/object:DateTime 2015-11-25 14:28:33.065000000 Z updated_at: !ruby/object:DateTime 2017-01-24 15:18:23.508000000 Z content_type_id: image revision: 3 image: sys: id: 1UsysL5u3ioSim8YKyQ4mS created_at: !ruby/object:DateTime 2015-12-11 16:05:57.381000000 Z updated_at: !ruby/object:DateTime 2015-12-11 16:05:57.381000000 Z title: UGATES0010002 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1UsysL5u3ioSim8YKyQ4mS/56c1505f1a1d24e85ba055421b1c0383/UGATES0010002_1.jpg" caption: Site of Nyero 1. 2013,2034.14796 © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3671587&partId=1&searchText=2013,2034.14796&page=1 - sys: id: 2At2H2doaAceQKO2gi0WyO created_at: !ruby/object:DateTime 2015-11-25 14:39:27.080000000 Z updated_at: !ruby/object:DateTime 2015-11-25 14:39:27.080000000 Z content_type_id: chapter revision: 1 title_internal: 'Uganda: featured site, chapter 2' body: |- More recent studies have proposed that the rock art was the work of settled human groups and not early hunter-gatherers. It has been proposed that rock shelters were used by semi-nomadic peoples devoted to animal herding, and used as reference points in the landscape. Generally positioned away from flat land, they may have served to direct herders of cattle and/or goats towards paths and water. The unknown identity of the rock artists makes dating problematic, but some of the paintings may be up to 12,000 years old. Notwithstanding the problems associated with attribution and chronology, many of the rock paintings in Uganda show serious damage due to long exposure to the elements. At Nyero 2, the paintings are partially covered with mineral salts, while at Nyero 5 the paintings have been destroyed or are obscured by rain wash-off. The physical condition of the paintings is testament to their antiquity. - sys: id: 1DnRQQLvIgWcYyWOeweAoC created_at: !ruby/object:DateTime 2015-11-25 14:29:09.297000000 Z updated_at: !ruby/object:DateTime 2017-01-24 15:19:01.643000000 Z content_type_id: image revision: 4 image: sys: id: 4TmZuqmyM8UukoEmU6kUcY created_at: !ruby/object:DateTime 2015-12-11 16:05:57.367000000 Z updated_at: !ruby/object:DateTime 2015-12-11 16:05:57.367000000 Z title: UGATES0020007 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/4TmZuqmyM8UukoEmU6kUcY/1fb5255968afbd1a3f022f8e8142a5ff/UGATES0020007_1.jpg" caption: Nyero 2 showing rock art obscured by mineral salts leaching out from the rock face. 2013,2034.14828 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3671630&partId=1&searchText=2013,2034.14828&page=1 - sys: id: 2QBfTBIQlG6muuGs2CyQMe created_at: !ruby/object:DateTime 2015-11-25 14:39:54.020000000 Z updated_at: !ruby/object:DateTime 2017-01-24 15:20:18.146000000 Z content_type_id: chapter revision: 3 title_internal: 'Uganda: featured site, chapter 3' body: | __Nyero Rock Art sites:__ __Nyero 1__ This is a small rock shelter on the outer edge of the outcrop and comprises six sets of concentric circles with a central image of a ‘floral motif’ and a so-called ‘acacia pod’ shape. The geometrics in this shelter are all painted in white. __Nyero 2__ This is the main shelter, the overhang of which is formed by an enormous boulder (estimated to weigh at least 20,000 tons) which has broken away; a vertical rock against the back wall measures 10m in height. The panel at Nyero 2 consists of more than forty images such as vertical divided sausage shapes, so-called ‘canoes‘, unidentified faint markings, ‘U’ shapes, lines and dots, with evidence of superimposition; but is dominated by concentric circles. A unique feature of the paintings are the so-called ‘canoes’ or parts of ‘canoes’, so-called because of their resemblance in form. The depictions are all painted in shades of red. - sys: id: i4OzTdyoO4MaaSWYEw44a created_at: !ruby/object:DateTime 2015-11-25 14:30:29.951000000 Z updated_at: !ruby/object:DateTime 2017-01-24 15:20:45.228000000 Z content_type_id: image revision: 3 image: sys: id: 55q7QQMYVacGSCOEqOMq2q created_at: !ruby/object:DateTime 2015-12-11 16:05:57.370000000 Z updated_at: !ruby/object:DateTime 2015-12-11 16:05:57.370000000 Z title: UGATES0020019 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/55q7QQMYVacGSCOEqOMq2q/cbe87e9b47e1b735a6ea4ed5709af86a/UGATES0020019_1.jpg" caption: Paintings at Nyero 2. 2013,2034.14840 © TARA/<NAME>oulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3671647&partId=1&searchText=2013,2034.14840&page=1 - sys: id: 2coobYQw4gccSA44SGY2og created_at: !ruby/object:DateTime 2015-11-25 14:31:19.584000000 Z updated_at: !ruby/object:DateTime 2017-01-24 15:21:14.609000000 Z content_type_id: image revision: 3 image: sys: id: 7yIW3zRgn6SEKuyWSW4ao0 created_at: !ruby/object:DateTime 2015-12-11 16:05:57.385000000 Z updated_at: !ruby/object:DateTime 2015-12-11 16:05:57.385000000 Z title: UGATES0020030 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/7yIW3zRgn6SEKuyWSW4ao0/abca8da930f88993859b431aa0487356/UGATES0020030_1.jpg" caption: Close up of concentric circles and large canoe shaped object design. 2013,2034.14851 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3671768&partId=1&searchText=2013,2034.14851&page=1 - sys: id: 3NJ4Oz0UY8Yiao0WKKYsKk created_at: !ruby/object:DateTime 2015-11-25 14:40:37.018000000 Z updated_at: !ruby/object:DateTime 2015-11-25 14:40:37.018000000 Z content_type_id: chapter revision: 1 title_internal: 'Uganda: featured site, chapter 4' body: | The paintings are protected from direct rain by the overhang and rocks to the front and sides protect the paintings from the sun, which is likely to have contributed to their preservation. Early users of the shelter placed ritual gifts on its south-eastern side; the tradition of using this space to place money either before or after receiving help from ancestral spirits is continued by the local community. As well as the rock art, a bone incised with three concentric circles and four parallel lines, and pieces of prepared ochre were excavated from this site in 1945. These are the only evidence of prehistoric portable art so far found in Uganda. __Nyero 3__ Located about eight minutes’ walk from Nyero 2, this shelter is formed by a large boulder perched on supporting rocks. Paintings consist of white concentric circles; the outer circles surrounded by double curved designs, between which are double lines divided into small compartments. - sys: id: 1TFcUtPntaamu6iAGw0Yu6 created_at: !ruby/object:DateTime 2015-11-25 14:36:03.085000000 Z updated_at: !ruby/object:DateTime 2017-01-24 15:21:39.949000000 Z content_type_id: image revision: 3 image: sys: id: qpeXjLAjUOK6GGOeE8iQK created_at: !ruby/object:DateTime 2015-12-11 16:05:57.362000000 Z updated_at: !ruby/object:DateTime 2015-12-11 16:05:57.362000000 Z title: UGATES0030001 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/qpeXjLAjUOK6GGOeE8iQK/d8caeb2c1a67f044f488183b926536e7/UGATES0030001_1.jpg" caption: White concentric circle at Nyero 3. 2013,2034.14888 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3673770&partId=1&searchText=2013,2034.14889&page=1 - sys: id: 4uHJ60KmQ88eK0eGI2eqqi created_at: !ruby/object:DateTime 2015-11-25 14:41:05.035000000 Z updated_at: !ruby/object:DateTime 2015-11-25 14:41:05.035000000 Z content_type_id: chapter revision: 1 title_internal: 'Uganda: featured site, chapter 5' body: | __Nyero 4__ This is a small shelter on the south-western side of the hill where there are a few traces of red finger-painted concentric circles, two conical shapes and lines. __Nyero 5__ Situated on the western side of the hill, this shelter has a red geometric motif composed of a combination of circular and linear shapes made with both a brush and a finger. However, the images are quite difficult to distinguish as they are damaged by natural water erosion. - sys: id: 1i0uRJ0CsIS6skI4CSeICy created_at: !ruby/object:DateTime 2015-11-25 14:36:38.229000000 Z updated_at: !ruby/object:DateTime 2017-01-24 15:22:17.715000000 Z content_type_id: image revision: 3 image: sys: id: 66GiQKzNokmUKWM6IKSOeC created_at: !ruby/object:DateTime 2015-12-11 16:05:57.384000000 Z updated_at: !ruby/object:DateTime 2015-12-11 16:05:57.384000000 Z title: UGATES0050011 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/66GiQKzNokmUKWM6IKSOeC/5a861c2c47d32c7a5a2271c4f824e0c0/UGATES0050011_1.jpg" caption: Nyero 5 showing paintings damaged by water erosion. 2013,2034.14954 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3673887&partId=1&searchText=2013,2034.14954&page=1 - sys: id: 6kXL90PRsciwo4kcwm4qs4 created_at: !ruby/object:DateTime 2015-11-25 14:41:27.841000000 Z updated_at: !ruby/object:DateTime 2015-11-25 14:41:27.841000000 Z content_type_id: chapter revision: 1 title_internal: 'Uganda: featured site, chapter 6' body: | __Nyero 6__ Situated on the top of the hill, this shelter has a good view of the landscape. This site features two red finger-painted outlines of small oval shapes and a slanting L-shape as well as an outlined cross with a small circle below. The painted surface is now subject to severe exfoliation as it is open to the rain and morning sun. The sites at Nyero are believed locally to have been sacred ancestral places where, in the past, people would have travelled long distances to make offerings of food, beer and money in times of drought, misfortune and for child birth. Nyero was also regarded as a magical place where rain ceremonies were held. Oral histories have recorded strong attachments to the site and individual and community prayers were held seasonally. The antiquity of the images and their association with long-forgotten peoples may serve to enhance Nyero as a special and sacred place for local communities. citations: - sys: id: 1JbeHTVApauCyUYOGKCa0W created_at: !ruby/object:DateTime 2015-11-25 14:37:22.101000000 Z updated_at: !ruby/object:DateTime 2015-11-25 14:44:11.347000000 Z content_type_id: citation revision: 4 citation_line: |+ <NAME>. 2010. *Surrogate Surfaces: A contextual interpretive approach to the rock art of Uganda*. Unpublished PhD Thesis. Johannesburg: University of Witwatersrand Turchetta, Barbara and <NAME> (eds). 2014. *Uganda Rock Art Sites: A Vanishing Heritage of Lake Victoria Region*. Kampala: National Museum of Uganda &dagger; An annual report submitted by each region to the Governor of Uganda during British colonial rule. &Dagger; A Tentative List is an inventory of those properties considered to be of cultural and/or natural heritage of outstanding universal value and therefore suitable for inscription on the World Heritage List. background_images: - sys: id: 51UNpKVSAEu6kkScs6uoOS created_at: !ruby/object:DateTime 2015-11-25 14:26:21.477000000 Z updated_at: !ruby/object:DateTime 2015-11-25 14:26:21.477000000 Z title: '2013,2034.14840' description: url: "//images.ctfassets.net/xt8ne4gbbocd/51UNpKVSAEu6kkScs6uoOS/21f12a22f47abbc0a67a1552a0fcf045/UGATES0020019.jpg" - sys: id: gVjIO1sqY06wAO8oIewkM created_at: !ruby/object:DateTime 2015-11-25 14:27:30.672000000 Z updated_at: !ruby/object:DateTime 2015-11-25 14:27:30.672000000 Z title: '2013,2034.14954' description: url: "//images.ctfassets.net/xt8ne4gbbocd/gVjIO1sqY06wAO8oIewkM/304d628709a396506a486f96c78f6fa0/UGATES0050011.jpg" ---<file_sep>/_coll_country/egypt.md --- contentful: sys: id: 4bGUyz1ry0oCGaqWIUegck created_at: !ruby/object:DateTime 2015-11-26 18:50:22.357000000 Z updated_at: !ruby/object:DateTime 2018-05-17 16:59:45.779000000 Z content_type_id: country revision: 9 name: Egypt slug: egypt col_url: http://www.britishmuseum.org/research/collection_online/search.aspx?people=197356&place=42209 map_progress: true intro_progress: true image_carousel: - sys: id: 4lKghiDq6Isw4ACWYGqcys created_at: !ruby/object:DateTime 2015-11-30 13:34:19.580000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:23:45.457000000 Z title: '2013,2034.108' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3577697&partId=1&searchText=2013,2034.108&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/4lKghiDq6Isw4ACWYGqcys/0b4c8365bd01954ad4d56d5bcba668b6/2013_2034.108_1.jpg" - sys: id: 2JRA7ZTPiEgskw2w6CAwki created_at: !ruby/object:DateTime 2015-11-30 13:34:19.593000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:25:26.330000000 Z title: '2013,2034.126' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3577677&partId=1&searchText=2013,2034.126&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/2JRA7ZTPiEgskw2w6CAwki/bc51e1221f4302c2432de16ca960fbf2/2013_2034.126_1.jpg" - sys: id: 6pW55O6bPUgA868iaymU0S created_at: !ruby/object:DateTime 2015-11-30 13:34:19.613000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:26:45.965000000 Z title: '2013,2034.212' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3577589&partId=1&searchText=2013,2034.212&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/6pW55O6bPUgA868iaymU0S/d444187808f12cb5ba8fdf0223aca94c/2013_2034.212_1.jpg" - sys: id: 1DmPc4SXTi2qQiYW6mKK62 created_at: !ruby/object:DateTime 2015-11-30 13:34:19.597000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:31:31.555000000 Z title: '2013,2034.25' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3577780&partId=1&images=true&people=197356&place=42209&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/1DmPc4SXTi2qQiYW6mKK62/412e8b744a4af417ad873768aad220f6/2013_2034.5277_1.jpg" - sys: id: 3R3Ri8y5pe2I4AM8iauayW created_at: !ruby/object:DateTime 2015-11-25 15:00:35.477000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:28:16.164000000 Z title: '2013,2034.190' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3577611&partId=1&searchText=2013,2034.190&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/3R3Ri8y5pe2I4AM8iauayW/5e53609e755eba8130847a5017e32268/2013_2034.190.jpg" featured_site: sys: id: 4af0chnVYAe0e4mqoQwaoy created_at: !ruby/object:DateTime 2015-11-25 15:07:32.113000000 Z updated_at: !ruby/object:DateTime 2015-12-07 20:53:48.674000000 Z content_type_id: featured_site revision: 3 title: Cave of Swimmers, Egypt slug: cave-of-swimmers chapters: - sys: id: 4pHoZkgWDegMQsumuSUekM created_at: !ruby/object:DateTime 2015-11-25 15:04:41.300000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:04:41.300000000 Z content_type_id: chapter revision: 1 title_internal: 'Egypt: featured site, chapter 1' body: The ‘Cave of Swimmers’ is one of the most famous rock art sites of the Sahara. It sits in Wadi Sura, loosely translated as the ‘Valley of Pictures’ due to the prevalence of rock art in the region. - sys: id: 1cUANarsnIIyGQ8MUGaKMM created_at: !ruby/object:DateTime 2015-11-25 15:01:11.701000000 Z updated_at: !ruby/object:DateTime 2017-01-09 15:35:42.682000000 Z content_type_id: image revision: 2 image: sys: id: 5LebP1Vcqs4A4US00uI0Q4 created_at: !ruby/object:DateTime 2015-11-25 15:00:35.480000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:00:35.480000000 Z title: '2013,2034.186' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5LebP1Vcqs4A4US00uI0Q4/56ba762bb737baf4545dc62a6a745bb3/2013_2034.186.jpg" caption: A view of the entrance to the ‘Cave of Swimmers’. On a promontory at the entrance to an inlet in Wadi Sura, Gilf Kebir, Egypt. 2013,2034.186 © <NAME> / TARA col_link: http://bit.ly/2iV11IU - sys: id: 5AJki82zIcK2AEyigEiu2g created_at: !ruby/object:DateTime 2015-11-25 15:05:05.937000000 Z updated_at: !ruby/object:DateTime 2017-01-09 15:44:27.933000000 Z content_type_id: chapter revision: 2 title_internal: 'Egypt: featured site, chapter 2' body: The ‘Cave of Swimmers’ is the larger of two shallow caves situated side by side in the southern part of the Gilf Kebir plateau in Egypt’s Western Desert, an area so remote and inaccessible that its existence only became known to European cartographers in 1926. It is so named due to the human figures painted on its walls with their limbs contorted as if swimming. It has since become world-renowned, particularly as a key location in the feature film *The English Patient* (1996), based on <NAME>’s novel of the same name. - sys: id: 1imxvhdhHEYsyKueK6coS created_at: !ruby/object:DateTime 2015-11-25 15:01:51.007000000 Z updated_at: !ruby/object:DateTime 2017-01-09 16:35:41.280000000 Z content_type_id: image revision: 2 image: sys: id: 2halaUUgAMe6ES0uycIIIG created_at: !ruby/object:DateTime 2015-11-25 15:00:35.469000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:00:35.469000000 Z title: '2013,2034.188' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2halaUUgAMe6ES0uycIIIG/ec1812c9c376a941c691641c471b7105/2013_2034.188.jpg" caption: View out of the cave mouth. 2013,2034.188 © <NAME> / TARA col_link: http://bit.ly/2iVbiVc - sys: id: 2iFZCE50AsqKM4C8ma0IO8 created_at: !ruby/object:DateTime 2015-11-25 15:05:27.680000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:05:27.680000000 Z content_type_id: chapter revision: 1 title_internal: 'Egypt: featured site, chapter 3' body: The book and film feature fictionalised versions of the cave and its real-life discoverer, <NAME>, as the title character. In reality, Almásy was a charismatic figure in pre-war Saharan exploration. He argued that the ‘swimming’ figures suggested the prior existence of abundant water in the area and was therefore evidence that it had not always been arid desert, a radical new theory at the time that has since been confirmed, although not on the basis of these paintings as evidence. Rock art is notoriously difficult to date as it was a tradition practiced for thousands of years. These paintings have been dated at between 9,000 and 6,000 years ago, although some researchers have suggested both earlier and later dates. - sys: id: 6tD8WMYexGWoiEYeEKAaIw created_at: !ruby/object:DateTime 2015-11-25 15:02:56.246000000 Z updated_at: !ruby/object:DateTime 2017-01-09 16:36:48.650000000 Z content_type_id: image revision: 2 image: sys: id: 3R3Ri8y5pe2I4AM8iauayW created_at: !ruby/object:DateTime 2015-11-25 15:00:35.477000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:28:16.164000000 Z title: '2013,2034.190' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3577611&partId=1&searchText=2013,2034.190&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/3R3Ri8y5pe2I4AM8iauayW/5e53609e755eba8130847a5017e32268/2013_2034.190.jpg" caption: The main painted panel on the cave wall, showing the famous ‘swimming’ figures (bottom centre and top right). 2013,2034.190 © <NAME> / TARA col_link: http://bit.ly/2j0fxBy - sys: id: 5VeXJi6wN2Cq00COCo08Sk created_at: !ruby/object:DateTime 2015-11-25 15:05:49.205000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:05:49.205000000 Z content_type_id: chapter revision: 1 title_internal: 'Egypt: featured site, chapter 4' body: 'New rock art discoveries in this area have been made in recent years and add to the debate, which has continued, as have expeditions by academics, tourists and others. These visitors have sometimes left their own marks on the rock faces in the form of graffiti, and in the surrounding sand, where the tracks from previous parties (including Almásy’s) lie undisturbed, adding to the sense of history: not only of those who produced the paintings, but also of the site itself. Meanwhile the condition of the paintings, prone to flaking, continues to deteriorate, further obscuring this tantalising glimpse into the past.' - sys: id: QzRyY82AYSMgMGCUcws2m created_at: !ruby/object:DateTime 2015-11-25 15:03:54.190000000 Z updated_at: !ruby/object:DateTime 2017-01-09 16:37:39.120000000 Z content_type_id: image revision: 2 image: sys: id: 6Fqf4hcw1OeG2IIO442ckW created_at: !ruby/object:DateTime 2015-11-25 15:00:35.492000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:00:35.492000000 Z title: '2013,2034.192' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6Fqf4hcw1OeG2IIO442ckW/6d975af11e82e634f913ca9aed815e44/2013_2034.192.jpg" caption: Two ‘negative’ hand prints from the left side of the main panel, blown in different pigments. Three crouched figures are painted across the lower handprint. 2013,2034.192 © <NAME> / TARA col_link: http://bit.ly/2iaUQ4J - sys: id: 23YZHecGleqeiKYiAQQcq0 created_at: !ruby/object:DateTime 2015-11-25 15:06:06.304000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:06:06.304000000 Z content_type_id: chapter revision: 1 title_internal: 'Egypt: featured site, chapter 5' body: 'The ‘swimmers’ are not the only humans depicted here: there are others, some heavily adorned, some apparently engaged in activities. A meticulously engraved antelope’s hoofprint adds another element to this fascinating site. Perhaps most striking are the numerous ‘negative’ handprints, produced by the artist blowing pigment onto the rock face over splayed fingers. As with so much rock art, they leave an imprint as immediate and familiar as it is elusive and enigmatic.' background_images: - sys: id: 2halaUUgAMe6ES0uycIIIG created_at: !ruby/object:DateTime 2015-11-25 15:00:35.469000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:00:35.469000000 Z title: '2013,2034.188' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2halaUUgAMe6ES0uycIIIG/ec1812c9c376a941c691641c471b7105/2013_2034.188.jpg" - sys: id: 6Fqf4hcw1OeG2IIO442ckW created_at: !ruby/object:DateTime 2015-11-25 15:00:35.492000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:00:35.492000000 Z title: '2013,2034.192' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6Fqf4hcw1OeG2IIO442ckW/6d975af11e82e634f913ca9aed815e44/2013_2034.192.jpg" key_facts: sys: id: 1p0szJra88OeCEWCkE2Yky created_at: !ruby/object:DateTime 2015-11-26 10:46:28.092000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:47:28.403000000 Z content_type_id: country_key_facts revision: 2 title_internal: 'Egypt: key facts' image_count: 342 images date_range: Mostly 6,000 BC – 30 BC main_areas: Nile valley, Gilf Kebir Plateau techniques: Engravings, brush paintings, blown pigment paintings main_themes: Boats, cattle, wild animals, handprints, inscriptions thematic_articles: - sys: id: 72UN6TbsDmocqeki00gS4I created_at: !ruby/object:DateTime 2015-11-26 17:35:22.951000000 Z updated_at: !ruby/object:DateTime 2015-12-07 20:47:35.130000000 Z content_type_id: thematic revision: 4 title: Chariots in the Sahara slug: chariots-in-the-sahara lead_image: sys: id: 2Ed8OkQdX2YIYAIEQwiY8W created_at: !ruby/object:DateTime 2015-11-26 17:17:39.181000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:17:39.181000000 Z title: '2013,2034.999' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2Ed8OkQdX2YIYAIEQwiY8W/9873a75ad2995b1b7a86923eca583f31/2013_2034.999.jpg" chapters: - sys: id: 3pSkk40LWUWs28e0A2ocI2 created_at: !ruby/object:DateTime 2015-11-26 17:27:59.282000000 Z updated_at: !ruby/object:DateTime 2018-05-16 16:42:36.356000000 Z content_type_id: chapter revision: 2 title_internal: 'Thematic: chariots, chapter 1' body: A number of sites from this Collection are located in the Libyan Desert, notably the Fezzan region, and include paintings of chariots in a variety of forms dating to the Horse Period, from up to 3,000 years ago. This has stimulated some interesting questions about the use of chariots in what appears to be such a seemingly inappropriate environment for a wheeled vehicle, as well as the nature of representation. Why were chariots used in the desert and why were they represented in such different ways? - sys: id: 2Hjql4WXLOsmCogY4EAWSq created_at: !ruby/object:DateTime 2015-11-26 17:18:19.534000000 Z updated_at: !ruby/object:DateTime 2018-05-16 16:43:36.197000000 Z content_type_id: image revision: 2 image: sys: id: 2Ed8OkQdX2YIYAIEQwiY8W created_at: !ruby/object:DateTime 2015-11-26 17:17:39.181000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:17:39.181000000 Z title: '2013,2034.999' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2Ed8OkQdX2YIYAIEQwiY8W/9873a75ad2995b1b7a86923eca583f31/2013_2034.999.jpg" caption: Two-wheeled chariot in profile view. Tihenagdal, Acacus Mountains, Libya. 2013,2034.999 © TARA / <NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3588528&partId=1&people=197356&museumno=2013,2034.999&page=1 - sys: id: 3TiPUtUxgAQUe0UGoQUqO0 created_at: !ruby/object:DateTime 2015-11-26 17:28:18.968000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:28:18.968000000 Z content_type_id: chapter revision: 1 title_internal: 'Thematic: chariots, chapter 2' body: The chariot has been one of the great empowering innovations of history. It likely originated in Mesopotamia about 3000 BC due to advances in metallurgy during the Bronze Age, and has served as a primary means of transport until quite recently in the historical period across Africa, Eurasia and Europe. Chariots provided rapid and efficient transport, and were ideal for the battlefield as the design provided a raised firing platform for archers . As a result the chariot became the principal war machine from the Egyptians through to the Romans; and the Chinese, who owned an army of 10,000 chariots. Indeed, our use of the word car is a derivative of the Latin word carrus, meaning ‘a chariot of war or of triumph’. - sys: id: 5ZxcAksrFSKEGacE2iwQuk created_at: !ruby/object:DateTime 2015-11-26 17:19:58.050000000 Z updated_at: !ruby/object:DateTime 2018-05-16 16:44:46.340000000 Z content_type_id: image revision: 2 image: sys: id: 5neJpIDOpyUQAWC8q0mCIK created_at: !ruby/object:DateTime 2015-11-26 17:17:39.141000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:17:39.141000000 Z title: '124534' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5neJpIDOpyUQAWC8q0mCIK/d8ee0111089adb2b565b48919f21dfbe/124534.jpg" caption: Neo-Assyrian Gypsum wall panel relief showing Ashurnasirpal II hunting lions, 865BC – 860 BC. © Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=367027&partId=1&people=197356&museumno=124534&page=1 - sys: id: 2Grf0McSJ2Uq4SUaUQAMwU created_at: !ruby/object:DateTime 2015-11-26 17:28:46.851000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:28:46.851000000 Z content_type_id: chapter revision: 1 title_internal: 'Thematic: chariots, chapter 3' body: The chariot in the Sahara was probably introduced by the Garamantes, a cultural group thought to be descended from Berbers and Saharan pastoralists. There is little textual information about the Garamantes, documentation comes mainly from Greek and Roman sources. Herodotus described them as ‘a very great nation’. Recent archaeological research has shown that the Garamantes established about eight major towns as well as numerous other settlements, and were ‘brilliant farmers, resourceful engineers, and enterprising merchants’. The success of the Garamantes was based on their subterranean water-extraction system, a network of underground tunnels, allowing the Garamantian culture to flourish in an increasingly arid environment, resulting in population expansion, urbanisation, and conquest. - sys: id: 6fOKcyIgKcyMi8uC4WW6sG created_at: !ruby/object:DateTime 2015-11-26 17:20:33.572000000 Z updated_at: !ruby/object:DateTime 2018-05-16 16:45:32.605000000 Z content_type_id: image revision: 2 image: sys: id: 4DBpxlJqeAS4O0eYeCO2Ms created_at: !ruby/object:DateTime 2015-11-26 17:17:39.152000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:17:39.152000000 Z title: '2013,2034.407' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4DBpxlJqeAS4O0eYeCO2Ms/18e67077bdaa437ac82e85ba48cdb0da/2013_2034.407.jpg" caption: A so-called ‘Flying gallop’ chariot. Wadi Teshuinat, Acacus Mountains, Libya. 2013,2034.407 © TARA / <NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3580186&partId=1&people=197356&museumno=2013,2034.407&page=1 - sys: id: CAQ4O5QWhaCeOQAMmgGSo created_at: !ruby/object:DateTime 2015-11-26 17:29:06.521000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:29:06.521000000 Z content_type_id: chapter revision: 1 title_internal: 'Thematic: chariots, chapter 4' body: On average there are about 500 drawings of chariots across the Sahara, from the Fezzan in Libya through the Aïr of Niger into northern Mali and then westward to the Atlantic coast; but not all were produced by the Garamantes. It is still not certain that chariots were driven along the routes where their depictions occur; remains of chariots have never been found west of the Fezzan. However, the Fezzan states were thriving trade routes and chariots are likely to have been used to transport salt, cloth, beads and metal goods in exchange for gold, ivory and slaves. The widespread occurrence of chariot imagery on Saharan rock outcrops has led to the proposition of ‘chariot routes’ linking North and West Africa. However, these vehicles were not suited for long-distance transport across desert terrain; more localised use is probable, conducted through middlemen who were aware of the trade routes through the desert landscape. Additionally, the horse at this time was a prestige animal and it is unlikely that they facilitated transport across the Saharan trade routes, with travellers rather utilising donkeys or oxen. - sys: id: 5cgk0mmvKwC0IGsCyIsewG created_at: !ruby/object:DateTime 2015-11-26 17:20:59.281000000 Z updated_at: !ruby/object:DateTime 2018-05-16 16:46:44.461000000 Z content_type_id: image revision: 2 image: sys: id: 4XYASoQz6UQggUGI8gqkgq created_at: !ruby/object:DateTime 2015-11-26 17:17:39.148000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:17:39.148000000 Z title: '2013,2034.389' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4XYASoQz6UQggUGI8gqkgq/d167c56220dfd17c399b02086fe9ebc3/2013_2034.389.jpg" caption: This two wheeled chariot is being drawn by a cow with upturned horns. Awis Valley, Acacus Mountains, Libya. 2013,2034.389 © TARA / <NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3579985&partId=1&people=197356&museumno=2013,2034.389&page=1 - sys: id: 5pKuD1vPdmcs2o8eQeumM4 created_at: !ruby/object:DateTime 2015-11-26 17:29:23.611000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:29:23.611000000 Z content_type_id: chapter revision: 1 title_internal: 'Thematic: chariots, chapter 5' body: The absence of archaeological evidence for chariots has led to the suggestion that some representations of chariots may have been the result of cultural diffusion, transmitted orally by nomadic peoples traversing the region. Artists may never have actually seen the vehicles themselves. If this is the case, chariot symbols may have acquired some special meaning above their function as modes of transport. It may also explain why some representations of chariots do not seem to conform to more conventional styles of representations and account for the different ways in which they were depicted. - sys: id: wckVt1SCpqs0IYeaAsWeS created_at: !ruby/object:DateTime 2015-11-26 17:21:42.421000000 Z updated_at: !ruby/object:DateTime 2018-05-16 16:48:40.965000000 Z content_type_id: image revision: 3 image: sys: id: 279BaN9Z4QeOYAWCMSkyeQ created_at: !ruby/object:DateTime 2015-11-26 17:17:46.288000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:17:46.288000000 Z title: '2013,2034.392' description: url: "//images.ctfassets.net/xt8ne4gbbocd/279BaN9Z4QeOYAWCMSkyeQ/7606d86492a167b9ec4b105a7eb57d74/2013_2034.392.jpg" caption: These two images (above and below) depicts chariots as if ‘flattened out’, with the horses represented back to back. Awis Valley, Acacus Mountains, Libya. 2013,2034.392 © TARA / <NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3579981&partId=1&people=197356&museumno=2013,2034.392&page=1 - sys: id: 7fKfpmISPYs04YOi8G0kAm created_at: !ruby/object:DateTime 2015-11-26 17:23:05.317000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:23:05.317000000 Z content_type_id: image revision: 1 image: sys: id: 28JPIQ4mYQCMYQmMQ0Oke8 created_at: !ruby/object:DateTime 2015-11-26 17:17:45.941000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:17:45.941000000 Z title: '2013,2034.393' description: url: "//images.ctfassets.net/xt8ne4gbbocd/28JPIQ4mYQCMYQmMQ0Oke8/665bea9aafec58dfe3487ee665b3a9ec/2013_2034.393.jpg" caption: 2013,2034.393 © TARA / <NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3579980&partId=1&people=197356&museumno=2013,2034.393&page=1 - sys: id: 3xUchEu4sECWq4mAoEYYM4 created_at: !ruby/object:DateTime 2015-11-26 17:23:33.472000000 Z updated_at: !ruby/object:DateTime 2018-05-16 17:20:52.618000000 Z content_type_id: image revision: 2 image: sys: id: 697LgKlm3SWSQOu8CqSuIO created_at: !ruby/object:DateTime 2015-11-26 17:17:45.956000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:17:45.956000000 Z title: '2013,2034.370' description: url: "//images.ctfassets.net/xt8ne4gbbocd/697LgKlm3SWSQOu8CqSuIO/c8afe8c1724289dee3c1116fd4ba9280/2013_2034.370.jpg" caption: Possible chariot feature in top left of image. Acacus Mountains, Libya. 2013,2034.370 © TARA / <NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3579291&partId=1&people=197356&museumno=2013,2034.370&page=1 - sys: id: 6bQzinrqXmYESoWqyYYyuI created_at: !ruby/object:DateTime 2015-11-26 17:24:01.069000000 Z updated_at: !ruby/object:DateTime 2018-05-16 17:21:25.227000000 Z content_type_id: image revision: 2 image: sys: id: 5RKPaYinvOW6yyCGYcIsmK created_at: !ruby/object:DateTime 2015-11-26 17:17:45.952000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:17:45.952000000 Z title: '2013,2034.371' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5RKPaYinvOW6yyCGYcIsmK/a0328f912ac8f6fe017ce99d8e673421/2013_2034.371.jpg" caption: Possible chariots with two wheels. Acacus Mountains, Fezzan District, Libya. 2013,2034.371 © TARA / <NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3579290&partId=1&people=197356&museumno=2013,2034.371&page=1 - sys: id: 5qthr4HJaEoIe2sOOqiU4K created_at: !ruby/object:DateTime 2015-11-26 17:29:40.388000000 Z updated_at: !ruby/object:DateTime 2018-05-16 17:31:17.884000000 Z content_type_id: chapter revision: 2 title_internal: 'Thematic: chariots, chapter 6' body: |- The two images may or may not depict chariots. The rectangular shapes are potentially abstracted forms of the chariot similar to the ‘flattened out’ depictions discussed previously. These potentially abstracted representations often sit alongside distinguishing figures, such as geometric bi-triangular figures, spears or lances, women wearing long dresses, and animals drawn in a fairly naturalistic style, of the Horse Period when the chariots were being used. Beside the schematic and simply depicted chariots, there is also a group which has been termed the ‘flying gallop chariots’. Their distribution includes the whole Tassili region, although there are fewer in the Acacus Mountains. They resemble the classical two-wheeled antique chariots, generally drawn by two horses, but sometimes three, or even four. The driver is usually alone, and is depicted in a typical style with a stick head. The majority are shown at full speed, with the driver holding a whip standing on a small platform, sometimes straining forward. - sys: id: 2NEHx4J06IMSceEyC4w0CA created_at: !ruby/object:DateTime 2015-11-26 17:24:30.605000000 Z updated_at: !ruby/object:DateTime 2018-05-16 17:31:46.413000000 Z content_type_id: image revision: 2 image: sys: id: 74j3IOLwLS8IocMCACY2W created_at: !ruby/object:DateTime 2015-11-26 17:17:45.949000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:17:45.949000000 Z title: '2013,2034.523' description: url: "//images.ctfassets.net/xt8ne4gbbocd/74j3IOLwLS8IocMCACY2W/5495e8c245e10db13caf5cb0f36905c4/2013_2034.523.jpg" caption: "'Flying gallop’ chariot, <NAME>, Acacus Mountains, Fezzan District, Libya. 2013,2034.523 © TARA / <NAME>" col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3583068&partId=1&people=197356&museumno=2013,2034.523&page=1 - sys: id: 1YKtISfrKAQ6M4mMawIOYK created_at: !ruby/object:DateTime 2015-11-26 17:30:08.834000000 Z updated_at: !ruby/object:DateTime 2018-05-16 17:33:37.308000000 Z content_type_id: chapter revision: 2 title_internal: 'Thematic: chariots, chapter 7' body: |- In a similar manner to the schematic chariots, the 'Flying Gallop' depictions display the entire platform and both wheels of the chariot. In addition, more than one horse is depicted as a single horse in profile with numerous legs indicating multiple horses; an artistic technique first seen during the Upper Palaeolithic in Europe. Interestingly, in the Libyan rock art of the Acacus Mountains it seemed that animals could be conceived of in profile and in movement, but chariots were conceived of differently, and are represented in plain view, seen from above or in three-quarters perspective. Why are chariots depicted in a variety of ways, and what can we say about the nature of representation in relation to chariots? It is clear that chariots are able to be depicted in profile view, yet there are variations that digress from this perspective. In relation to the few examples we have come across so far in the Acacus Mountains in south-western Libya, one observation we might make is that the ways in which chariots have been represented may be indicative of the ways in which they have been observed by the artists representing them; as a rule from above. The rock shelters in the Acacus are often some height above the now dried up wadis, and so the ways in which they conceived of representing the chariot itself , whether as a flying gallop chariot, a chariot drawn by a bovid or as an abstraction, may have become a particular representational convention. The ways in which animals were represented conformed also to a convention, one that had a longer tradition, but chariots were an innovation and may have been represented as they were observed; from higher up in the rockshelters; thus chariots were conceived of as a whole and from an aerial perspective. The ways in which environments affect our perceptions of dimension, space and colour are now well-established, initially through cross-cultural anthropological studies in the 1960s, and becoming better understood through more recent research concerning the brain. Of course, this is speculation, and further research would be needed to consider all the possibilities. But for now, we can start to see some intriguing lines of enquiry and research areas that these images have stimulated. - sys: id: 4nHApyWfWowgG0qASeKEwk created_at: !ruby/object:DateTime 2015-11-26 17:25:19.180000000 Z updated_at: !ruby/object:DateTime 2018-05-16 17:34:17.369000000 Z content_type_id: image revision: 2 image: sys: id: 4Mn54dTjEQ80ssSOK0q0Mq created_at: !ruby/object:DateTime 2015-11-26 17:17:39.129000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:17:39.129000000 Z title: '135568' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4Mn54dTjEQ80ssSOK0q0Mq/c1bca8c151b882c16adaf7bc449e1850/135568.jpg" caption: Model of chariot, Middle Bronze Age – Early Bronze Age, 2000BC, Eastern Anatolia Region. 1971,0406.1 © Trustees of the British Museum. The design of this chariot is very similar to the representation in Fig. 4. col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=369521&partId=1&people=197356&museumno=135568&page=1 - sys: id: 5dtoX8DJv2UkguMM24uWwK created_at: !ruby/object:DateTime 2015-11-26 17:26:17.455000000 Z updated_at: !ruby/object:DateTime 2018-05-16 17:34:59.909000000 Z content_type_id: image revision: 2 image: sys: id: 7zQLgo270Am82CG0Qa6gaE created_at: !ruby/object:DateTime 2015-11-26 17:17:45.956000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:17:45.956000000 Z title: '894,1030.1' description: url: "//images.ctfassets.net/xt8ne4gbbocd/7zQLgo270Am82CG0Qa6gaE/80aa63978217874eaaa0960a6e0847d6/894_1030.1.jpg" caption: Bronze model of a two-horse racing chariot. Roman, 1st century – 2nd century, Latium, Tiber River. 1894,1030.1 © Trustees of the British Museum. col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=399770&partId=1&people=197356&museumno=1894,1030.1&page=1 - sys: id: 74fcVRriowwOQeWua2uMMY created_at: !ruby/object:DateTime 2015-11-26 17:30:27.301000000 Z updated_at: !ruby/object:DateTime 2018-05-16 17:35:36.578000000 Z content_type_id: chapter revision: 2 title_internal: 'Thematic: chariots, chapter 8' body: Vast trading networks across the Sahara Desert not only facilitated the spread of goods, but the routes served as a conduit for cultural diffusion through the spread of knowledge, ideas and technologies. Chariots were both functional and symbolic. As a mode of transport, as a weapon of war, as a means of trade and exchange and as a symbol of power, the chariot has been a cultural artefact for 4,000 years. Its temporal and spatial reach is evident not only in the rock art, but through the British Museum collections, which reveal comparisons between 2D rock art and 3D artefacts. Similarities and adjacencies occur not only in the structure and design of the chariots themselves but in their symbolic and pragmatic nature. - sys: id: 266zWxwbfC86gaKyG8myCU created_at: !ruby/object:DateTime 2015-11-26 17:26:53.266000000 Z updated_at: !ruby/object:DateTime 2018-05-16 17:43:56.525000000 Z content_type_id: image revision: 2 image: sys: id: 4rwQF960rueIOACosUMwoa created_at: !ruby/object:DateTime 2015-11-26 17:17:39.145000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:17:39.145000000 Z title: EA 37982 description: url: "//images.ctfassets.net/xt8ne4gbbocd/4rwQF960rueIOACosUMwoa/b5b41cda0efd36989292d004f039bace/EA_37982.jpg" caption: Fragment of a limestone tomb-painting representing the assessment of crops, c. 1350BC, Tomb of Nebamun, Thebes, Egypt. British Museum EA37982 ©Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=117388&partId=1&people=197356&museumno=37982&page=1 - sys: id: 2mTEgMGc5iiM00MOE4WSqU created_at: !ruby/object:DateTime 2015-11-26 17:27:28.284000000 Z updated_at: !ruby/object:DateTime 2018-05-16 17:44:28.029000000 Z content_type_id: image revision: 2 image: sys: id: 70cjifYtVeeqIOoOCouaGS created_at: !ruby/object:DateTime 2015-11-26 17:17:46.009000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:17:46.009000000 Z title: '1867,0101.870' description: url: "//images.ctfassets.net/xt8ne4gbbocd/70cjifYtVeeqIOoOCouaGS/066bc072069ab814687828a61e1ff1aa/1867_0101.870.jpg" caption: Gold coin of Diocletian, obverse side showing chariot. British Museum 1867,0101.870 ©Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=1189587&partId=1&people=197356&museumno=1867,0101.870&page=1 - sys: id: 5Z6SQu2oLuG40IIWEqKgWE created_at: !ruby/object:DateTime 2015-11-26 17:30:47.583000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:30:47.583000000 Z content_type_id: chapter revision: 1 title_internal: 'Thematic: chariots, chapter 9' body: A hoard of 100,000 Roman coins from the Diocletian period (not the above) were unearthed near Misurata, Libya, probably used to pay both regular Roman and local troops. Such finds demonstrate the symbolic power of the chariot and the diffusion of the imagery. citations: - sys: id: vVxzecw1jwam6aCcEA8cY created_at: !ruby/object:DateTime 2015-11-26 17:31:32.248000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:31:32.248000000 Z content_type_id: citation revision: 1 citation_line: <NAME>. ‘Kingdom of the Sands', in *Current Archaeology*, Vol. 57 No 2, March/April 2004 background_images: - sys: id: 3Cv9FvodyoQIQS2UaCo4KU created_at: !ruby/object:DateTime 2015-12-07 18:43:47.568000000 Z updated_at: !ruby/object:DateTime 2015-12-07 18:43:47.568000000 Z title: '01495388 001' description: url: "//images.ctfassets.net/xt8ne4gbbocd/3Cv9FvodyoQIQS2UaCo4KU/f243937c551a4a12f07c1063d13edaaa/01495388_001.jpg" - sys: id: 2yTKrZUOY00UsmcQ8sC0w4 created_at: !ruby/object:DateTime 2015-12-07 18:44:42.716000000 Z updated_at: !ruby/object:DateTime 2015-12-07 18:44:42.716000000 Z title: '01495139 001' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2yTKrZUOY00UsmcQ8sC0w4/8e527c421d837b3993026107d0a0acbb/01495139_001.jpg" - sys: id: 7oNFGUa6g8qSweyAyyiCAe created_at: !ruby/object:DateTime 2015-11-26 18:11:30.861000000 Z updated_at: !ruby/object:DateTime 2015-12-07 20:51:34.879000000 Z content_type_id: thematic revision: 4 title: The domesticated horse in northern African rock art slug: the-domesticated-horse lead_image: sys: id: n2MxgdjbMW2gm0IoOKkCU created_at: !ruby/object:DateTime 2015-11-26 17:51:43.133000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:43.133000000 Z title: Fig. 1. Painted horse description: url: "//images.ctfassets.net/xt8ne4gbbocd/n2MxgdjbMW2gm0IoOKkCU/e2c7369ef1e4ab11c71023a769f8fe0d/Fig._1._Painted_horse.jpg" chapters: - sys: id: 27bcd1mylKoMWiCQ2KuKMa created_at: !ruby/object:DateTime 2015-11-26 18:00:19.777000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:00:19.777000000 Z content_type_id: chapter revision: 1 title_internal: 'Thematic: horse, chapter 1' body: Throughout northern Africa, there is a wealth of rock art depicting the domestic horse and its various uses, providing valuable evidence for the uses of horses at various times in history, as well as a testament to their importance to Saharan peoples. - sys: id: 2EbfpTN9L6E0sYmuGyiaec created_at: !ruby/object:DateTime 2015-11-26 17:52:26.605000000 Z updated_at: !ruby/object:DateTime 2018-05-15 16:39:29.412000000 Z content_type_id: image revision: 2 image: sys: id: n2MxgdjbMW2gm0IoOKkCU created_at: !ruby/object:DateTime 2015-11-26 17:51:43.133000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:43.133000000 Z title: Fig. 1. Painted horse description: url: "//images.ctfassets.net/xt8ne4gbbocd/n2MxgdjbMW2gm0IoOKkCU/e2c7369ef1e4ab11c71023a769f8fe0d/Fig._1._Painted_horse.jpg" caption: 'Painted horse and rider, <NAME>, Chad. 2013,2034.6406 © TARA/David Coulson. ' col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3641775&partId=1&searchText=2013,2034.6406&page=1 - sys: id: 4QexWBEVXiAksikIK6g2S4 created_at: !ruby/object:DateTime 2015-11-26 18:00:49.116000000 Z updated_at: !ruby/object:DateTime 2018-05-15 16:40:28.446000000 Z content_type_id: chapter revision: 2 title: Horses and chariots title_internal: 'Thematic: horse, chapter 2' body: The first introduction of the domestic horse to Ancient Egypt- and thereby to Africa- is usually cited at around 1600 BC, linked with the arrival in Egypt of the Hyksos, a group from the Levant who ruled much of Northern Egypt during the Second Intermediate Period. By this point, horses had probably only been domesticated for about 2,000 years, but with the advent of the chariot after the 3rd millennium BC in Mesopotamia, the horse proved to be a valuable martial asset in the ancient world. One of the first clear records of the use of horses and chariots in battle in Africa is found in depictions from the mortuary complex of the Pharaoh Ahmose at Abydos from around 1525 BC, showing their use by Egyptians in defeating the Hyksos, and horses feature prominently in later Egyptian art. - sys: id: 22x06a7DteI0C2U6w6oKes created_at: !ruby/object:DateTime 2015-11-26 17:52:52.323000000 Z updated_at: !ruby/object:DateTime 2018-05-15 16:40:52.214000000 Z content_type_id: image revision: 2 image: sys: id: 1AZD3AxiUwwoYUWSWY8MGW created_at: !ruby/object:DateTime 2015-11-26 17:51:50.284000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:50.284000000 Z title: '2013,2034.1001' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1AZD3AxiUwwoYUWSWY8MGW/b68bd24c9b19c5c8c7752bfb75a5db0e/2013_2034.1001.jpg" caption: Painted two-horse chariot, Acacus Mountains, Libya. 2013,2034.1001 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3588526&partId=1&people=197356&museumno=2013,2034.1001&page=1 - sys: id: 1voXfvqIcQkgUYqq4w8isQ created_at: !ruby/object:DateTime 2015-11-26 18:01:15.173000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:01:15.173000000 Z content_type_id: chapter revision: 1 title_internal: 'Thematic: horse, chapter 3' body: 'Some of the most renowned images of horses in Saharan rock art are also those of chariot teams: in particular, those of the so-called ‘flying gallop’ style chariot pictures, from the Tassili n’Ajjer and Acacus mountains in modern Algeria and Libya. These distinctive images are characterised by depictions of one or more horses pulling a chariot with their legs outstretched in a stylised manner and are sometimes attributed to the Garamantes, a group who were a local power in the central Sahara from about 500 BC-700 AD. But the Ajjer Plateau is over a thousand miles from the Nile- how and when did the horse and chariot first make their way across the Western Desert to the rest of North Africa in the first place? Egyptian accounts indicate that by the 11th century BC Libyans (people living on the north African coast around the border of modern Egypt and Libya) were using chariots in war. Classical sources later write about the chariots of the Garamantes and of chariot use by peoples of the far western Sahara continuing into the 1st century BC, by which time the chariot horse had largely been eclipsed in war by the cavalry mount.' - sys: id: LWROS2FhUkywWI60eQYIy created_at: !ruby/object:DateTime 2015-11-26 17:53:42.845000000 Z updated_at: !ruby/object:DateTime 2018-05-15 16:41:33.841000000 Z content_type_id: image revision: 2 image: sys: id: 6N6BF79qk8EUygwkIgwcce created_at: !ruby/object:DateTime 2015-11-26 17:51:44.708000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:44.708000000 Z title: '2013,2034.4574' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6N6BF79qk8EUygwkIgwcce/ac95a5214a326794542e0707c0d819d7/2013_2034.4574.jpg" caption: Painted human figure and horse. Tarssed Jebest, Tassili n’Ajjer, Algeria. Horse displays Arabian breed-type characteristics such as dished face and high tail carriage. 2013,2034.4574 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3603790&partId=1&people=197356&museumno=2013,2034.4574+&page=1 - sys: id: 6eaH84QdUs46sEQoSmAG2u created_at: !ruby/object:DateTime 2015-11-26 18:01:48.835000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:01:48.835000000 Z content_type_id: chapter revision: 1 title: Horse Riding title_internal: 'Thematic: horse, chapter 4' body: As well as the unique iconography of rock art chariot depictions, there are also numerous paintings and engravings across northern Africa of people riding horses. Riding may have been practiced since the earliest times of horse domestication, though the earliest definitive depictions of horses being ridden come from the Middle East in the late 3rd and early 2nd millennia BC. Images of horses and riders in rock art occur in various areas of Morocco, Egypt and Sudan and are particularly notable in the Ennedi region of Chad and the Adrar and Tagant plateaus in Mauritania (interestingly, however, no definite images of horses are known in the Gilf Kebir/Jebel Uweinat area at the border of Egypt, Sudan and Libya). - sys: id: 6LTzLWMCTSak4IIukAAQMa created_at: !ruby/object:DateTime 2015-11-26 17:54:23.846000000 Z updated_at: !ruby/object:DateTime 2018-05-15 16:41:52.743000000 Z content_type_id: image revision: 2 image: sys: id: 4NdhGNLc9yEck4My4uQwIo created_at: !ruby/object:DateTime 2015-11-26 17:51:43.495000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:43.495000000 Z title: ME22958 description: url: "//images.ctfassets.net/xt8ne4gbbocd/4NdhGNLc9yEck4My4uQwIo/703945afad6a8e3c97d10b09c487381c/ME22958.jpg" caption: Terracotta mould of man on horseback, Old Babylonian, Mesopotamia 2000-1600 BC. One of the oldest known depictions of horse riding in the world. British Museum ME22958 © Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=388860&partId=1&people=197356&museumno=22958&page=1 - sys: id: 5YkSCzujy8o08yuomIu6Ei created_at: !ruby/object:DateTime 2015-11-26 17:54:43.227000000 Z updated_at: !ruby/object:DateTime 2018-05-16 11:12:34.068000000 Z content_type_id: image revision: 2 image: sys: id: 1tpjS4kZZ6YoeiWeIi8I4C created_at: !ruby/object:DateTime 2015-11-26 17:51:43.188000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:43.188000000 Z title: Fig. 5. Painted ‘bitriangular’ description: url: "//images.ctfassets.net/xt8ne4gbbocd/1tpjS4kZZ6YoeiWeIi8I4C/c798c1afb41006855c34363ec2b54557/Fig._5._Painted____bitriangular___.jpg" caption: Painted ‘bi-triangular’ horse and rider with saddle. <NAME>, Assaba, Mauritania. 2013,2034.12285 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3645983&partId=1&searchText=2013,2034.12285&page=1 - sys: id: 1vZDFfKXU0US2qkuaikG8m created_at: !ruby/object:DateTime 2015-11-26 18:02:13.433000000 Z updated_at: !ruby/object:DateTime 2018-05-16 11:14:56.468000000 Z content_type_id: chapter revision: 2 title_internal: 'Thematic: horse, chapter 5' body: Traditional chronologies for Saharan rock art areas tend to place depictions of ridden horses chronologically after those of horses and chariots, and in general use horse depictions to categorise regional stylistic periods of rock art according to broad date boundaries. As such, in most places, the ‘horse’ rock art period is usually said to cover about a thousand years from the end of the 2nd millennium BC. It is then considered to be succeeded by a ‘camel’ period, where the appearance of images of dromedaries – known only to have been introduced to the eastern Sahara from Arabia at the end of the 1st century BC – reflects the next momentous influx of a beast of burden to the area and thus a new dating parameter ([read more about depictions of camels in the Sahara](https://africanrockart.britishmuseum.org/thematic/camels-in-saharan-rock-art/)). However, such simplistic categorisation can be misleading. For one thing, although mounting horses certainly gained popularity over driving them, it is not always clear that depictions of ridden horses are not contemporary with those of chariots. Further, the horse remained an important martial tool after the use of war-chariots declined. Even after the introduction of the camel, there are several apparently contemporary depictions featuring both horse and camel riders. - sys: id: 2gaHPgtyEwsyQcUqEIaGaq created_at: !ruby/object:DateTime 2015-11-26 17:55:29.704000000 Z updated_at: !ruby/object:DateTime 2018-05-16 11:32:44.364000000 Z content_type_id: image revision: 3 image: sys: id: 6quML2y0nuYgSaeG0GGYy4 created_at: !ruby/object:DateTime 2015-11-26 17:51:50.292000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:50.292000000 Z title: '2013,2034.5739' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6quML2y0nuYgSaeG0GGYy4/7f48ae9c550dd6b4f0e80b8da10a3da6/2013_2034.5739.jpg" caption: Engraved ridden horse and camel. Draa Valley, Morocco. 2013,2034.5739 ©TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3619780&partId=1&people=197356&museumno=2013,2034.5739+&page=1 - sys: id: 583LKSbz9SSg00uwsqquAG created_at: !ruby/object:DateTime 2015-11-26 18:02:41.576000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:02:41.576000000 Z content_type_id: chapter revision: 1 title: Berber Horses title_internal: 'Thematic: horse, chapter 6' body: As the more manoeuvrable rider rose in popularity against the chariot as a weapon of war, historical reports from classical authors like Strabo tell us of the prowess of African horsemen such as the cavalry of the Numidians, a Berber group that allied with Carthage against the Romans in the 3rd century BC. Berber peoples would remain heavily associated with horse breeding and riding, and the later rock art of Mauritania has been attributed to Berber horsemen, or the sight of them. Although horses may already have reached the areas of modern Mauritania and Mali by this point, archaeological evidence does not confirm their presence in these south-westerly regions of the Sahara until much later, in the mid-1st millennium AD, and it has been suggested that some of the horse paintings in Mauritania may be as recent as 16th century. - sys: id: 7zrBlvCEGkW86Qm8k2GQAK created_at: !ruby/object:DateTime 2015-11-26 17:56:24.617000000 Z updated_at: !ruby/object:DateTime 2018-05-16 11:16:52.557000000 Z content_type_id: image revision: 2 image: sys: id: uOFcng0Q0gU8WG8kI2kyy created_at: !ruby/object:DateTime 2015-11-26 17:51:44.717000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:44.717000000 Z title: '2013,2034.5202' description: url: "//images.ctfassets.net/xt8ne4gbbocd/uOFcng0Q0gU8WG8kI2kyy/7fba0330e151fc416d62333f3093d950/2013_2034.5202.jpg" caption: Engraved horses and riders surrounded by Libyan-Berber script. Oued Djerat, Algeria. These images appear to depict riders using Arab-style saddles and stirrups, thus making them probably no older than 7th c. AD. 2013,2034.5202 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3624404&partId=1&people=197356&museumno=2013,2034.5202&page=1 - sys: id: 45vpX8SP7aGeOS0qGaoo4a created_at: !ruby/object:DateTime 2015-11-26 18:03:14.279000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:03:14.279000000 Z content_type_id: chapter revision: 1 title_internal: 'Thematic: horse, chapter 7' body: 'Certainly, from the 14th century AD, horses became a key commodity in trans-Saharan trade routes and became items of great military value in West Africa following the introduction of equipment such as saddles with structured trees (frames). Indeed, discernible images of such accoutrements in Saharan rock art can help to date it following the likely introduction of the equipment to the area: for example, the clear depiction of saddles suggests an image to be no older than the 1st century AD; images including stirrups are even more recent.' - sys: id: 7GeTQBofPamw0GeEAuGGee created_at: !ruby/object:DateTime 2015-11-26 17:56:57.851000000 Z updated_at: !ruby/object:DateTime 2018-05-16 11:29:02.520000000 Z content_type_id: image revision: 2 image: sys: id: 5MaSKooQvYssI4us8G0MyO created_at: !ruby/object:DateTime 2015-11-26 17:51:43.501000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:43.501000000 Z title: RRM12824 description: url: "//images.ctfassets.net/xt8ne4gbbocd/5MaSKooQvYssI4us8G0MyO/8c3a7c2d372f2c48a868d60201909932/RRM12824.jpg" caption: 19th-century Moroccan stirrups with typical curved base of the type possibly visible in the image above. 1939,0311.7-8 © Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=217451&partId=1&page=1 - sys: id: 6mNtqnqaEE2geSkU0IiYYe created_at: !ruby/object:DateTime 2015-11-26 18:03:32.195000000 Z updated_at: !ruby/object:DateTime 2018-05-16 11:29:50.228000000 Z content_type_id: chapter revision: 2 title_internal: 'Thematic: horse, chapter 8' body: 'Another intriguing possibility is that of gaining clues on the origins of modern horse breeds from rock art, in particular the ancient Barb breed native to the Maghreb, where it is still bred. Ancient Mesopotamian horses were generally depicted as heavily-built, and it has been suggested that the basic type for the delicate Arabian horse, with its dished (concave) facial profile and high-set tail, may have been developed in north-east Africa prior to its subsequent appearance and cultivation in Arabia, and that these features may be observed in Ancient Egyptian images from the New Kingdom. Likewise, there is the possibility that some of the more naturalistic paintings from the central Sahara show the similarly gracile features of the progenitors of the Barb, distinguishable from the Arab by its straight profile and low-set tail. Like the Arab, the Barb is a desert horse: hardy, sure-footed and able to withstand great heat; it is recognised as an ancient breed with an important genetic legacy, both in the ancestry of the Iberian horses later used throughout the Americas, and that of the modern racing thoroughbred.' - sys: id: 3OM1XJI6ruwGOwwmkKOKaY created_at: !ruby/object:DateTime 2015-11-26 17:57:25.145000000 Z updated_at: !ruby/object:DateTime 2018-05-16 11:30:30.915000000 Z content_type_id: image revision: 2 image: sys: id: 6ZmNhZjLCoQSEIYKIYUUuk created_at: !ruby/object:DateTime 2015-11-26 17:51:50.293000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:50.293000000 Z title: '2013,2034.1452' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6ZmNhZjLCoQSEIYKIYUUuk/45bbff5b29985eb19679e1e513499d6b/2013_2034.1452.jpg" caption: Engraved horses and riders, Awis, Acacus Mountains, Libya. High head carriage and full rumps suggest Arabian/Barb breed type features. Riders have been obscured. 2013,2034.1452 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3592678&partId=1&people=197356&museumno=2013,2034.1452&page=1 - sys: id: 40E0pTCrUIkk00uGWsus4M created_at: !ruby/object:DateTime 2015-11-26 17:57:49.497000000 Z updated_at: !ruby/object:DateTime 2018-05-16 11:33:55.443000000 Z content_type_id: image revision: 2 image: sys: id: 5mbJWrbZV6aQQOyamKMqIa created_at: !ruby/object:DateTime 2015-11-26 17:51:43.468000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:43.468000000 Z title: Fig. 10. Barb horses description: url: "//images.ctfassets.net/xt8ne4gbbocd/5mbJWrbZV6aQQOyamKMqIa/87f29480513be0a531e0a93b51f9eae5/Fig._10._Barb_horses.jpg" caption: Barb horses ridden at a festival in Agadir, Morocco. ©Notwist (Wikimedia Commons) col_link: https://commons.wikimedia.org/wiki/File:Berber_warriors_show.JPG - sys: id: 3z5YSVu9y8caY6AoYWge2q created_at: !ruby/object:DateTime 2015-11-26 18:04:02.770000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:04:02.770000000 Z content_type_id: chapter revision: 1 title: The symbolism of the horse title_internal: 'Thematic: horse, chapter 9' body: However, caution must be taken in drawing such comparisons based on morphology alone, especially given the gulf of time that has elapsed and the relative paucity of ‘naturalistic’ rock art images. Indeed, there is huge diversity of horse depictions throughout northern Africa, with some forms highly schematic. This variation is not only in style – and, as previously noted, in time period and geography – but also in context, as of course images of one subject cannot be divorced from the other images around them, on whichever surface has been chosen, and are integral to these surroundings. - sys: id: 1FRP1Z2hyQEWUSOoKqgic2 created_at: !ruby/object:DateTime 2015-11-26 17:58:21.234000000 Z updated_at: !ruby/object:DateTime 2019-02-21 15:41:39.821000000 Z content_type_id: image revision: 2 image: sys: id: 4EatwZfN72waIquQqWEeOs created_at: !ruby/object:DateTime 2015-11-26 17:51:43.121000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:43.121000000 Z title: '2013,2034.11147' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4EatwZfN72waIquQqWEeOs/d793f6266f2ff486e0e99256c2c0ca39/2013_2034.11147.jpg" caption: Engraved ‘Libyan Warrior-style’ figure with horse. Indakatte, Western Aïr Mountains, Niger. 2013,2034.11147 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3637713&partId=1&people=197356&museumno=2013,2034.11147+&page=1 - sys: id: 45pI4ivRk4IM6gaG40gUU0 created_at: !ruby/object:DateTime 2015-11-26 17:58:41.308000000 Z updated_at: !ruby/object:DateTime 2019-02-21 15:41:59.784000000 Z content_type_id: image revision: 2 image: sys: id: 2FcYImmyd2YuqMKQMwAM0s created_at: !ruby/object:DateTime 2015-11-26 17:51:43.117000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:43.117000000 Z title: Fig. 12. Human figure description: url: "//images.ctfassets.net/xt8ne4gbbocd/2FcYImmyd2YuqMKQMwAM0s/e48fda8e2a23b12e6afde5c560c3f164/Fig._12._Human_figure.jpg" caption: Human figure painted over by horse to appear mounted (digitally enhanced image). © TARA/<NAME> - sys: id: 54hoc6Htwck8eyewsa6kA8 created_at: !ruby/object:DateTime 2015-11-26 18:04:26.929000000 Z updated_at: !ruby/object:DateTime 2015-11-26 18:04:26.929000000 Z content_type_id: chapter revision: 1 title_internal: 'Thematic: horse, chapter 10' body: The nature of the depictions in this sense speaks intriguingly of the apparent symbolism and implied value of the horse image in different cultural contexts. Where some Tassilian horses are delicately painted in lifelike detail, the stockier images of horses associated with the so-called ‘Libyan Warrior’ style petroglyphs of the Aïr mountains and Adrar des Ifoghas in Niger and Mali appear more as symbolic accoutrements to the central human figures and tend not to be shown as ridden. By contrast, there are paintings in the Ennedi plateau of Chad where galloping horse figures have clearly been painted over existing walking human figures to make them appear as if riding. - sys: id: 4XMm1Mdm7Y0QacMuy44EKa created_at: !ruby/object:DateTime 2015-11-26 17:59:06.184000000 Z updated_at: !ruby/object:DateTime 2019-02-21 15:42:27.444000000 Z content_type_id: image revision: 2 image: sys: id: 21xnJrk3dKwW6uSSkGumMS created_at: !ruby/object:DateTime 2015-11-26 17:51:44.697000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:44.697000000 Z title: '2013,2034.6297' description: url: "//images.ctfassets.net/xt8ne4gbbocd/21xnJrk3dKwW6uSSkGumMS/698c254a9a10c5a9a56d69e0525bca83/2013_2034.6297.jpg" caption: Engraved horse, <NAME>, Ennedi Plateau, Chad. 2013,2034.6297 © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3637529&partId=1&people=197356&museumno=2013,2034.6297&page=1 - sys: id: 4rB9FCopjOCC4iA2wOG48w created_at: !ruby/object:DateTime 2015-11-26 17:59:26.549000000 Z updated_at: !ruby/object:DateTime 2019-02-21 15:43:34.211000000 Z content_type_id: image revision: 2 image: sys: id: 3PfHuSbYGcqeo2U4AEKsmM created_at: !ruby/object:DateTime 2015-11-26 17:51:43.196000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:43.196000000 Z title: Fig. 14. Engraved horse description: url: "//images.ctfassets.net/xt8ne4gbbocd/3PfHuSbYGcqeo2U4AEKsmM/33a068fa954954fd3b9b446c943e0791/Fig._14._Engraved_horse.jpg" caption: Engraved horse, Eastern Aïr Mountains. 2013,2034.9421 ©TARA/<NAME>. col_link: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3640574&partId=1&searchText=2013,2034.9421&page=1 - sys: id: 6tFSQzFupywiK6aESCgCia created_at: !ruby/object:DateTime 2015-11-26 18:04:56.612000000 Z updated_at: !ruby/object:DateTime 2019-02-21 15:47:26.838000000 Z content_type_id: chapter revision: 2 title_internal: 'Thematic: horse, chapter 11' body: |- In each of these cases, the original symbolic intent of the artists have been lost to time, but with these horse depictions, as with so much African rock art imagery, there is great scope for further future analysis. Particularly intriguing, for example, are the striking stylistic similarities in horse depictions across great distances, such the horse depictions with bi-triangular bodies (see above), or with fishbone-style tails which may be found almost two thousand miles apart in Chad and Mauritania. Whatever the myriad circumstances and significances of the images, it is clear that following its introduction to the continent, the hardy and surefooted desert horse’s usefulness for draught, transport and fighting purposes transformed the societies which used it and gave it a powerful symbolic value. - sys: id: 2P6ERbclfOIcGEgI6e0IUq created_at: !ruby/object:DateTime 2015-11-26 17:59:46.042000000 Z updated_at: !ruby/object:DateTime 2019-02-21 15:45:12.419000000 Z content_type_id: image revision: 2 image: sys: id: 3UXc5NiGTYQcmu2yuU42g created_at: !ruby/object:DateTime 2015-11-26 17:51:43.128000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:43.128000000 Z title: Fig. 15. Painted horse, Terkei description: url: "//images.ctfassets.net/xt8ne4gbbocd/3UXc5NiGTYQcmu2yuU42g/7586f05e83f708ca9d9fca693ae0cd83/Fig._15._Painted_horse__Terkei.jpg" caption: Painted horse, Terkei, Ennedi Plateau, Chad. 2013,2034.6537 © TARA/David Coulson col_link: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3640682&partId=1&searchText=2013,2034.6537&page=1 citations: - sys: id: 32AXGC1EcoSi4KcogoY2qu created_at: !ruby/object:DateTime 2015-11-26 17:51:20.602000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:20.602000000 Z content_type_id: citation revision: 1 citation_line: "<NAME>. & <NAME>. 2000, *The Origins and Development of African Livestock: archaeology, genetics, linguistics and ethnography*. London; New York, NY: UCL Press\n \n<NAME>., <NAME>., <NAME>., 2012. *The Horse: From Arabia to Royal Ascot*. London: British Museum Press\n \nLaw, R., 1980. *The Horse in West African History*. Oxford: Oxford University Press\n \nHachid, M. 2000. *Les Premieres Berbères*. Aix-en-Provence: Edisud\n \nLhote, H. 1952. 'Le cheval et le chameau dans les peintures et gravures rupestres du Sahara', *Bulletin de l'Institut franç ais de l'Afrique noire* 15: 1138-228\n \n<NAME>. & <NAME>. 2010, *A gift from the desert: the art, history, and culture of the Arabian horse*. Lexington, KY: Kentucky Horse Park\n\n" background_images: - sys: id: 2avgKlHUm8CauWie6sKecA created_at: !ruby/object:DateTime 2015-12-07 18:44:31.346000000 Z updated_at: !ruby/object:DateTime 2015-12-07 18:44:31.346000000 Z title: EAF 141485 description: url: "//images.ctfassets.net/xt8ne4gbbocd/2avgKlHUm8CauWie6sKecA/cf02168ca83c922f27eca33f16e8cc90/EAF_141485.jpg" - sys: id: 1wtaUDwbSk4MiyGiISE6i8 created_at: !ruby/object:DateTime 2015-12-07 18:43:51.804000000 Z updated_at: !ruby/object:DateTime 2015-12-07 18:43:51.804000000 Z title: 01522751 001 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1wtaUDwbSk4MiyGiISE6i8/5918544d0289f9c4b2b4724f4cda7a2d/01522751_001.jpg" - sys: id: 1KwPIcPzMga0YWq8ogEyCO created_at: !ruby/object:DateTime 2015-11-26 16:25:56.681000000 Z updated_at: !ruby/object:DateTime 2015-12-07 20:49:15.151000000 Z content_type_id: thematic revision: 5 title: 'Sailors on sandy seas: camels in Saharan rock art' slug: camels-in-saharan-rock-art lead_image: sys: id: 46X3vtG1faouSYYws0Aywu created_at: !ruby/object:DateTime 2015-11-26 16:07:51.521000000 Z updated_at: !ruby/object:DateTime 2019-02-12 02:30:35.572000000 Z title: View of camel salt caravan crossing the Ténéré desert. Niger. ©David Coulson/TARA description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3652083&partId=1&searchText=2013,2034.10379&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/46X3vtG1faouSYYws0Aywu/6ff8cc3f26c918c81157746e1b2b3131/Fig._1._Camel.jpg" chapters: - sys: id: 1Q7xHD856UsISuceGegaqI created_at: !ruby/object:DateTime 2015-11-26 16:19:29.618000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:19:29.618000000 Z content_type_id: chapter revision: 1 title_internal: 'Camels: thematic, chapter 1' body: 'If we were to choose a defining image for the Sahara Desert, it would probably depict an endless sea of yellow dunes under a blue sky and, off in the distance, a line of long-legged, humped animals whose profiles have become synonymous with deserts: the one-humped camel (or dromedary). Since its domestication, the camel’s resistance to heat and its ability to survive with small amounts of water and a diet of desert vegetation have made it a key animal for inhabitants of the Sahara, deeply bound to their economy, material culture and lifestyle.' - sys: id: 4p7wUbC6FyiEYsm8ukI0ES created_at: !ruby/object:DateTime 2015-11-26 16:09:23.136000000 Z updated_at: !ruby/object:DateTime 2019-02-12 02:30:19.986000000 Z content_type_id: image revision: 3 image: sys: id: 46X3vtG1faouSYYws0Aywu created_at: !ruby/object:DateTime 2015-11-26 16:07:51.521000000 Z updated_at: !ruby/object:DateTime 2019-02-12 02:30:35.572000000 Z title: View of camel salt caravan crossing the Ténéré desert. Niger. ©David Coulson/TARA description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3652083&partId=1&searchText=2013,2034.10379&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/46X3vtG1faouSYYws0Aywu/6ff8cc3f26c918c81157746e1b2b3131/Fig._1._Camel.jpg" caption: Camel salt caravan crossing the Ténéré desert in Niger. 2013,2034.10487 ©<NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3652360&partId=1&searchText=2013,2034.10487&page=1 - sys: id: 1LsXHHPAZaIoUksC2US08G created_at: !ruby/object:DateTime 2015-11-26 16:19:46.820000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:19:46.820000000 Z content_type_id: chapter revision: 1 title_internal: 'Camels: thematic, chapter 2' body: Yet, surprising as it seems, the camel is a relative newcomer to the Sahara – at least when compared to other domestic animals such as cattle, sheep, horses and donkeys. Although the process is not yet fully known, camels were domesticated in the Arabian Peninsula around the third millennium BC, and spread from there to the Middle East, North Africa and Somalia from the 1st century AD onwards. The steps of this process from Egypt to the Atlantic Ocean have been documented through many different historical sources, from Roman texts to sculptures or coins, but it is especially relevant in Saharan rock art, where camels became so abundant that they have given their name to a whole period. The depictions of camels provide an incredible amount of information about the life, culture and economy of the Berber and other nomadic communities from the beginnings of the Christian era to the Muslim conquest in the late years of the 7th century. - sys: id: j3q9XWFlMOMSK6kG2UWiG created_at: !ruby/object:DateTime 2015-11-26 16:10:00.029000000 Z updated_at: !ruby/object:DateTime 2018-05-17 14:21:07.255000000 Z content_type_id: image revision: 2 image: sys: id: 6afrRs4VLUS4iEG0iwEoua created_at: !ruby/object:DateTime 2015-11-26 16:07:34.273000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:34.273000000 Z title: EA26664 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6afrRs4VLUS4iEG0iwEoua/e00bb3c81c6c9b44b5e224f5a8ce33a2/EA26664.jpg" caption: Roman terracotta camel with harness, 1st – 3rd century AD, Egypt. British Museum 1891,0403.31 © Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?museumno=1891,0430.31&objectId=118725&partId=1 - sys: id: NxdAnazJaUkeMuyoSOy68 created_at: !ruby/object:DateTime 2015-11-26 16:20:03.948000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:20:03.948000000 Z content_type_id: chapter revision: 1 title_internal: 'Camels: thematic, chapter 3' body: 'What is it that makes camels so suited to deserts? It is not only their ability to transform the fat stored in their hump into water and energy, or their capacity to eat thorny bushes, acacia leaves and even fish and bones. Camels are also able to avoid perspiration by manipulating their core temperature, enduring fluctuations of up to six degrees that could be fatal for other mammals. They rehydrate very quickly, and some of their physical features (nostrils, eyebrows) have adapted to increase water conservation and protect the animals from dust and sand. All these capacities make camels uniquely suited to hot climates: in temperatures of 30-40 °C, they can spend up to 15 days without water. In addition, they are large animals, able to carry loads of up to 300kg, over long journeys across harsh environments. The pads on their feet have evolved so as to prevent them from sinking into the sand. It is not surprising that dromedaries are considered the ‘ships of the desert’, transporting people, commodities and goods through the vast territories of the Sahara.' - sys: id: 2KjIpAzb9Kw4O82Yi6kg2y created_at: !ruby/object:DateTime 2015-11-26 16:10:36.039000000 Z updated_at: !ruby/object:DateTime 2018-05-17 14:39:34.523000000 Z content_type_id: image revision: 2 image: sys: id: 6iaMmNK91YOU00S4gcgi6W created_at: !ruby/object:DateTime 2015-11-26 16:07:51.477000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:51.477000000 Z title: Af1937,0105.16 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6iaMmNK91YOU00S4gcgi6W/4a850695b34c1766d1ee5a06f61f2b36/Af1937_0105.16.jpg" caption: Clay female dromedary (possibly a toy), Somalia. British Museum Af1937,0105.16 © Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?assetId=1088379&objectId=590967&partId=1 - sys: id: 12mIwQ0wG2qWasw4wKQkO0 created_at: !ruby/object:DateTime 2015-11-26 16:11:00.578000000 Z updated_at: !ruby/object:DateTime 2018-05-17 14:45:29.810000000 Z content_type_id: image revision: 2 image: sys: id: 4jTR7LKYv6IiY8wkc2CIum created_at: !ruby/object:DateTime 2015-11-26 16:07:51.505000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:51.505000000 Z title: Fig. 4. Man description: url: "//images.ctfassets.net/xt8ne4gbbocd/4jTR7LKYv6IiY8wkc2CIum/3dbaa11c18703b33840a6cda2c2517f2/Fig._4._Man.jpg" caption: Man leading a camel train through the Ennedi Plateau, Chad. 2013,2034.6134 ©<NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3636989&partId=1&searchText=2013,2034.6134&page=1 - sys: id: 6UIdhB0rYsSQikE8Yom4G6 created_at: !ruby/object:DateTime 2015-11-26 16:20:29.219000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:20:29.219000000 Z content_type_id: chapter revision: 1 title_internal: 'Camels: thematic, chapter 4' body: As mentioned previously, camels came from the Arabian Peninsula through Egypt, where bone remains have been dated to the early 1st millennium BC. However, it took hundreds of years to move into the rest of North Africa due to the River Nile, which represented a major geographical and climatic barrier for these animals. The expansion began around the beginning of the Christian era, and probably took place both along the Mediterranean Sea and through the south of the Sahara. At this stage, it appears to have been very rapid, and during the following centuries camels became a key element in the North African societies. They were used mainly for riding, but also for transporting heavy goods and even for ploughing. Their milk, hair and meat were also used, improving the range of resources available to their herders. However, it seems that the large caravans that crossed the desert searching for gold, ivory or slaves came later, when the Muslim conquest of North Africa favoured the establishment of vast trade networks with the Sahel, the semi-arid region that lies south of the Sahara. - sys: id: YLb3uCAWcKm288oak4ukS created_at: !ruby/object:DateTime 2015-11-26 16:11:46.395000000 Z updated_at: !ruby/object:DateTime 2018-05-17 14:46:15.751000000 Z content_type_id: image revision: 2 image: sys: id: 5aJ9wYpcHe6SImauCSGoM8 created_at: !ruby/object:DateTime 2015-11-26 16:06:48.336000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:06:48.336000000 Z title: '1923,0401.850' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5aJ9wYpcHe6SImauCSGoM8/74efd37612ec798fd91c2a46c65587f7/1923_0401.850.jpg" caption: Glass paste gem imitating beryl, engraved with a short, bearded man leading a camel with a pack on its hump. Roman Empire, 1st – 3rd century AD. 1923,0401.850 ©Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=434529&partId=1&museumno=1923,0401.850&page=1 - sys: id: 3uitqbkcY8s8GCcicKkcI4 created_at: !ruby/object:DateTime 2015-11-26 16:20:45.582000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:20:45.582000000 Z content_type_id: chapter revision: 1 title_internal: 'Camels: thematic, chapter 5' body: Rock art can be extremely helpful in learning about the different ways in which camels were used in the first millennium AD. Images of camels are found in both engravings and paintings in red, white or – on rare occasions – black; sometimes the colours are combined to achieve a more impressive effect. They usually appear in groups, alongside humans, cattle and, occasionally, dogs and horses. Sometimes, even palm trees and houses are included to represent the oases where the animals were watered. Several of the scenes show female camels herded or taking care of their calves, showing the importance of camel-herding and breeding for the Libyan-Berber communities. - sys: id: 5OWosKxtUASWIO6IUii0EW created_at: !ruby/object:DateTime 2015-11-26 16:12:17.552000000 Z updated_at: !ruby/object:DateTime 2018-05-17 15:11:49.775000000 Z content_type_id: image revision: 2 image: sys: id: 3mY7XFQW6QY6KekSQm6SIu created_at: !ruby/object:DateTime 2015-11-26 16:06:48.343000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:06:48.343000000 Z title: '2013,2034.383' description: url: "//images.ctfassets.net/xt8ne4gbbocd/3mY7XFQW6QY6KekSQm6SIu/85c0b70ab40ead396c695fe493081801/2013_2034.383.jpg" caption: Painted scene of a village, depicting a herd or caravan of camels guided by riders and dogs. <NAME>, Acacus Mountains, Libya. 2013,2034.383 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3579914&partId=1&museumno=2013,2034.383&page=1 - sys: id: 2Ocb7A3ig8OOkc2AAQIEmo created_at: !ruby/object:DateTime 2015-11-26 16:12:48.147000000 Z updated_at: !ruby/object:DateTime 2018-05-17 15:12:22.249000000 Z content_type_id: image revision: 2 image: sys: id: 2xR2nZml7mQAse8CgckCa created_at: !ruby/object:DateTime 2015-11-26 16:07:51.480000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:51.480000000 Z title: '2013,2034.5117' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2xR2nZml7mQAse8CgckCa/984e95b65ebdc647949d656cb08c0fc9/2013_2034.5117.jpg" caption: Engravings of a female camel with calves. Oued Djerat, Algeria. 2013,2034.5117 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3624292&partId=1&museumno=2013,2034.5117&page=1 - sys: id: 4iTHcZ38wwSyGK8UIqY2yQ created_at: !ruby/object:DateTime 2015-11-26 16:13:13.897000000 Z updated_at: !ruby/object:DateTime 2018-05-17 15:31:09.339000000 Z content_type_id: image revision: 2 image: sys: id: 1ecCbVeHUGa2CsYoYSQ4Sm created_at: !ruby/object:DateTime 2015-11-26 16:07:34.241000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:34.241000000 Z title: Fig. 8. Painted description: url: "//images.ctfassets.net/xt8ne4gbbocd/1ecCbVeHUGa2CsYoYSQ4Sm/21b2aebd215d0691482411608ad5682f/Fig._8._Painted.jpg" caption: " Painted scene of Libyan-Berber warriors riding camels, accompanied by infantry and cavalrymen. <NAME>, Chad. 2013,2034.7295 © <NAME>/TARA" col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3655154&partId=1&searchText=2013,2034.7295&page=1 - sys: id: 2zqiJv33OUM2eEMIK2042i created_at: !ruby/object:DateTime 2015-11-26 16:21:08.068000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:21:08.068000000 Z content_type_id: chapter revision: 1 title_internal: 'Camels: thematic, chapter 6' body: |- That camels were used to transport goods is obvious, and depictions of long lines of animals are common, sometimes with saddles on which to place the packs and ropes to tie the animals together. However, if rock art depictions are some indication of camel use, it seems that until the Muslim conquest the main function of one-humped camels was as mounts, often linked to war. The Sahara desert contains dozens of astonishingly detailed images of warriors riding camels, armed with spears, long swords and shields, sometimes accompanied by infantry soldiers and horsemen. Although camels are not as good as horses for use as war mounts (they are too tall and make insecure platforms for shooting arrows), they were undoubtedly very useful in raids – the most common type of war activity in the desert – as well as being a symbol of prestige, wealth and authority among the desert warriors, much as they still are today. Moreover, the extraordinary detail of some of the rock art paintings has provided inestimable help in understanding how (and why) camels were ridden in the 1st millennium AD. Unlike horses, donkeys or mules, one-humped camels present a major problem for riders: where to put the saddle. Although it might be assumed that the saddle should be placed over the hump, they can, in fact, also be positioned behind or in front of the hump, depending on the activity. It seems that the first saddles were placed behind the hump, but that position was unsuitable for fighting, quite uncomfortable, and unstable. Subsequently, a new saddle was invented in North Arabia around the 5th century BC: a framework of wood that rested over the hump and provided a stable platform on which to ride and fight more effectively. The North Arabian saddle led to a revolution in the domestication of one-humped camels, allowed a faster expansion of the use of these animals, and it is probably still the most used type of saddle today. - sys: id: 6dOm7ewqmA6oaM4cK4cy8c created_at: !ruby/object:DateTime 2015-11-26 16:14:25.900000000 Z updated_at: !ruby/object:DateTime 2018-05-17 15:31:33.078000000 Z content_type_id: image revision: 2 image: sys: id: 5qXuQrcnUQKm0qCqoCkuGI created_at: !ruby/object:DateTime 2015-11-26 16:06:48.345000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:06:48.345000000 Z title: As1974,29.17 description: url: "//images.ctfassets.net/xt8ne4gbbocd/5qXuQrcnUQKm0qCqoCkuGI/2b279eff2a6f42121ab0f6519d694a92/As1974_29.17.jpg" caption: North Arabian-style saddle, with a wooden framework designed to be put around the hump. Jordan. British Museum As1974,29.17 © Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3320111&partId=1&object=23696&page=1 - sys: id: 5jE9BeKCBUEK8Igg8kCkUO created_at: !ruby/object:DateTime 2015-11-26 16:21:27.156000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:21:27.156000000 Z content_type_id: chapter revision: 1 title_internal: 'Camels: thematic, chapter 7' body: 'Although North Arabian saddles are found throughout North Africa and are often depicted in rock art paintings, at some point a new kind of saddle was designed in North Africa: one placed in front of the hump, with the weight over the shoulders of the camel. This type of shoulder saddle allows the rider to control the camel with the feet and legs, thus improving the ride. Moreover, the rider is seated in a lower position and thus needs shorter spears and swords that can be brandished more easily, making warriors more efficient. This new kind of saddle, which is still used throughout North Africa today, appears only in the western half of the Sahara and is well represented in the rock art of Algeria, Niger and Mauritania. And it is not only saddles that are recognizable in Saharan rock art: harnesses, reins, whips or blankets are identifiable in the paintings and show astonishing similarities to those still used today by desert peoples.' - sys: id: 6yZaDQMr1Sc0sWgOG6MGQ8 created_at: !ruby/object:DateTime 2015-11-26 16:14:46.560000000 Z updated_at: !ruby/object:DateTime 2018-05-17 15:33:25.754000000 Z content_type_id: image revision: 2 image: sys: id: 40zIycUaTuIG06mgyaE20K created_at: !ruby/object:DateTime 2015-11-26 16:07:51.466000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:51.466000000 Z title: Fig. 10. Painting description: url: "//images.ctfassets.net/xt8ne4gbbocd/40zIycUaTuIG06mgyaE20K/1736927ffb5e2fc71d1f1ab04310a73f/Fig._10._Painting.jpg" caption: Painting of rider on a one-humped camel. Note the North Arabian saddle on the hump, similar to the example from Jordan above. Terkei, Ennedi plateau, Chad. 2013,2034.6568 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3640623&partId=1&searchText=2013,2034.6568&page=1 - sys: id: 5jHyVlfWXugI2acowekUGg created_at: !ruby/object:DateTime 2015-11-26 16:15:13.926000000 Z updated_at: !ruby/object:DateTime 2018-05-17 15:36:07.603000000 Z content_type_id: image revision: 2 image: sys: id: 6EvwTsiMO4qoiIY4gGCgIK created_at: !ruby/object:DateTime 2015-11-26 16:07:34.249000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:34.249000000 Z title: '2013,2034.4471' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6EvwTsiMO4qoiIY4gGCgIK/1db47ae083ff605b9533898d9d9fb10d/2013_2034.4471.jpg" caption: Camel-rider using a North African saddle (in front of the hump), surrounded by warriors with spears and swords, with Libyan-Berber graffiti. Tin Tazarift, Tassili, Algeria. 2013,2034.4471 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3602860&partId=1&museumno=2013,2034.4471&page=1 - sys: id: 57goC8PzUs6G4UqeG0AgmW created_at: !ruby/object:DateTime 2015-11-26 16:16:51.920000000 Z updated_at: !ruby/object:DateTime 2019-02-12 02:33:53.275000000 Z content_type_id: image revision: 3 image: sys: id: 5JDO7LrdKMcSEOMEG8qsS8 created_at: !ruby/object:DateTime 2015-11-26 16:07:34.250000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:34.250000000 Z title: Fig. 12. Tuaregs description: url: "//images.ctfassets.net/xt8ne4gbbocd/5JDO7LrdKMcSEOMEG8qsS8/76cbecd637724d549db8a7a101553280/Fig._12._Tuaregs.jpg" caption: Tuaregs at <NAME>, an annual meeting of desert peoples. Note the saddles in front of the hump and the camels' harnesses, similar to the rock paintings above such as the image from Terkei. Ingal, Northern Niger. 2013,2034.10523 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3652377&partId=1&searchText=2013,2034.10523&page=1 - sys: id: 3QPr46gQP6sQWswuSA2wog created_at: !ruby/object:DateTime 2015-11-26 16:21:50.767000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:21:50.767000000 Z content_type_id: chapter revision: 1 title_internal: 'Camels: thematic, chapter 8' body: Since their introduction to the Sahara during the first centuries of the Christian era, camels have become indispensable for desert communities, providing a method of transport for people and commodities, but also for their milk, meat and hair for weaving. They allowed the improvement of wide cultural and economic networks, transforming the Sahara into a key node linking the Mediterranean Sea with Sub-Saharan Africa. A symbol of wealth and prestige, the Libyan-Berber peoples recognized camels’ importance and expressed it through paintings and engravings across the desert, leaving a wonderful document of their societies. The painted images of camel-riders crossing the desert not only have an evocative presence, they are also perfect snapshots of a history that started two thousand years ago and seems as eternal as the Sahara. - sys: id: 54fiYzKXEQw0ggSyo0mk44 created_at: !ruby/object:DateTime 2015-11-26 16:17:13.884000000 Z updated_at: !ruby/object:DateTime 2018-05-17 16:01:13.379000000 Z content_type_id: image revision: 2 image: sys: id: 3idPZkkIKAOWCiKouQ8c8i created_at: !ruby/object:DateTime 2015-11-26 16:07:34.244000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:34.244000000 Z title: Fig. 13. Camel-riders description: url: "//images.ctfassets.net/xt8ne4gbbocd/3idPZkkIKAOWCiKouQ8c8i/4527b1eebe112ef9c38da1026e7540b3/Fig._13._Camel-riders.jpg" caption: Camel-riders galloping. Butress cave, <NAME>, Chad. 2013,2034.6077 ©<NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3637992&partId=1&searchText=2013,2034.6077&page=1 - sys: id: 1ymik3z5wMUEway6omqKQy created_at: !ruby/object:DateTime 2015-11-26 16:17:32.501000000 Z updated_at: !ruby/object:DateTime 2018-05-17 16:02:41.679000000 Z content_type_id: image revision: 2 image: sys: id: 4Y85f5QkVGQiuYEaA2OSUC created_at: !ruby/object:DateTime 2015-11-26 16:07:06.194000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:06.194000000 Z title: Fig. 14. Tuareg description: url: "//images.ctfassets.net/xt8ne4gbbocd/4Y85f5QkVGQiuYEaA2OSUC/4fbca027ed170b221daefdff0ae7d754/Fig._14._Tuareg.jpg" caption: Tuareg rider galloping at the Cure Salee meeting. Ingal, northern Niger. 2013,2034.10528 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3652371&partId=1&searchText=2013,2034.10528&page=1 background_images: - sys: id: 3mhr7uvrpesmaUeI4Aiwau created_at: !ruby/object:DateTime 2015-12-07 18:13:48.396000000 Z updated_at: !ruby/object:DateTime 2015-12-07 18:13:48.396000000 Z title: CHAENP0340003 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3mhr7uvrpesmaUeI4Aiwau/65c691f09cd60bb7aa08457e18eaa624/CHAENP0340003_1_.JPG" - sys: id: BPzulf3QNqMC4Iqs4EoCG created_at: !ruby/object:DateTime 2015-12-07 18:13:31.094000000 Z updated_at: !ruby/object:DateTime 2015-12-07 18:13:31.094000000 Z title: CHAENP0340001 description: url: "//images.ctfassets.net/xt8ne4gbbocd/BPzulf3QNqMC4Iqs4EoCG/356b921099bfccf59008b69060d20d75/CHAENP0340001_1_.JPG" - sys: id: 1hw0sVC0XOUA4AsiG4AA0q created_at: !ruby/object:DateTime 2017-11-23 11:49:41.362000000 Z updated_at: !ruby/object:DateTime 2017-11-23 11:49:41.362000000 Z content_type_id: thematic revision: 1 title: 'Introduction to rock art in northern Africa ' slug: rock-art-in-northern-africa lead_image: sys: id: 1fzfpavYuGaOKaAM2ko6es created_at: !ruby/object:DateTime 2015-11-26 15:53:30.004000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:53:30.004000000 Z title: '2013,2034.3840' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1fzfpavYuGaOKaAM2ko6es/f1e27e311dca40ce58657e5e88cb8526/2013_2034.3840.jpg" chapters: - sys: id: axu12ftQUoS04AQkcSWYI created_at: !ruby/object:DateTime 2015-11-26 15:58:10.885000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:58:10.885000000 Z content_type_id: chapter revision: 1 title: title_internal: 'North Africa: regional, chapter 1' body: 'The Sahara is the largest non-polar desert in the world, covering almost 8,600,000 km² and comprising most of northern Africa, from the Red Sea to the Atlantic Ocean. Although it is considered a distinct entity, it is composed of a variety of geographical regions and environments, including sand seas, hammadas (stone deserts), seasonal watercourses, oases, mountain ranges and rocky plains. Rock art is found throughout this area, principally in the desert mountain and hill ranges, where stone ''canvas'' is abundant: the highlands of Adrar in Mauritania and Adrar des Ifoghas in Mali, the Atlas Mountains of Morocco and Algeria, the Tassili n’Ajjer and Ahaggar Mountains in Algeria, the mountainous areas of Tadrart Acacus and Messak in Libya, the Aïr Mountains of Nigeria, the Ennedi Plateau and Tibesti Mountains in Chad, the Gilf Kebir plateau of Egypt and Sudan, as well as the length of the Nile Valley.' - sys: id: 4DelCmwI7mQ4MC2WcuAskq created_at: !ruby/object:DateTime 2015-11-26 15:54:19.234000000 Z updated_at: !ruby/object:DateTime 2016-12-22 10:12:21.657000000 Z content_type_id: image revision: 2 image: sys: id: 1fzfpavYuGaOKaAM2ko6es created_at: !ruby/object:DateTime 2015-11-26 15:53:30.004000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:53:30.004000000 Z title: '2013,2034.3840' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1fzfpavYuGaOKaAM2ko6es/f1e27e311dca40ce58657e5e88cb8526/2013_2034.3840.jpg" caption: Bubalus Period engraving. Pelorovis Antiquus, Wadi Mathendous, Libya. 2013,2034.3840 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3593438&partId=1&images=true&people=197356&museumno=2013,2034.3840&page=1 - sys: id: 2XmfdPdXW0Y4cy6k4O4caO created_at: !ruby/object:DateTime 2015-11-26 15:58:31.891000000 Z updated_at: !ruby/object:DateTime 2016-10-17 13:40:03.509000000 Z content_type_id: chapter revision: 3 title: Types of rock art and distribution title_internal: 'North Africa: regional, chapter 2' body: |+ Although the styles and subjects of north African rock art vary, there are commonalities: images are most often figurative and frequently depict animals, both wild and domestic. There are also many images of human figures, sometimes with accessories such as recognisable weaponry or clothing. These may be painted or engraved, with frequent occurrences of both, at times in the same context. Engravings are generally more common, although this may simply be a preservation bias due to their greater durability. The physical context of rock art sites varies depending on geographical and topographical factors – for example, Moroccan rock engravings are often found on open rocky outcrops, while Tunisia’s Djebibina rock art sites have all been found in rock shelters. Rock art in the vast and harsh environments of the Sahara is often inaccessible and hard to find, and there is probably a great deal of rock art that is yet to be seen by archaeologists; what is known has mostly been documented within the last century. - sys: id: 2HqgiB8BAkqGi4uwao68Ci created_at: !ruby/object:DateTime 2016-10-17 13:41:30.844000000 Z updated_at: !ruby/object:DateTime 2016-10-17 13:41:30.844000000 Z content_type_id: chapter revision: 1 title: History of research title_internal: 'North Africa: regional chapter 2.5' body: Although the existence of rock art throughout the Sahara was known to local communities, it was not until the nineteenth century that it became known to Europeans, thanks to explorers such as <NAME>, who crossed the Messak Plateau in Libya in 1850, first noting the existence of engravings. Further explorations in the early twentieth century by celebrated travellers, ethnographers and archaeologists such as <NAME>, <NAME>, László Almásy, <NAME> and <NAME> brought the rock art of Sahara, and northern Africa in general, to the awareness of a European public. - sys: id: 5I9fUCNjB668UygkSQcCeK created_at: !ruby/object:DateTime 2015-11-26 15:54:54.847000000 Z updated_at: !ruby/object:DateTime 2016-12-22 10:13:53.921000000 Z content_type_id: image revision: 2 image: sys: id: 2N4uhoeNLOceqqIsEM6iCC created_at: !ruby/object:DateTime 2015-11-26 15:53:37.250000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:53:37.250000000 Z title: '2013,2034.1424' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2N4uhoeNLOceqqIsEM6iCC/240a45012afba4ff5508633fcaea3462/2013_2034.1424.jpg" caption: Pastoral Period painting, cattle and human figure. Tin Taborak, Acacus Mountains, Libya. 2013,2034.1424 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3592663 - sys: id: 5OkqapzKtqEcomSucG0EoQ created_at: !ruby/object:DateTime 2015-11-26 15:58:52.432000000 Z updated_at: !ruby/object:DateTime 2016-10-17 13:45:37.885000000 Z content_type_id: chapter revision: 4 title: Attribution and dating title_internal: 'North Africa: regional, chapter 3' body: 'The investigations of these researchers and those who have followed them have sought to date and attribute these artworks, with varying measures of success. Rock art may be associated with certain cultures through known parallels with the imagery in other artefacts, such as Naqada Period designs in Egyptian rock art that mirror those on dateable pottery. Authorship may be also guessed at through corroborating evidence: for example, due to knowledge of their chariot use, and the location of rock art depicting chariots in the central Sahara, it has been suggested that it was produced by – or at the same time as – the height of the Garamantes culture, a historical ethnic group who formed a local power around what is now southern Libya from 500 BC–700 AD. However, opportunities to anchor rock art imagery in this way to known ancient cultures are few and far between, and rock art is generally ascribed to anonymous hunter-gatherers, nomadic peoples, or pastoralists, with occasional imagery-based comparisons made with contemporary groups, such as the Fulani peoples.' - sys: id: 2KmaZb90L6qoEAK46o46uK created_at: !ruby/object:DateTime 2015-11-26 15:55:22.104000000 Z updated_at: !ruby/object:DateTime 2016-12-22 10:16:53.318000000 Z content_type_id: image revision: 2 image: sys: id: 5A1AwRfu9yM8mQ8EeOeI2I created_at: !ruby/object:DateTime 2015-11-26 15:53:37.288000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:53:37.288000000 Z title: '2013,2034.1152' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5A1AwRfu9yM8mQ8EeOeI2I/cac0592abfe1b31d7cf7f589355a216e/2013_2034.1152.jpg" caption: Round Head Period painting, human figures. <NAME>, Acacus Mountains, Libya. 2013,2034.1152 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3592099&partId=1&images=true&people=197356&page=1 - sys: id: 27ticyFfocuOIGwioIWWYA created_at: !ruby/object:DateTime 2015-11-26 15:59:26.852000000 Z updated_at: !ruby/object:DateTime 2016-10-17 15:18:29.234000000 Z content_type_id: chapter revision: 2 title_internal: 'North Africa: regional, chapter 4' body: |- Occasionally, association with writing in the form of, for example, Libyan-Berber or Arabic graffiti can give a known dating margin, but in general, lack of contemporary writing and written sources (Herodotus wrote about the Garamantes) leaves much open to conjecture. Other forms of (rare) circumstantial evidence, such as rock art covered by a dateable stratigraphic layer, and (more common) stylistic image-based dating have been used instead to form a chronology of Saharan rock art periods that is widely agreed upon, although dates are contested. The first stage, known as the Early Hunter, Wild Fauna or Bubalus Period, is posited at about 12,000–6,000 years ago, and is typified by naturalistic engravings of wild animals, in particular an extinct form of buffalo identifiable by its long horns. - sys: id: q472iFYzIsWgqWG2esg28 created_at: !ruby/object:DateTime 2015-11-26 15:55:58.985000000 Z updated_at: !ruby/object:DateTime 2016-12-22 10:19:11.991000000 Z content_type_id: image revision: 2 image: sys: id: 1YAVmJPnZ2QQiguCQsgOUi created_at: !ruby/object:DateTime 2015-11-26 15:53:29.989000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:53:29.989000000 Z title: '2013,2034.4570' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1YAVmJPnZ2QQiguCQsgOUi/4080b87891cb255e12a17216d7e71286/2013_2034.4570.jpg" caption: Horse Period painting, charioteer and standing horses. <NAME>, <NAME>, Algeria. 2013,2034.4570 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3603794 - sys: id: 7tsWGNvkQgACuKEMmC0uwG created_at: !ruby/object:DateTime 2015-11-26 15:59:47.880000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:59:47.880000000 Z content_type_id: chapter revision: 1 title_internal: 'North Africa: regional, chapter 5' body: A possibly concurrent phase is known as the Round Head Period (about 10,000 to 8,000 years ago) due to the large discoid heads of the painted human figures. Following this is the most widespread style, the Pastoral Period (around 7,500 to 4,000 years ago), which is characterised by numerous paintings and engravings of cows, as well as occasional hunting scenes. The Horse Period (around 3,000 to 2,000 years ago) features recognisable horses and chariots and the final Camel Period (around 2,000 years ago to present) features domestic dromedary camels, which we know to have been widely used across the Sahara from that time. - sys: id: 13V2nQ2cVoaGiGaUwWiQAC created_at: !ruby/object:DateTime 2015-11-26 15:56:25.598000000 Z updated_at: !ruby/object:DateTime 2016-12-22 10:39:22.861000000 Z content_type_id: image revision: 2 image: sys: id: 6MOI9r5tV6Gkae0CEiQ2oQ created_at: !ruby/object:DateTime 2015-11-26 15:53:29.964000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:53:29.964000000 Z title: 2013,2034.1424 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6MOI9r5tV6Gkae0CEiQ2oQ/bad4ec8dd7c6ae553d623e4238641561/2013_2034.1424_1.jpg" caption: Camel engraving. <NAME>, <NAME>, Sudan. 2013,2034.335 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3586831 - sys: id: 3A64bY4VeMGkKCsGCGwu4a created_at: !ruby/object:DateTime 2015-11-26 16:00:04.267000000 Z updated_at: !ruby/object:DateTime 2016-10-17 15:30:04.896000000 Z content_type_id: chapter revision: 2 title_internal: 'North Africa: regional, chapter 6' body: "While this chronology serves as a useful framework, it must be remembered that the area – and the time period in which rock art was produced – is extensive and there is significant temporal and spatial variability within and across sites. There are some commonalities in rock art styles and themes across the Sahara, but there are also regional variations and idiosyncrasies, and a lack of evidence that any of these were directly, or even indirectly, related. The engravings of weaponry motifs from Morocco and the painted ‘swimming’ figures of the Gilf Kebir Plateau in Egypt and Sudan are not only completely different, but unique to their areas. Being thousands of kilometres apart and so different in style and composition, they serve to illustrate the limitations inherent in examining northern African rock art as a unit. The contemporary political and environmental challenges to accessing rock art sites in countries across the Sahara serves as another limiting factor in their study, but as dating techniques improve and further discoveries are made, this is a field with the potential to help illuminate much of the prehistory of northern Africa.\n\n" citations: - sys: id: 4AWHcnuAVOAkkW0GcaK6We created_at: !ruby/object:DateTime 2016-10-17 15:15:38.284000000 Z updated_at: !ruby/object:DateTime 2016-10-17 15:15:38.284000000 Z content_type_id: citation revision: 1 citation_line: | <NAME>. 1998. Art rupestre et préhistoire du Sahara: le Messak Libyen. Paris: Payot & Rivages <NAME>. 1995. Les images rupestres du Sahara. — Toulouse (author’s ed.), p. 447 <NAME>. 2001. Saharan Africa in (ed) <NAME>, Handbook of Rock Art Research, pp 605-636. AltaMira Press, Walnut Creek <NAME>. 2013. Dating the rock art of Wadi Sura, in Wadi Sura – The Cave of Beasts, Kuper, R. (ed). Africa Praehistorica 26 – Köln: Heinrich-Barth-Institut, pp. 38-39 Rodrigue, A. 1999. L'art rupestre du Haut Atlas Marocain. Paris, L'Harmattan Soukopova, J. 2012. Round Heads: The Earliest Rock Paintings in the Sahara. Newcastle upon Tyne: Cambridge Scholars Publishing <NAME>. 1993. Préhistoire de la Mauritanie. Centre Culturel Français A. de Saint Exupéry-Sépia, Nouakchott background_images: - sys: id: 3ZTCdLVejemGiCIWMqa8i created_at: !ruby/object:DateTime 2015-12-07 19:41:46.025000000 Z updated_at: !ruby/object:DateTime 2015-12-07 19:41:46.025000000 Z title: EAF135068 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3ZTCdLVejemGiCIWMqa8i/5a0d13fdd2150f0ff81a63afadd4258e/EAF135068.jpg" - sys: id: 2jvgN3MMfqoAW6GgO8wGWo created_at: !ruby/object:DateTime 2015-12-07 19:41:50.029000000 Z updated_at: !ruby/object:DateTime 2015-12-07 19:41:50.029000000 Z title: EAF131007 description: url: "//images.ctfassets.net/xt8ne4gbbocd/2jvgN3MMfqoAW6GgO8wGWo/393c91068f4dc0ca540c35a79b965288/EAF131007.jpg" country_introduction: sys: id: 3HkyZVGe2suiyEMe6ICs4U created_at: !ruby/object:DateTime 2015-11-26 10:45:19.662000000 Z updated_at: !ruby/object:DateTime 2015-12-07 13:42:03.255000000 Z content_type_id: country_information revision: 2 title: 'Egypt: country introduction' chapters: - sys: id: 1RtA0G7m6ok8cOWi20EC2s created_at: !ruby/object:DateTime 2015-11-26 10:37:46.214000000 Z updated_at: !ruby/object:DateTime 2017-01-09 15:05:57.139000000 Z content_type_id: chapter revision: 3 title: Introduction title_internal: 'Egypt: country, chapter 1' body: The rock art of Egypt was largely unknown outside of the region until the beginning of the 20th century. The rock paintings and engravings of Egypt feature a range of subjects and styles, including domestic cattle, wild animals, humans, boat images and inscriptions. Much of the rock art appears to date from within the last 8,000 years. However, earlier Palaeolithic engravings have also been found near the Nile, suggesting a longer time frame for the practice. The majority of Egypt’s most famous rock art, including the ‘Cave of Swimmers’, is found in the desert in the far south-west of the country. - sys: id: JXxIothd6gke6u68aMS2k created_at: !ruby/object:DateTime 2015-11-26 10:33:39.571000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:30:48.038000000 Z content_type_id: image revision: 4 image: sys: id: 4yqh628H2wae4Mwe6MQGWa created_at: !ruby/object:DateTime 2015-11-26 10:33:01.324000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:30:00.913000000 Z title: '2013,2034.25' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3577780&partId=1&images=true&people=197356&place=42209&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/4yqh628H2wae4Mwe6MQGWa/41dcae1c01f69ace28bccc26fd712c6f/2013_2034.5277.jpg" caption: Painted human figures and cows on rock shelter roof. <NAME>, Jebel Uweinat, Egypt. 2013,2034.25© TARA/<NAME> col_link: http://bit.ly/2iVMFd0 - sys: id: 3Cs9Muna1qeMOCAUyCCuQm created_at: !ruby/object:DateTime 2015-11-26 10:38:16.091000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:38:16.091000000 Z content_type_id: chapter revision: 1 title: Geography title_internal: 'Egypt: country, chapter 2' body: Egypt covers about 996,000km² at Africa’s north-east corner and until the creation of the Suez Canal in 1869, contained Africa’s only direct physical connection to Eurasia. The country’s most prominent geographical feature, the river Nile, flows from the highlands of Ethiopia and Central Africa into the Mediterranean, dividing the eastern portion of the Sahara into the Western and Eastern Deserts, with the Sinai Peninsula to the east. - sys: id: 7IH4mS5LW0cSGcgEaa6ESO created_at: !ruby/object:DateTime 2015-11-26 10:38:54.278000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:38:54.278000000 Z content_type_id: chapter revision: 1 title: Research history title_internal: 'Egypt: country, chapter 3' body: |- The presence of rock art in Egypt has been noticed by European scholars since the early 19th century. Geographically isolated from the bulk of rock art in the country, the paintings and engravings of Gilf Kebir and Jebel Uweinat were first catalogued in the 1920s by the Egyptian explorers and public figures <NAME> and <NAME>, and thereafter by renowned early twentieth century explorers and ethnographers such as <NAME>, <NAME>, <NAME> and <NAME>, whose expeditions helped bring Saharan rock art into wider public consciousness. Hans Winkler’s seminal *Rock Drawings of Southern Upper Egypt* (1938-9) was one of the first regional catalogues and remains a pre-eminent review of finds. Further cataloguing of rock art images and sites in the southern Nile valley took place at the time of the construction of the Aswan High Dam in the 1960s. Where rock art historically was part of larger archaeological research in the area, in recent years it has been subject to more direct and rigorous study which will contribute to a better understanding of chronologies and relationships. - sys: id: 3CzPFWoTFeIMaCsMgSy0sg created_at: !ruby/object:DateTime 2015-11-26 10:39:46.908000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:44:29.300000000 Z content_type_id: chapter revision: 2 title: Themes title_internal: 'Egypt: country, chapter 4' body: In desert areas, recognisably stylised Pharaonic-period inscriptions and engravings from between 3,100 and 30 BC can be found on rock faces, particularly at oases and quarry sites such as Kharga Oasis and Wadi Hammamat in the Western and Eastern deserts. There is also rock art from later periods like that at Matna el-Barqa in the Western Desert hinterland, where both Pharaonic and later Coptic inscriptions mix with images of gods and horsemen. Earlier examples of engraved rock art may be found in the Nile valley, in what is now southern Egypt and northern Sudan, linked to progenitors of ancient Egyptian cultures, most particularly the people of the Naqada Periods (4,000-3,100 BC). This art is characterised by frequent depictions on pottery of river boats, which occur in much of the rock art near the Nile, and include, pecked on a boulder at Nag el-Hamdulab near Aswan, what is considered the first known depiction of a Pharaoh, on just such a boat. Also prevalent in these areas are numerous engravings of animals and human figures. - sys: id: 2YNlS4f9ZuswQuwKQmIEkU created_at: !ruby/object:DateTime 2015-11-26 10:34:25.538000000 Z updated_at: !ruby/object:DateTime 2017-01-09 15:09:37.165000000 Z content_type_id: image revision: 2 image: sys: id: 3MIwpw8kAMIuGukggC2mUo created_at: !ruby/object:DateTime 2015-11-26 10:33:01.309000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:33:01.309000000 Z title: '2013,2034.108' description: url: "//images.ctfassets.net/xt8ne4gbbocd/3MIwpw8kAMIuGukggC2mUo/a296d679fd2c30c9a1fec354b5028ef9/2013_2034.108.jpg" caption: Engraved antelope and lion pugmarks on cave wall. Wadi el-Obeiyd, Farafra Oasis, Western Desert. 2013,2034.108 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3577697&partId=1&images=true&people=197356&place=42209&page=2 - sys: id: 4jirnWi9nqW0e44wqkOwMi created_at: !ruby/object:DateTime 2015-11-26 10:40:02.893000000 Z updated_at: !ruby/object:DateTime 2017-01-09 15:07:08.214000000 Z content_type_id: chapter revision: 2 title_internal: 'Egypt: country, chapter 5' body: Possible links between ancient Egyptian culture and wider Saharan rock art traditions have been discussed since the rock art of northern Africa first met European academic attention in the early 20th century. Although the arid Western Desert appears to have been a significant barrier, relations remain unclear. - sys: id: 69gKt6UfRuqKcSuCWUYOkc created_at: !ruby/object:DateTime 2015-11-26 10:40:26.215000000 Z updated_at: !ruby/object:DateTime 2017-01-09 15:21:14.317000000 Z content_type_id: chapter revision: 2 title: Chronology title_internal: 'Egypt: country, chapter 6' body: Certainly, not all rock art found in Egypt has direct links to Pharaonic cultures. Recently, the rock art at Qurta, south of Edfu, of naturalistic outline engravings of ancient aurochs (ancestors of domestic cattle), were dated reliably to the Palaeolithic Period, between 16,000 and 15,000 years ago, making them the oldest known rock art in northern Africa. Between the eighth and fourth millennia BC, Egypt’s climate was generally temperate, interrupted only briefly by dry spells, until the increasing aridity thereafter concentrated life in the Eastern Sahara around the river’s banks. - sys: id: 6JMuLUburS0sqo4aGIgq4e created_at: !ruby/object:DateTime 2015-11-26 10:35:03.483000000 Z updated_at: !ruby/object:DateTime 2017-01-09 15:21:43.897000000 Z content_type_id: image revision: 2 image: sys: id: 1BqBCPqhDiiM0qqeM6Eeie created_at: !ruby/object:DateTime 2015-11-26 10:33:01.325000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:33:01.325000000 Z title: '2013,2034.126' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1BqBCPqhDiiM0qqeM6Eeie/cc9f8eabaf32202035c94c9e7d444bb2/2013_2034.126.jpg" caption: Hand prints, blown pigment on cave wall. <NAME>, Farafra Oasis, Western Desert. 2013,2034.126 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3577677&partId=1&images=true&people=197356&place=42209&page=1 - sys: id: 68oUY9MIOA82MUu0SUuYIU created_at: !ruby/object:DateTime 2015-11-26 10:40:44.511000000 Z updated_at: !ruby/object:DateTime 2016-07-22 19:36:46.175000000 Z content_type_id: chapter revision: 2 title_internal: 'Egypt: country, chapter 7' body: This development fostered both ancient Egyptian culture and isolated populations of animals elsewhere driven out of their environments by encroaching desert, some of which, like crocodiles, are represented in the rock engravings found along the alluvial plains. Engravings of wild fauna continue to be uncovered, such as that recently found near the Farafra Oasis, with depictions of giraffe and antelope scratched into the rock face. In a cave nearby, alongside engraved lion paw prints, are blown-pigment negative paintings of human hands. - sys: id: 5iFCF3Y5AsMoKE8mqa2gMK created_at: !ruby/object:DateTime 2015-11-26 10:35:44.393000000 Z updated_at: !ruby/object:DateTime 2017-01-09 15:28:38.595000000 Z content_type_id: image revision: 2 image: sys: id: 2eE8VylT2ocoEoAQ22m2Qq created_at: !ruby/object:DateTime 2015-11-26 10:33:01.349000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:33:01.349000000 Z title: '2013,2034.4' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2eE8VylT2ocoEoAQ22m2Qq/3a8fa3faf5eb2287751d90b451c1090c/2013_2034.4.jpg" caption: Engraved cattle. <NAME>, Jebel Uweinat. 2013,2034.4 © TARA/David Coulson col_link: http://bit.ly/2iW0oAD - sys: id: 4lif35hFsIWGGeYmQIK2Sc created_at: !ruby/object:DateTime 2015-11-26 10:41:00.987000000 Z updated_at: !ruby/object:DateTime 2017-01-09 15:30:05.093000000 Z content_type_id: chapter revision: 2 title_internal: 'Egypt: country, chapter 8' body: Some of Egypt’s most striking and famous rock art is found far from the Nile at Gilf Kebir, a vast sandstone plateau in the desert near the Libyan border. As elsewhere in the Sahara, there are frequent depictions of domestic cattle, people and wild animals. Like most rock art, the paintings and engravings here are hard to date accurately but may refer to the ‘Bovidian Period’ (Pastoral Period) rock art of the wider Sahara, typified by paintings and engravings of cattle and people (Huyge, 2009). However, the scholarly community recognises the inherent difficulty of formulating conclusions of direct links with wider rock art practices. Some evidence of pastoralists in the area means that this rock art could have been made as early as the fifth millennium BC and are thus possibly contemporaneous with Predynastic Egyptian cultures, but not necessarily connected (Riemer, 2013). - sys: id: 3MnIkobDNSIWoYeec8QmsI created_at: !ruby/object:DateTime 2015-11-26 10:41:27.078000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:41:27.078000000 Z content_type_id: chapter revision: 1 title: Interpretation title_internal: 'Egypt: country, chapter 9' body: The motivation behind producing these images remains elusive. Where a particular cosmology is better known, it can be speculated, such as the Nile boat paintings have been suggested to evoke funerary beliefs and practices. If nothing else, the cattle paintings of Gilf Kebir demonstrate the importance of cattle in the pastoralist culture that produced them. Despite still being relatively little known, the ‘mystique’ behind rock art has cultivated popular curiosity, in particular in Gilf Kebir’s famous ‘Cave of Swimmers’. This is a shallow rock shelter featuring many painted human figures in strange contortions, as if swimming – images which have captured the popular imagination, with their glimpse of life in Egypt millennia before the Pharaohs and their hints at a watery Sahara. - sys: id: 3Wc0ODJNxmUc86aiSCseWM created_at: !ruby/object:DateTime 2015-11-26 10:36:22.741000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:36:22.741000000 Z content_type_id: image revision: 1 image: sys: id: 2QN2xRgnrOcQKsIM224CYY created_at: !ruby/object:DateTime 2015-11-26 10:33:01.324000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:33:01.324000000 Z title: '2013,2034.212' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2QN2xRgnrOcQKsIM224CYY/6444f91f912b086def593035a40f987b/2013_2034.212.jpg" caption: Painted human and cattle figures, <NAME>, <NAME>. 2013,2034.212 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3577589&partId=1 citations: - sys: id: 6D5UoHwwO4sg8gmUA8ikWs created_at: !ruby/object:DateTime 2015-11-26 10:37:10.022000000 Z updated_at: !ruby/object:DateTime 2016-07-22 19:38:21.856000000 Z content_type_id: citation revision: 2 citation_line: |+ <NAME>. 2009, *Rock Art*. In Willeke Wendrich (ed.), UCLA Encyclopedia of Egyptology, Los Angeles, p. 4 <NAME>. 2013. *Dating the rock art of Wadi Sura, in Wadi Sura – The Cave of Beasts*, <NAME>. (ed). Africa Praehistorica 26 – Köln: Heinrich-Barth-Institut, pp. 38-39 background_images: - sys: id: 5LebP1Vcqs4A4US00uI0Q4 created_at: !ruby/object:DateTime 2015-11-25 15:00:35.480000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:00:35.480000000 Z title: '2013,2034.186' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5LebP1Vcqs4A4US00uI0Q4/56ba762bb737baf4545dc62a6a745bb3/2013_2034.186.jpg" - sys: id: 6pW55O6bPUgA868iaymU0S created_at: !ruby/object:DateTime 2015-11-30 13:34:19.613000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:26:45.965000000 Z title: '2013,2034.212' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3577589&partId=1&searchText=2013,2034.212&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/6pW55O6bPUgA868iaymU0S/d444187808f12cb5ba8fdf0223aca94c/2013_2034.212_1.jpg" - sys: id: 1DmPc4SXTi2qQiYW6mKK62 created_at: !ruby/object:DateTime 2015-11-30 13:34:19.597000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:31:31.555000000 Z title: '2013,2034.25' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3577780&partId=1&images=true&people=197356&place=42209&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/1DmPc4SXTi2qQiYW6mKK62/412e8b744a4af417ad873768aad220f6/2013_2034.5277_1.jpg" region: Northern / Saharan Africa ---<file_sep>/_coll_thematic/geometric-motifs.md --- contentful: sys: id: 6h9anIEQRGmu8ASywMeqwc created_at: !ruby/object:DateTime 2015-11-25 17:07:20.920000000 Z updated_at: !ruby/object:DateTime 2015-12-07 20:49:54.244000000 Z content_type_id: thematic revision: 4 title: Geometric motifs and cattle brands slug: geometric-motifs lead_image: sys: id: 5yD7fOuAdU4cemkewCqCMO created_at: !ruby/object:DateTime 2015-11-25 16:56:44.778000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:56:44.778000000 Z title: '2013,2034.12976' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5yD7fOuAdU4cemkewCqCMO/4d203afb0318bee69decb23327864c79/2013_2034.12976.jpg" chapters: - sys: id: 5plObOxqdq6MuC0k4YkCQ8 created_at: !ruby/object:DateTime 2015-11-25 17:02:35.234000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:05:34.964000000 Z content_type_id: chapter revision: 3 title_internal: 'Geometric motifs: thematic, chapter 1' body: |- The rock art of eastern Africa is characterised by a wide range of non-figurative images, broadly defined as geometric. Occurring in a number of different patterns or designs, they are thought to have been in existence in this region for thousands of years, although often it is difficult to attribute the art to particular cultural groups. Geometric rock art is difficult to interpret, and designs have been variously associated with sympathetic magic, symbols of climate or fertility and altered states of consciousness (Coulson and Campbell, 2010:220). However, in some cases the motifs painted or engraved on the rock face resemble the same designs used for branding livestock and are intimately related to people’s lives and world views in this region. First observed in Kenya in the 1970s with the work of Gramly (1975) at <NAME> and Lynch and Robbins (1977) at Namoratung’a, some geometric motifs seen in the rock art of the region were observed to have had their counterparts on the hides of cattle of local communities. Although cattle branding is known to be practised by several Kenyan groups, Gramly concluded that “drawing cattle brands on the walls of rock shelters appears to be confined to the regions formerly inhabited by the Maa-speaking pastoralists or presently occupied by them”&dagger;(Gramly, 1977:117). - sys: id: 71cjHu2xrOC8O6IwSmMSS2 created_at: !ruby/object:DateTime 2015-11-25 16:57:39.559000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:06:07.592000000 Z content_type_id: image revision: 2 image: sys: id: 5yD7fOuAdU4cemkewCqCMO created_at: !ruby/object:DateTime 2015-11-25 16:56:44.778000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:56:44.778000000 Z title: '2013,2034.12976' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5yD7fOuAdU4cemkewCqCMO/4d203afb0318bee69decb23327864c79/2013_2034.12976.jpg" caption: White symbolic designs possibly representing Maa clans and livestock brands, Laikipia, Kenya. 2013,2034.12976 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3693276&partId=1&searchText=2013,2034.12976&page=1 - sys: id: 36QhSWVHKgOeMQmSMcGeWs created_at: !ruby/object:DateTime 2015-11-25 17:03:05.920000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:03:05.920000000 Z content_type_id: chapter revision: 1 title: title_internal: 'Geometric motifs: thematic, chapter 2' body: In the case of Lukenya Hill, the rock shelters on whose walls these geometric symbols occur are associated with meat-feasting ceremonies. Meat-feasting shelters exist from northern Tanzania through Kenya to Lake Turkana, and are places where Maa-speaking initiated men, who are not permitted to eat meat in their homes, gather to kill and feast on animals, predominantly cattle. During or after feasting, symbols of the animals that had been eaten were painted on the shelter ceiling in white or less often red. Maa speakers brand their cattle and camels with symbols that signify the lineage of their owners, but may also indicate if an animal has been treated for a particular disease. Different symbols may be used for male and female animals. - sys: id: 4t76LZy5zaSMGM4cUAsYOq created_at: !ruby/object:DateTime 2015-11-25 16:58:35.447000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:07:35.181000000 Z content_type_id: image revision: 2 image: sys: id: 1lBqQePHxK2Iw8wW8S8Ygw created_at: !ruby/object:DateTime 2015-11-25 16:56:44.764000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:56:44.764000000 Z title: '2013,2034.12846' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1lBqQePHxK2Iw8wW8S8Ygw/68fffb37b845614214e96ce78879c0b0/2013_2034.12846.jpg" caption: View of the long rock shelter below the waterfall showing white abstract Maasai paintings made probably quite recently during meat feasting ceremonies, Enkinyoi, Kenya. 2013,2034.12846 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3694558&partId=1&searchText=2013,2034.12846&page=1 - sys: id: 3HGWtlhoS424kQCMo6soOe created_at: !ruby/object:DateTime 2015-11-25 17:03:28.158000000 Z updated_at: !ruby/object:DateTime 2016-05-19 07:35:38.155000000 Z content_type_id: chapter revision: 2 title_internal: 'Geometric motifs: thematic, chapter 3' body: The sites of Namoratung’a near Lake Turkana in northern Kenya showed a similar visible relationship. The southernmost site is well known for its 167 megalithic stones marking male burials on which are engraved hundreds of geometric motifs. Some of these motifs bear a striking resemblance to the brand marks that the Turkana mark on their cattle, camels, donkeys and other livestock in the area, although local people claim no authorship for the funerary engravings (Russell, 2013:4). - sys: id: kgoyTkeS0oQIoaOaaWwwm created_at: !ruby/object:DateTime 2015-11-25 16:59:05.484000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:08:12.169000000 Z content_type_id: image revision: 2 image: sys: id: 19lqDiCw7UOomiMmYagQmq created_at: !ruby/object:DateTime 2015-11-25 16:56:44.756000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:56:44.756000000 Z title: '2013,2034.13006' description: url: "//images.ctfassets.net/xt8ne4gbbocd/19lqDiCw7UOomiMmYagQmq/6f54d106aaec53ed9a055dc7bf3ac014/2013_2034.13006.jpg" caption: Ndorobo man with bow and quiver of arrows kneels at a rock shelter adorned with white symbolic paintings suggesting meat-feasting rituals. Laikipia, Kenya. 2013,2034.13006 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3700172&partId=1&searchText=2013,2034.13006&page=1 - sys: id: 2JZ8EjHqi4U8kWae8oEOEw created_at: !ruby/object:DateTime 2015-11-25 17:03:56.190000000 Z updated_at: !ruby/object:DateTime 2016-05-19 07:35:15.319000000 Z content_type_id: chapter revision: 2 title_internal: 'Geometric motifs: thematic, chapter 4' body: Recent research (Russell, 2013) has shown that at Namoratung’a the branding of animals signifies a sense of belonging rather than a mark of ownership as we understand it in a modern farming context; all livestock, cattle, camel, goats, sheep and donkeys are branded according to species and sex (Russell, 2013:7). Ethnographic accounts document that clan membership can only be determined by observing someone with their livestock (Russell, 2013:9). The symbol itself is not as important as the act of placing it on the animal’s skin, and local people have confirmed that they never mark rock with brand marks. Thus, the geometric motifs on the grave markers may have been borrowed by local Turkana to serve as identity markers, but in a different context. In the Horn of Africa, some geometric rock art is located in the open landscape and on graves. It has been suggested that these too are brand or clan marks, possibly made by camel keeping pastoralists to mark achievement, territory or ownership (Russell, 2013:18). Some nomadic pastoralists, further afield, such as the Tuareg, place their clan marks along the routes they travel, carved onto salt blocks, trees and wells (Mohamed, 1990; Landais, 2001). - sys: id: 3sW37nPBleC8WSwA8SEEQM created_at: !ruby/object:DateTime 2015-11-25 16:59:47.649000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:59:47.649000000 Z content_type_id: image revision: 1 image: sys: id: 5yUlpG85GMuW2IiMeYCgyy created_at: !ruby/object:DateTime 2015-11-25 16:56:44.766000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:56:44.766000000 Z title: '2013,2034.13451' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5yUlpG85GMuW2IiMeYCgyy/a234f96f9931ec3fdddcf1ab54a33cd9/2013_2034.13451.jpg" caption: Borana cattle brands. Namoratung’a, Kenya. 2013,2034.13451. © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3660359&partId=1&searchText=2013,2034.13451&page=1 - sys: id: 6zBkbWkTaEoMAugoiuAwuK created_at: !ruby/object:DateTime 2015-11-25 17:04:38.446000000 Z updated_at: !ruby/object:DateTime 2016-05-19 07:34:17.646000000 Z content_type_id: chapter revision: 3 title_internal: 'Geometric motifs: thematic, chapter 5' body: "However, not all pastoralist geometric motifs can be associated with meat-feasting or livestock branding; they may have wider symbolism or be symbolic of something else (Russell, 2013:17). For example, informants from the Samburu people reported that while some of the painted motifs found at Samburu meat-feasting shelters were of cattle brands, others represented female headdresses or were made to mark an initiation, and in some Masai shelters there are also clear representations of warriors’ shields. In Uganda, a ceremonial rock in Karamoja, shows a dung painting consisting of large circles bisected by a cross which is said to represent cattle enclosures (Robbins, 1972). Geometric symbols, painted in fat and red ochre, on large phallic-shaped fertility stones on the Mesakin and Korongo Hills in south Sudan indicate the sex of the child to whom prayers are offered (Bell, 1936). A circle bisected by a line or circles bisected by two crosses represent boys. Girls are represented by a cross (drawn diagonally) or a slanting line (like a forward slash)(Russell, 2013: 17).\n\nAlthough pastoralist geometric motifs are widespread in the rock art of eastern Africa, attempting to find the meaning behind geometric designs is problematic. The examples discussed here demonstrate that motifs can have multiple authors, even in the same location, and that identical symbols can be the products of very different behaviours. \n" citations: - sys: id: 2oNK384LbeCqEuSIWWSGwc created_at: !ruby/object:DateTime 2015-11-25 17:01:10.748000000 Z updated_at: !ruby/object:DateTime 2016-05-19 07:33:26.748000000 Z content_type_id: citation revision: 3 citation_line: |- <NAME>. 1936. ‘Nuba fertility stones’, in *Sudan Notes and Records* 19(2), pp.313–314. Gramly R 1975. ‘Meat-feasting sites and cattle brands: Patterns of rock-shelter utilization in East Africa’ in *Azania*, 10, pp.107–121. <NAME>. 2001. ‘The marking of livestock in traditional pastoral societies’, *Scientific and Technical Review of the Office International des Epizooties* (Paris), 20 (2), pp.463–479. <NAME>. and <NAME>. 1977. ‘Animal brands and the interpretation of rock art in East Africa’ in *Current Anthropology *18, pp.538–539. Robbins LH (1972) Archaeology in the Turkana district, Kenya. Science 176(4033): 359–366 <NAME>. 2013. ‘Through the skin: exploring pastoralist marks and their meanings to understand parts of East African rock art’, in *Journal of Social Archaeology* 13:1, pp.3-30 &dagger; The term Maa relates to a group of closely related Eastern Nilotic languages, which historically dominated the east African hinterland; and today is spoken by around a million people. background_images: - sys: id: 1TDQd4TutiKwIAE8mOkYEU created_at: !ruby/object:DateTime 2015-12-07 19:16:42.825000000 Z updated_at: !ruby/object:DateTime 2015-12-07 19:16:42.825000000 Z title: KENLOK0030053 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1TDQd4TutiKwIAE8mOkYEU/718ff84615930ddafb1f1fdc67b5e479/KENLOK0030053.JPG" - sys: id: 2SCvEkDjAcIewkiu6iSGC4 created_at: !ruby/object:DateTime 2015-12-07 19:16:42.845000000 Z updated_at: !ruby/object:DateTime 2015-12-07 19:16:42.845000000 Z title: KENKAJ0030008 description: url: "//images.ctfassets.net/xt8ne4gbbocd/2SCvEkDjAcIewkiu6iSGC4/b2e2e928e5d9a6a25aca5c99058dfd76/KENKAJ0030008.jpg" ---<file_sep>/_coll_thematic/rock-art-in-northern-africa.md --- contentful: sys: id: 1hw0sVC0XOUA4AsiG4AA0q created_at: !ruby/object:DateTime 2017-11-23 11:49:41.362000000 Z updated_at: !ruby/object:DateTime 2017-11-23 11:49:41.362000000 Z content_type_id: thematic revision: 1 title: 'Introduction to rock art in northern Africa ' slug: rock-art-in-northern-africa lead_image: sys: id: 1fzfpavYuGaOKaAM2ko6es created_at: !ruby/object:DateTime 2015-11-26 15:53:30.004000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:53:30.004000000 Z title: '2013,2034.3840' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1fzfpavYuGaOKaAM2ko6es/f1e27e311dca40ce58657e5e88cb8526/2013_2034.3840.jpg" chapters: - sys: id: axu12ftQUoS04AQkcSWYI created_at: !ruby/object:DateTime 2015-11-26 15:58:10.885000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:58:10.885000000 Z content_type_id: chapter revision: 1 title: title_internal: 'North Africa: regional, chapter 1' body: 'The Sahara is the largest non-polar desert in the world, covering almost 8,600,000 km² and comprising most of northern Africa, from the Red Sea to the Atlantic Ocean. Although it is considered a distinct entity, it is composed of a variety of geographical regions and environments, including sand seas, hammadas (stone deserts), seasonal watercourses, oases, mountain ranges and rocky plains. Rock art is found throughout this area, principally in the desert mountain and hill ranges, where stone ''canvas'' is abundant: the highlands of Adrar in Mauritania and Adrar des Ifoghas in Mali, the Atlas Mountains of Morocco and Algeria, the Tassili n’Ajjer and Ahaggar Mountains in Algeria, the mountainous areas of Tadrart Acacus and Messak in Libya, the Aïr Mountains of Nigeria, the Ennedi Plateau and Tibesti Mountains in Chad, the Gilf Kebir plateau of Egypt and Sudan, as well as the length of the Nile Valley.' - sys: id: 4DelCmwI7mQ4MC2WcuAskq created_at: !ruby/object:DateTime 2015-11-26 15:54:19.234000000 Z updated_at: !ruby/object:DateTime 2016-12-22 10:12:21.657000000 Z content_type_id: image revision: 2 image: sys: id: 1fzfpavYuGaOKaAM2ko6es created_at: !ruby/object:DateTime 2015-11-26 15:53:30.004000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:53:30.004000000 Z title: '2013,2034.3840' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1fzfpavYuGaOKaAM2ko6es/f1e27e311dca40ce58657e5e88cb8526/2013_2034.3840.jpg" caption: Bubalus Period engraving. Pelorovis Antiquus, Wadi Mathendous, Libya. 2013,2034.3840 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3593438&partId=1&images=true&people=197356&museumno=2013,2034.3840&page=1 - sys: id: 2XmfdPdXW0Y4cy6k4O4caO created_at: !ruby/object:DateTime 2015-11-26 15:58:31.891000000 Z updated_at: !ruby/object:DateTime 2016-10-17 13:40:03.509000000 Z content_type_id: chapter revision: 3 title: Types of rock art and distribution title_internal: 'North Africa: regional, chapter 2' body: |+ Although the styles and subjects of north African rock art vary, there are commonalities: images are most often figurative and frequently depict animals, both wild and domestic. There are also many images of human figures, sometimes with accessories such as recognisable weaponry or clothing. These may be painted or engraved, with frequent occurrences of both, at times in the same context. Engravings are generally more common, although this may simply be a preservation bias due to their greater durability. The physical context of rock art sites varies depending on geographical and topographical factors – for example, Moroccan rock engravings are often found on open rocky outcrops, while Tunisia’s Djebibina rock art sites have all been found in rock shelters. Rock art in the vast and harsh environments of the Sahara is often inaccessible and hard to find, and there is probably a great deal of rock art that is yet to be seen by archaeologists; what is known has mostly been documented within the last century. - sys: id: 2HqgiB8BAkqGi4uwao68Ci created_at: !ruby/object:DateTime 2016-10-17 13:41:30.844000000 Z updated_at: !ruby/object:DateTime 2016-10-17 13:41:30.844000000 Z content_type_id: chapter revision: 1 title: History of research title_internal: 'North Africa: regional chapter 2.5' body: Although the existence of rock art throughout the Sahara was known to local communities, it was not until the nineteenth century that it became known to Europeans, thanks to explorers such as <NAME>, who crossed the Messak Plateau in Libya in 1850, first noting the existence of engravings. Further explorations in the early twentieth century by celebrated travellers, ethnographers and archaeologists such as <NAME>, <NAME>, <NAME>, <NAME> and <NAME> brought the rock art of Sahara, and northern Africa in general, to the awareness of a European public. - sys: id: 5I9fUCNjB668UygkSQcCeK created_at: !ruby/object:DateTime 2015-11-26 15:54:54.847000000 Z updated_at: !ruby/object:DateTime 2016-12-22 10:13:53.921000000 Z content_type_id: image revision: 2 image: sys: id: 2N4uhoeNLOceqqIsEM6iCC created_at: !ruby/object:DateTime 2015-11-26 15:53:37.250000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:53:37.250000000 Z title: '2013,2034.1424' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2N4uhoeNLOceqqIsEM6iCC/240a45012afba4ff5508633fcaea3462/2013_2034.1424.jpg" caption: Pastoral Period painting, cattle and human figure. <NAME>, Acacus Mountains, Libya. 2013,2034.1424 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3592663 - sys: id: 5OkqapzKtqEcomSucG0EoQ created_at: !ruby/object:DateTime 2015-11-26 15:58:52.432000000 Z updated_at: !ruby/object:DateTime 2016-10-17 13:45:37.885000000 Z content_type_id: chapter revision: 4 title: Attribution and dating title_internal: 'North Africa: regional, chapter 3' body: 'The investigations of these researchers and those who have followed them have sought to date and attribute these artworks, with varying measures of success. Rock art may be associated with certain cultures through known parallels with the imagery in other artefacts, such as Naqada Period designs in Egyptian rock art that mirror those on dateable pottery. Authorship may be also guessed at through corroborating evidence: for example, due to knowledge of their chariot use, and the location of rock art depicting chariots in the central Sahara, it has been suggested that it was produced by – or at the same time as – the height of the Garamantes culture, a historical ethnic group who formed a local power around what is now southern Libya from 500 BC–700 AD. However, opportunities to anchor rock art imagery in this way to known ancient cultures are few and far between, and rock art is generally ascribed to anonymous hunter-gatherers, nomadic peoples, or pastoralists, with occasional imagery-based comparisons made with contemporary groups, such as the Fulani peoples.' - sys: id: 2KmaZb90L6qoEAK46o46uK created_at: !ruby/object:DateTime 2015-11-26 15:55:22.104000000 Z updated_at: !ruby/object:DateTime 2016-12-22 10:16:53.318000000 Z content_type_id: image revision: 2 image: sys: id: 5A1AwRfu9yM8mQ8EeOeI2I created_at: !ruby/object:DateTime 2015-11-26 15:53:37.288000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:53:37.288000000 Z title: '2013,2034.1152' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5A1AwRfu9yM8mQ8EeOeI2I/cac0592abfe1b31d7cf7f589355a216e/2013_2034.1152.jpg" caption: Round Head Period painting, human figures. <NAME>, Acacus Mountains, Libya. 2013,2034.1152 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3592099&partId=1&images=true&people=197356&page=1 - sys: id: 27ticyFfocuOIGwioIWWYA created_at: !ruby/object:DateTime 2015-11-26 15:59:26.852000000 Z updated_at: !ruby/object:DateTime 2016-10-17 15:18:29.234000000 Z content_type_id: chapter revision: 2 title_internal: 'North Africa: regional, chapter 4' body: |- Occasionally, association with writing in the form of, for example, Libyan-Berber or Arabic graffiti can give a known dating margin, but in general, lack of contemporary writing and written sources (Herodotus wrote about the Garamantes) leaves much open to conjecture. Other forms of (rare) circumstantial evidence, such as rock art covered by a dateable stratigraphic layer, and (more common) stylistic image-based dating have been used instead to form a chronology of Saharan rock art periods that is widely agreed upon, although dates are contested. The first stage, known as the Early Hunter, Wild Fauna or Bubalus Period, is posited at about 12,000–6,000 years ago, and is typified by naturalistic engravings of wild animals, in particular an extinct form of buffalo identifiable by its long horns. - sys: id: q472iFYzIsWgqWG2esg28 created_at: !ruby/object:DateTime 2015-11-26 15:55:58.985000000 Z updated_at: !ruby/object:DateTime 2016-12-22 10:19:11.991000000 Z content_type_id: image revision: 2 image: sys: id: 1YAVmJPnZ2QQiguCQsgOUi created_at: !ruby/object:DateTime 2015-11-26 15:53:29.989000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:53:29.989000000 Z title: '2013,2034.4570' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1YAVmJPnZ2QQiguCQsgOUi/4080b87891cb255e12a17216d7e71286/2013_2034.4570.jpg" caption: Horse Period painting, charioteer and standing horses. Tarssed Jebest, <NAME>, Algeria. 2013,2034.4570 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3603794 - sys: id: 7tsWGNvkQgACuKEMmC0uwG created_at: !ruby/object:DateTime 2015-11-26 15:59:47.880000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:59:47.880000000 Z content_type_id: chapter revision: 1 title_internal: 'North Africa: regional, chapter 5' body: A possibly concurrent phase is known as the Round Head Period (about 10,000 to 8,000 years ago) due to the large discoid heads of the painted human figures. Following this is the most widespread style, the Pastoral Period (around 7,500 to 4,000 years ago), which is characterised by numerous paintings and engravings of cows, as well as occasional hunting scenes. The Horse Period (around 3,000 to 2,000 years ago) features recognisable horses and chariots and the final Camel Period (around 2,000 years ago to present) features domestic dromedary camels, which we know to have been widely used across the Sahara from that time. - sys: id: 13V2nQ2cVoaGiGaUwWiQAC created_at: !ruby/object:DateTime 2015-11-26 15:56:25.598000000 Z updated_at: !ruby/object:DateTime 2016-12-22 10:39:22.861000000 Z content_type_id: image revision: 2 image: sys: id: 6MOI9r5tV6Gkae0CEiQ2oQ created_at: !ruby/object:DateTime 2015-11-26 15:53:29.964000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:53:29.964000000 Z title: 2013,2034.1424 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6MOI9r5tV6Gkae0CEiQ2oQ/bad4ec8dd7c6ae553d623e4238641561/2013_2034.1424_1.jpg" caption: Camel engraving. <NAME>, <NAME>, Sudan. 2013,2034.335 © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3586831 - sys: id: 3A64bY4VeMGkKCsGCGwu4a created_at: !ruby/object:DateTime 2015-11-26 16:00:04.267000000 Z updated_at: !ruby/object:DateTime 2016-10-17 15:30:04.896000000 Z content_type_id: chapter revision: 2 title_internal: 'North Africa: regional, chapter 6' body: "While this chronology serves as a useful framework, it must be remembered that the area – and the time period in which rock art was produced – is extensive and there is significant temporal and spatial variability within and across sites. There are some commonalities in rock art styles and themes across the Sahara, but there are also regional variations and idiosyncrasies, and a lack of evidence that any of these were directly, or even indirectly, related. The engravings of weaponry motifs from Morocco and the painted ‘swimming’ figures of the Gilf Kebir Plateau in Egypt and Sudan are not only completely different, but unique to their areas. Being thousands of kilometres apart and so different in style and composition, they serve to illustrate the limitations inherent in examining northern African rock art as a unit. The contemporary political and environmental challenges to accessing rock art sites in countries across the Sahara serves as another limiting factor in their study, but as dating techniques improve and further discoveries are made, this is a field with the potential to help illuminate much of the prehistory of northern Africa.\n\n" citations: - sys: id: 4AWHcnuAVOAkkW0GcaK6We created_at: !ruby/object:DateTime 2016-10-17 15:15:38.284000000 Z updated_at: !ruby/object:DateTime 2016-10-17 15:15:38.284000000 Z content_type_id: citation revision: 1 citation_line: | <NAME>. 1998. Art rupestre et préhistoire du Sahara: le Messak Libyen. Paris: Payot & Rivages <NAME>. 1995. Les images rupestres du Sahara. — Toulouse (author’s ed.), p. 447 <NAME>. 2001. Saharan Africa in (ed) David S. Whitley, Handbook of Rock Art Research, pp 605-636. AltaMira Press, Walnut Creek <NAME>. 2013. Dating the rock art of Wadi Sura, in Wadi Sura – The Cave of Beasts, Kuper, R. (ed). Africa Praehistorica 26 – Köln: Heinrich-Barth-Institut, pp. 38-39 <NAME>. 1999. L'art rupestre du Haut Atlas Marocain. Paris, L'Harmattan Soukopova, J. 2012. Round Heads: The Earliest Rock Paintings in the Sahara. Newcastle upon Tyne: Cambridge Scholars Publishing Vernet, R. 1993. Préhistoire de la Mauritanie. Centre Culturel Français A. de Saint Exupéry-Sépia, Nouakchott background_images: - sys: id: 3ZTCdLVejemGiCIWMqa8i created_at: !ruby/object:DateTime 2015-12-07 19:41:46.025000000 Z updated_at: !ruby/object:DateTime 2015-12-07 19:41:46.025000000 Z title: EAF135068 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3ZTCdLVejemGiCIWMqa8i/5a0d13fdd2150f0ff81a63afadd4258e/EAF135068.jpg" - sys: id: 2jvgN3MMfqoAW6GgO8wGWo created_at: !ruby/object:DateTime 2015-12-07 19:41:50.029000000 Z updated_at: !ruby/object:DateTime 2015-12-07 19:41:50.029000000 Z title: EAF131007 description: url: "//images.ctfassets.net/xt8ne4gbbocd/2jvgN3MMfqoAW6GgO8wGWo/393c91068f4dc0ca540c35a79b965288/EAF131007.jpg" ---<file_sep>/_coll_country/nigeria.md --- contentful: sys: id: 3KmS7DebO0e2skQsiuGOGo created_at: !ruby/object:DateTime 2017-11-21 09:03:26.866000000 Z updated_at: !ruby/object:DateTime 2019-02-12 02:08:00.867000000 Z content_type_id: country revision: 7 name: Nigeria slug: nigeria col_url: https://africanrockart.britishmuseum.org/country/nigeria/images/ map_progress: true intro_progress: true image_carousel: - sys: id: 5ofSFGPY6k6EmOK6OgAwAE created_at: !ruby/object:DateTime 2017-11-16 17:24:25.549000000 Z updated_at: !ruby/object:DateTime 2019-02-12 02:07:38.901000000 Z title: NIGCRM0070019 description: https://africanrockart.britishmuseum.org/country/nigeria/images/ url: "//images.ctfassets.net/xt8ne4gbbocd/5ofSFGPY6k6EmOK6OgAwAE/6b88478824aadcf00d4bf77f8ea3fa4c/NIGCRM0070019.jpg" - sys: id: 7kRiKib4PYC2EE6wcuUE4g created_at: !ruby/object:DateTime 2017-11-16 17:24:04.187000000 Z updated_at: !ruby/object:DateTime 2019-02-12 02:07:47.263000000 Z title: NIGCRM0090004 description: https://africanrockart.britishmuseum.org/country/nigeria/images/ url: "//images.ctfassets.net/xt8ne4gbbocd/7kRiKib4PYC2EE6wcuUE4g/f67eaf202892a271af516fa95ecfbf38/NIGCRM0090004.jpg" featured_site: sys: id: 3pCjM8ACHeyCo28Kuye6Oa created_at: !ruby/object:DateTime 2017-12-12 03:41:45.814000000 Z updated_at: !ruby/object:DateTime 2017-12-12 03:41:45.814000000 Z content_type_id: featured_site revision: 1 title: Ikom Monoliths, Cross River State, Nigeria slug: 'ikom-monoliths ' chapters: - sys: id: 6tTnRXJY5O4oiMcUIg2e6w created_at: !ruby/object:DateTime 2017-12-12 01:00:49.285000000 Z updated_at: !ruby/object:DateTime 2017-12-12 01:00:49.285000000 Z content_type_id: chapter revision: 1 title_internal: 'Nigeria: featured site, chapter 1' body: The Ikom Monoliths, originally consisting of around 400-450 engraved standing stones and distributed around thirty communities in the Ikom area of Cross River State, Nigeria, are thought to be up to 1500 years old. In more recent years, threatened by fire, theft, vandalism and neglect, there are now estimated to be less than 250. - sys: id: 5WVd1xtyCW8IkIm8MkyqoA created_at: !ruby/object:DateTime 2017-12-12 01:03:19.623000000 Z updated_at: !ruby/object:DateTime 2017-12-12 01:03:19.623000000 Z content_type_id: image revision: 1 image: sys: id: 6ndlBNzj4kC4IyysaSk20Y created_at: !ruby/object:DateTime 2017-12-12 01:02:00.372000000 Z updated_at: !ruby/object:DateTime 2017-12-12 01:02:00.372000000 Z title: NIGCRM0040011 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6ndlBNzj4kC4IyysaSk20Y/a9e3b2d35c3e0ee55a93cef88d92b9e3/NIGCRM0040011.jpg" caption: Monolith from Nnaborakpa with village elder standing in the background. 2013,2034.24046 © <NAME>/TARA - sys: id: 3wE6yzisV22Cq6S266Q8CO created_at: !ruby/object:DateTime 2017-12-12 01:13:13.390000000 Z updated_at: !ruby/object:DateTime 2017-12-12 01:13:13.390000000 Z content_type_id: chapter revision: 1 title_internal: 'Nigeria: featured site, chapter 2' body: 'The majority of the stones are skilfully carved in hard, medium-textured basaltic rock, with a few carved in sandstone and shelly limestone. Varying in height from 0.91-1.83m (3-6 feet) and sculpted into a phallus-shape, the stones share common decorative features. They depict stylised human features comprising two eyes, an open mouth, a head crowned with rings, a pointed beard, an elaborately marked navel, two hands with five fingers, a nose and a variety of facial markings. Emphasis is placed on the head while the rest of the body tapers into the base of the phallus’ shaped monolith, with limbs and legs suggested. They are also linearly inscribed with complex geometric motifs, which have been compared to the rock arts of Tanzania in that the meanings of the symbols are known to only the artists (UNESCO, 2007). ' - sys: id: 5Ep1vP8VXOi2se8O6qIY2q created_at: !ruby/object:DateTime 2017-12-12 01:46:21.095000000 Z updated_at: !ruby/object:DateTime 2017-12-12 01:46:21.095000000 Z content_type_id: image revision: 1 image: sys: id: 3EPsiq8TFKE0omSUGy2OiW created_at: !ruby/object:DateTime 2017-12-12 01:44:18.764000000 Z updated_at: !ruby/object:DateTime 2017-12-12 01:44:18.764000000 Z title: NIGCRM0090006 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3EPsiq8TFKE0omSUGy2OiW/920454e1f1e3b5ed3e7c24108a6c46ee/NIGCRM0090006.jpg" caption: Monolith from Agba. 2013,2034.24215© <NAME>/TARA - sys: id: 4fEnlxdHhSc4gUcGMyaegi created_at: !ruby/object:DateTime 2017-12-12 01:50:43.447000000 Z updated_at: !ruby/object:DateTime 2017-12-12 01:50:43.447000000 Z content_type_id: image revision: 1 image: sys: id: 1FTDyPet3WiyQYiq2UYEeu created_at: !ruby/object:DateTime 2017-12-12 01:49:44.361000000 Z updated_at: !ruby/object:DateTime 2017-12-12 01:49:44.361000000 Z title: NIGCRM0020001 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1FTDyPet3WiyQYiq2UYEeu/5691015503e7f726f99676e2976ef569/NIGCRM0020001.jpg" caption: Monolith from Njemetop. 2013,2034.23963 © <NAME>/TARA - sys: id: 21hKs1bzN6imgeCkiouquo created_at: !ruby/object:DateTime 2017-12-12 01:51:41.445000000 Z updated_at: !ruby/object:DateTime 2017-12-12 01:51:41.445000000 Z content_type_id: chapter revision: 1 title_internal: 'Nigeria: featured site, chapter 3' body: The effects of weathering has resulted in erosion and deterioration, and as such in 2007 were added to the World Monuments Fund’s list of sites in danger and are being considered for inclusion into UNESCO’s World Heritage Site list. Furthermore, it is estimated that the total numbers of monoliths is now thought to be less than 250, with many having been distributed among major museums throughout the world. - sys: id: 5Lj0qQJbj2eUyGsMEUegiG created_at: !ruby/object:DateTime 2017-12-12 01:54:04.301000000 Z updated_at: !ruby/object:DateTime 2017-12-12 01:54:04.301000000 Z content_type_id: image revision: 1 image: sys: id: 1wBaFXQ6iY2igSUc0Qwm02 created_at: !ruby/object:DateTime 2017-12-12 01:52:33.766000000 Z updated_at: !ruby/object:DateTime 2017-12-12 01:52:33.766000000 Z title: NIGCRM0070021 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1wBaFXQ6iY2igSUc0Qwm02/9bf58633776be1e68afbcc3a2bdf0279/NIGCRM0070021.jpg" caption: Moss and lichen growing on one of the monoliths occluding facial feaures, Nikirigom. 2013,2034.24103 © David Coulson/TARA - sys: id: 5IN3UXWyqswwO0qu4q6Ukc created_at: !ruby/object:DateTime 2017-12-12 01:55:42.020000000 Z updated_at: !ruby/object:DateTime 2017-12-12 01:55:42.020000000 Z content_type_id: image revision: 1 image: sys: id: 4GxwIaZP680CyIGeQ4YesO created_at: !ruby/object:DateTime 2017-12-12 01:54:53.364000000 Z updated_at: !ruby/object:DateTime 2017-12-12 01:54:53.364000000 Z title: NIGCRM0100031 description: url: "//images.ctfassets.net/xt8ne4gbbocd/4GxwIaZP680CyIGeQ4YesO/1a6e720fb39268f67947f11e6a496cce/NIGCRM0100031.jpg" caption: Fallen monolith that has been damaged by fire, Edamkono. 2013,2034.24278 © David Coulson/TARA - sys: id: 5UGVq9x89UIaMYwOmaCWYq created_at: !ruby/object:DateTime 2017-12-12 02:03:17.080000000 Z updated_at: !ruby/object:DateTime 2017-12-12 02:03:17.080000000 Z content_type_id: chapter revision: 1 title_internal: 'Nigeria: featured site, chapter 4' body: Known as Akwasnshi or Atal among the local Ejagham people of Cross River, the monoliths can be found in the centre of the village or in the central meeting place of the village elders, but also in the uncultivated forest outside the villages. In each village in which they are found, the upright stones are positioned in circles, sometimes perfect circles, facing each other. Some are slightly carved as very low reliefs, while others are inscribed engravings. - sys: id: 7afrXxiCmAmIq2Ae8CEMsQ created_at: !ruby/object:DateTime 2017-12-12 02:04:55.030000000 Z updated_at: !ruby/object:DateTime 2017-12-12 02:04:55.030000000 Z content_type_id: image revision: 1 image: sys: id: 4Rzr1W9YZ2yecY6MGkQ8Y8 created_at: !ruby/object:DateTime 2017-12-12 02:04:07.843000000 Z updated_at: !ruby/object:DateTime 2017-12-12 02:04:07.843000000 Z title: NIGCRM0010062 description: url: "//images.ctfassets.net/xt8ne4gbbocd/4Rzr1W9YZ2yecY6MGkQ8Y8/b45ad7ea3470fdabaea542144334b4f2/NIGCRM0010062.jpg" caption: View of five standing stones and one fallen stone in a clearing, Alok. 2013,2034.23933 © <NAME>/TARA - sys: id: 2mMylBVqvaQ6gIgoAiO6MU created_at: !ruby/object:DateTime 2017-12-12 02:05:49.581000000 Z updated_at: !ruby/object:DateTime 2017-12-12 02:05:49.581000000 Z content_type_id: chapter revision: 1 title_internal: 'Nigeria: featured site, chapter 5' body: Whilst the stones seem to share common features, each monolith is unique in its design and execution, and are thought to “bear a complex codified iconography and an ancient writing, communication and graphic system composed in a complex traditional design configuration” (UNESCO 2007). - sys: id: 20UEFUXCJOO6ki86sMi6q2 created_at: !ruby/object:DateTime 2017-12-12 03:35:55.321000000 Z updated_at: !ruby/object:DateTime 2017-12-12 03:35:55.321000000 Z content_type_id: chapter revision: 1 title: Interpretation title_internal: 'Nigeria: featured site, chapter 6' body: | Local ethnographies about the Ikom monoliths are based in oral traditions and as such there are numerous meanings associated with the stones. For example, stone circles are used as places of sacrifice and community meeting places. They were created as memorials of departed heroes or beloved family members and represent powerful ancestral spirits to whom offerings are still made (Esu and Ukata, 2012:112). In addition local community leaders also ascribed religious significance of the stones whereby particular stone are dedicated to the god of harvest, the god of fertility and the god of war (Esu and Ukata, 2012:113). The local communities in the area value the monoliths in their traditional practices, beliefs and rituals, such as being ceremonially painted at the time of the [Yam festival](http://africanrockart.org/news/monoliths-cross-river-state-nigeria "monoliths cross river state"). - sys: id: 5Azwtj3SEgoEweaESQUY0e created_at: !ruby/object:DateTime 2017-12-12 03:39:23.421000000 Z updated_at: !ruby/object:DateTime 2017-12-12 03:39:23.421000000 Z content_type_id: image revision: 1 image: sys: id: rOeKzKuGw8EMG08MyM02Q created_at: !ruby/object:DateTime 2017-12-12 03:38:21.345000000 Z updated_at: !ruby/object:DateTime 2017-12-12 03:38:21.345000000 Z title: NIGCRM0010081 description: url: "//images.ctfassets.net/xt8ne4gbbocd/rOeKzKuGw8EMG08MyM02Q/a8e500a01a2d3f45d2c761aeb181d904/NIGCRM0010081.jpg" caption: 'Monoith being opainted in orange, blue and white by local woman. Standing to the left is Chief Silvanus Akong of Alok village. 2013,2034.23952 © David Coulson/TARA ' - sys: id: 47U5H0p6yQUWagCwYauyci created_at: !ruby/object:DateTime 2017-12-12 03:40:23.912000000 Z updated_at: !ruby/object:DateTime 2017-12-12 03:40:23.912000000 Z content_type_id: chapter revision: 1 title_internal: 'Nigeria: featured site, chapter 7' body: 'Recent criticism has focused on ways in which scholars have situated these sculptural forms within Western/European anthropological and archaeological discourse that has reduced them to “mere artefacts and monuments” rather than attending to their “artistic attributes, content and context” (Akpang, 2014:67-68). ' citations: - sys: id: 5XzFExCZYA4mKGY0ua6Iwc created_at: !ruby/object:DateTime 2017-12-12 00:54:17.136000000 Z updated_at: !ruby/object:DateTime 2017-12-12 00:54:17.136000000 Z content_type_id: citation revision: 1 citation_line: "<NAME>. 2014. ‘Beyond Anthropological and Associational discourse- interrogating the minimalism of Ikom Monoliths as concept and found object art’, in \n*Global Journal of Arts Humanities and Social Sciences*, Vol.2, Issue 1, pp.67-84.\n\nAllison P. 1967. *Cross River State Monoliths*. Lagos: Department of Antiquities, Federal Republic of Nigeria.\n\nEsu, B. B. and <NAME>. 2012. ‘Enhancing the tourism value of Cross River state monoliths and stone circles through geo-mapping and ethnographic study (part 1)’, in *Journal of Hospitality Management and Tourism*, Vol. 3(6), pp. 106-116.\n\nLe Quellec, J-L. 2004. *Rock Art in Africa: Mythology and Legend*. Paris: Flammarion.\n\nMangut, J. and <NAME>. 2012. ‘Harnessing the Potentials of Rock Art Sites in Birnin Kudu, Jigawa State, Nigeria for Tourism Development’, in *Journal of Tourism and Heritage*, Vol.1 No. 1 pp: 36-42.\n\nShaw, T. 1978. *Nigeria its Archaeology and Early History*. London: Thames and\nHudson.\n\nUNESCO. 2007. \ ‘Alok Ikom Monoliths’ UNESCO [Online], Available at: http://whc.unesco.org/en/tentativelists/5173/\n\nVaughan J. H. 1962. ‘Rock paintings and Rock gong among the Marghi of\nNigeria’ in *Man*, 62, pp:49-52.\n\n\n" background_images: - sys: id: 3EPsiq8TFKE0omSUGy2OiW created_at: !ruby/object:DateTime 2017-12-12 01:44:18.764000000 Z updated_at: !ruby/object:DateTime 2017-12-12 01:44:18.764000000 Z title: NIGCRM0090006 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3EPsiq8TFKE0omSUGy2OiW/920454e1f1e3b5ed3e7c24108a6c46ee/NIGCRM0090006.jpg" - sys: id: rOeKzKuGw8EMG08MyM02Q created_at: !ruby/object:DateTime 2017-12-12 03:38:21.345000000 Z updated_at: !ruby/object:DateTime 2017-12-12 03:38:21.345000000 Z title: NIGCRM0010081 description: url: "//images.ctfassets.net/xt8ne4gbbocd/rOeKzKuGw8EMG08MyM02Q/a8e500a01a2d3f45d2c761aeb181d904/NIGCRM0010081.jpg" key_facts: sys: id: 56FnXwosA0kgA8WIM8Kusk created_at: !ruby/object:DateTime 2017-11-17 17:44:51.477000000 Z updated_at: !ruby/object:DateTime 2017-11-28 17:31:13.877000000 Z content_type_id: country_key_facts revision: 2 title_internal: 'Nigeria: key facts' image_count: 439 images date_range: 1500 BC -1500 AD main_areas: North-West and South-East, Cross River State techniques: Paintings and engraved standing stones main_themes: Animals, geometrics and stylised human faces thematic_articles: - sys: id: 5HZTuIVN8AASS4ikIea6m6 created_at: !ruby/object:DateTime 2017-12-19 12:27:08.508000000 Z updated_at: !ruby/object:DateTime 2017-12-19 12:27:08.508000000 Z content_type_id: thematic revision: 1 title: Introduction to rock art in central and eastern Africa slug: rock-art-in-central-and-east-africa lead_image: sys: id: 3esXNapo5GOWIKSImcY4QW created_at: !ruby/object:DateTime 2015-11-25 18:56:43.836000000 Z updated_at: !ruby/object:DateTime 2017-12-15 17:01:05.082000000 Z title: '2013,2034.12982' description: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3776396 url: "//images.ctfassets.net/xt8ne4gbbocd/3esXNapo5GOWIKSImcY4QW/6436b2034659eccb953844b21a400070/2013_2034.12982.jpg" chapters: - sys: id: 4ln5fQLq2saMKsOA4WSAgc created_at: !ruby/object:DateTime 2015-11-25 19:09:33.580000000 Z updated_at: !ruby/object:DateTime 2015-12-11 11:17:25.155000000 Z content_type_id: chapter revision: 4 title: Central and East Africa title_internal: 'East Africa: regional, chapter 1' body: |- Central Africa is dominated by vast river systems and lakes, particularly the Congo River Basin. Characterised by hot and wet weather on both sides of the equator, central Africa has no regular dry season, but aridity increases in intensity both north and south of the equator. Covered with a forest of about 400,000 m² (1,035,920 km²), it is one of the greenest parts of the continent. The rock art of central Africa stretches from the Zambezi River to the Angolan Atlantic coast and reaches as far north as Cameroon and Uganda. Termed the ‘schematic rock art zone’ by <NAME> (1959), it is dominated by finger-painted geometric motifs and designs, thought to extend back many thousands of years. Eastern Africa, from the Zambezi River Valley to Lake Turkana, consists largely of a vast inland plateau with the highest elevations on the continent, such as Mount Kilimanjaro (5,895m above sea level) and Mount Kenya (5,199 m above sea level). Twin parallel rift valleys run through the region, which includes the world’s second largest freshwater lake, Lake Victoria. The climate is atypical of an equatorial region, being cool and dry due to the high altitude and monsoon winds created by the Ethiopian Highlands. The rock art of eastern Africa is concentrated on this plateau and consists mainly of paintings that include animal and human representations. Found mostly in central Tanzania, eastern Zambia and Malawi; in comparison to the widespread distribution of geometric rock art, this figurative tradition is much more localised, and found at just a few hundred sites in a region of less than 100km in diameter. - sys: id: 4nyZGLwHTO2CK8a2uc2q6U created_at: !ruby/object:DateTime 2015-11-25 18:57:48.121000000 Z updated_at: !ruby/object:DateTime 2017-12-15 17:05:00.916000000 Z content_type_id: image revision: 2 image: sys: id: 3esXNapo5GOWIKSImcY4QW created_at: !ruby/object:DateTime 2015-11-25 18:56:43.836000000 Z updated_at: !ruby/object:DateTime 2017-12-15 17:01:05.082000000 Z title: '2013,2034.12982' description: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3776396 url: "//images.ctfassets.net/xt8ne4gbbocd/3esXNapo5GOWIKSImcY4QW/6436b2034659eccb953844b21a400070/2013_2034.12982.jpg" caption: Laikipia, Kenya. 2013,2034.12982 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3776396 - sys: id: 1OvIWDPyXaCO2gCWw04s06 created_at: !ruby/object:DateTime 2015-11-25 19:10:23.723000000 Z updated_at: !ruby/object:DateTime 2015-12-11 11:18:19.325000000 Z content_type_id: chapter revision: 2 title_internal: 'East Africa: regional, chapter 2' body: This collection from Central and East Africa comprises rock art from Kenya, Uganda and Tanzania, as well as the Horn of Africa; although predominantly paintings, engravings can be found in most countries. - sys: id: 4JqI2c7CnYCe8Wy2SmesCi created_at: !ruby/object:DateTime 2015-11-25 19:10:59.991000000 Z updated_at: !ruby/object:DateTime 2016-10-17 13:34:14.653000000 Z content_type_id: chapter revision: 3 title: History of research title_internal: 'East Africa: regional, chapter 3' body: |- The rock art of East Africa, in particular the red paintings from Tanzania, was extensively studied by Mary and <NAME> in the 1930s and 1950s. <NAME> observed Sandawe people of Tanzania making rock paintings in the mid-20th century, and on the basis of oral traditions argued that the rock art was made for three main purposes: casual art; magic art (for hunting purposes or connected to health and fertility) and sacrificial art (to appease ancestral spirits). Subsequently, during the 1970s Fidelis Masao and <NAME> recorded numerous sites, classifying the art in broad chronological and stylistic categories, proposing tentative interpretations with regard to meaning. There has much debate and uncertainty about Central African rock art. The history of the region has seen much mobility and interaction of cultural groups and understanding how the rock art relates to particular groups has been problematic. Pioneering work in this region was undertaken by <NAME> in central Malawi in the early 1920s, <NAME> visited Zambia in 1936 and attempted to provide a chronological sequence and some insight into the meaning of the rock art. Since the 1950s (Clarke, 1959), archaeologists have attempted to situate rock art within broader archaeological frameworks in order to resolve chronologies, and to categorise the art with reference to style, colour, superimposition, subject matter, weathering, and positioning of depictions within the panel (Phillipson, 1976). Building on this work, our current understanding of rock in this region has been advanced by <NAME> (1995, 1997, 2001) with his work in Zambia and Malawi. - sys: id: 35HMFoiKViegWSY044QY8K created_at: !ruby/object:DateTime 2015-11-25 18:59:25.796000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:51:25.789000000 Z content_type_id: image revision: 5 image: sys: id: 6KOxC43Z9mYCuIuqcC8Qw0 created_at: !ruby/object:DateTime 2015-11-25 18:57:00.077000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:57:00.077000000 Z title: '2013,2034.17450' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6KOxC43Z9mYCuIuqcC8Qw0/e25141d07f483d0100c4cf5604e3e525/2013_2034.17450.jpg" caption: This painting of a large antelope is possibly one of the earliest extant paintings. <NAME> believes similar paintings could be more than 28,000 years old. 2013,2034.17450 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3711689 - sys: id: 1dSBI9UNs86G66UGSEOOkS created_at: !ruby/object:DateTime 2015-12-09 11:56:31.754000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:50:18.203000000 Z content_type_id: chapter revision: 5 title: East African Rock Art title_internal: Intro to east africa, chapter 3.5 body: "Rock art of East Africa consists mainly of paintings, most of which are found in central Tanzania, and are fewer in number in eastern Zambia and Malawi; scholars have categorised them as follows:\n\n*__Red Paintings__*: \nRed paintings can be sub-divided into those found in central Tanzania and those found stretching from Zambia to the Indian Ocean.\nTanzanian red paintings include large, naturalistic animals with occasional geometric motifs. The giraffe is the most frequently painted animal, but antelope, zebra, elephant, rhino, felines and ostrich are also depicted. Later images show figures with highly distinctive stylised human head forms or hairstyles and body decoration, sometimes in apparent hunting and domestic scenes. The Sandawe and Hadza, hunter-gatherer groups, indigenous to north-central and central Tanzania respectively, claim their ancestors were responsible for some of the later art.\n\nThe area in which Sandawe rock art is found is less than 100km in diameter and occurs at just a few hundred sites, but corresponds closely to the known distribution of this group. There have been some suggestions that Sandawe were making rock art early into the 20th century, linking the art to particular rituals, in particular simbo; a trance dance in which the Sandawe communicate with the spirit world by taking on the power of an animal. The art displays a range of motifs and postures, features that can be understood by reference to simbo and to trance experiences; such as groups of human figures bending at the waist (which occurs during the *simbo* dance), taking on animal features such as ears and tails, and floating or flying; reflecting the experiences of those possessed in the dance." - sys: id: 7dIhjtbR5Y6u0yceG6y8c0 created_at: !ruby/object:DateTime 2015-11-25 19:00:07.434000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:51:51.887000000 Z content_type_id: image revision: 5 image: sys: id: 1fy9DD4BWwugeqkakqWiUA created_at: !ruby/object:DateTime 2015-11-25 18:57:11.188000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:57:11.188000000 Z title: '2013,2034.16849' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1fy9DD4BWwugeqkakqWiUA/9f8f1330c6c0bc0ff46d744488daa152/2013_2034.16849.jpg" caption: Three schematic figures formed by the use of multiple thin parallel lines. The shape and composition of the heads suggests either headdresses or elaborate hairstyles. Kondoa, Tanzania. 2013,2034.16849 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3709812 - sys: id: 1W573pi2Paks0iA8uaiImy created_at: !ruby/object:DateTime 2015-11-25 19:12:00.544000000 Z updated_at: !ruby/object:DateTime 2015-12-11 11:21:09.647000000 Z content_type_id: chapter revision: 8 title_internal: 'East Africa: regional, chapter 4' body: "Zambian rock art does not share any similarities with Tanzanian rock art and can be divided into two categories; animals (with a few depictions of humans), and geometric motifs. Animals are often highly stylised and superimposed with rows of dots. Geometric designs include, circles, some of which have radiating lines, concentric circles, parallel lines and ladder shapes. Predominantly painted in red, the remains of white pigment is still often visible. David Phillipson (1976) proposed that the naturalistic animals were earlier in date than geometric designs. Building on Phillipson’s work, <NAME> studied ethnographic records and demonstrated that geometric motifs were made by women or controlling the weather.\n\n*__Pastoralist paintings__*: \nPastoralist paintings are rare, with only a few known sites in Kenya and other possible sites in Malawi. Usually painted in black, white and grey, but also in other colours, they include small outlines, often infilled, of cattle and are occasional accompanied by geometric motifs. Made during the period from 3,200 to 1,800 years ago the practice ceased after Bantu language speaking people had settled in eastern Africa. Similar paintings are found in Ethiopia but not in southern Africa, and it has been assumed that these were made by Cushitic or Nilotic speaking groups, but their precise attribution remains unclear (Smith, 2013:154).\n" - sys: id: 5jReHrdk4okicG0kyCsS6w created_at: !ruby/object:DateTime 2015-11-25 19:00:41.789000000 Z updated_at: !ruby/object:DateTime 2017-12-15 17:10:04.890000000 Z content_type_id: image revision: 3 image: sys: id: 1hoZEK3d2Oi8iiWqoWACo created_at: !ruby/object:DateTime 2015-11-25 18:56:43.848000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:56:43.848000000 Z title: '2013,2034.13653' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1hoZEK3d2Oi8iiWqoWACo/1a1adcfad5d5a1cf0a341316725d61c4/2013_2034.13653.jpg" caption: Two red bulls face right. Mt Elgon, Kenya. 2013,2034.13653. © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3700058 - sys: id: 7rFAK9YoBqYs0u0EmCiY64 created_at: !ruby/object:DateTime 2015-11-25 19:00:58.494000000 Z updated_at: !ruby/object:DateTime 2017-12-15 17:11:37.760000000 Z content_type_id: image revision: 3 image: sys: id: 3bqDVyvXlS0S6AeY2yEmS8 created_at: !ruby/object:DateTime 2015-11-25 18:56:43.880000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:56:43.880000000 Z title: '2013,2034.13635' description: url: "//images.ctfassets.net/xt8ne4gbbocd/3bqDVyvXlS0S6AeY2yEmS8/c9921f3d8080bcef03c96c6b8f1b0323/2013_2034.13635.jpg" caption: Two cattle with horns in twisted perspective. Mt Elgon, Kenya. 2013,2034.13635. © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3698905 - sys: id: 1tX4nhIUgAGmyQ4yoG6WEY created_at: !ruby/object:DateTime 2015-11-25 19:14:33.823000000 Z updated_at: !ruby/object:DateTime 2015-11-25 19:14:33.823000000 Z content_type_id: chapter revision: 1 title_internal: 'East Africa: regional, chapter 5' body: |- *__Late White Paintings__*: Commonly painted in white, or off-white with the fingers, so-called ‘Late White’ depictions include quite large crudely rendered representations of wild animals, mythical animals, human figures and numerous geometric motifs. These paintings are attributed to Bantu language speaking, iron-working farmers who entered eastern Africa about 2,000 years ago from the west on the border of Nigeria and Cameroon. Moving through areas occupied by the Batwa it is thought they learned the use of symbols painted on rock, skin, bark cloth and in sand. Chewa peoples, Bantu language speakers who live in modern day Zambia and Malawi claim their ancestors made many of the more recent paintings which they used in rites of passage ceremonies. - sys: id: 35dNvNmIxaKoUwCMeSEO2Y created_at: !ruby/object:DateTime 2015-11-25 19:01:26.458000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:52:15.838000000 Z content_type_id: image revision: 4 image: sys: id: 6RGZZQ13qMQwmGI86Ey8ei created_at: !ruby/object:DateTime 2015-11-25 18:57:11.188000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:57:11.188000000 Z title: '2013,2034.16786' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6RGZZQ13qMQwmGI86Ey8ei/6d37a5bed439caf7a1223aca27dc27f8/2013_2034.16786.jpg" caption: Under a long narrow granite overhang, Late White designs including rectangular grids, concentric circles and various ‘square’ shapes. 2013,2034.16786 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3709608 - sys: id: 2XW0X9BzFCa8u2qiKu6ckK created_at: !ruby/object:DateTime 2015-11-25 19:01:57.959000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:53:21.559000000 Z content_type_id: image revision: 4 image: sys: id: 1UT4r6kWRiyiUIYSkGoACm created_at: !ruby/object:DateTime 2015-11-25 18:57:11.138000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:57:11.138000000 Z title: '2013,2034.16797' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1UT4r6kWRiyiUIYSkGoACm/fe915c6869b6c195d55b5ef805df7671/2013_2034.16797.jpg" caption: A monuments guard stands next to Late White paintings attributed to Bantu speaking farmers in Tanzania, probably made during the last 700 years. 2013,2034.16797 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3709628 - sys: id: 3z28O8A58AkgMUocSYEuWw created_at: !ruby/object:DateTime 2015-11-25 19:15:04.047000000 Z updated_at: !ruby/object:DateTime 2015-11-25 19:15:04.047000000 Z content_type_id: chapter revision: 1 title_internal: 'East Africa: regional, chapter 6' body: |- *__Meat-feasting paintings__*: Meat-feasting shelters exist from northern Tanzania through Kenya to Lake Turkana, and are places where Maa-speaking initiated men, who are not permitted to eat meat in their homes, gather to kill and feast on animals, predominantly cattle. The term Maa relates to a group of closely related Eastern Nilotic languages, which historically dominated the east African hinterland; and today is spoken by around a million people. During or after feasting, symbols of the animals that had been eaten were painted on the shelter ceiling in white or less often red. Maa speakers brand their cattle and camels with symbols that signify the lineage of their owners, but may also indicate if an animal has been treated for a particular disease. Different symbols may be used for male and female animals. Over the centuries, because the depictions are on the ceiling of meat feasting rock shelters, and because sites are used even today, a build-up of soot has obscured or obliterated the paintings. Unfortunately, few have been recorded or mapped. - sys: id: 1yjQJMFd3awKmGSakUqWGo created_at: !ruby/object:DateTime 2015-11-25 19:02:23.595000000 Z updated_at: !ruby/object:DateTime 2017-12-15 17:19:11.619000000 Z content_type_id: image revision: 3 image: sys: id: p4E0BRJzossaus6uUUkuG created_at: !ruby/object:DateTime 2015-11-25 18:56:49.743000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:56:49.743000000 Z title: '2013,2034.13004' description: url: "//images.ctfassets.net/xt8ne4gbbocd/p4E0BRJzossaus6uUUkuG/13562eee76ac2a9efe8c0d12e62fa23a/2013_2034.13004.jpg" caption: Huge granite boulder with Ndorobo man standing before a rock overhang used for meat-feasting. Laikipia, Kenya. 2013,2034. 13004. © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3700175 - sys: id: 6lgjLZVYrY606OwmwgcmG2 created_at: !ruby/object:DateTime 2015-11-25 19:02:45.427000000 Z updated_at: !ruby/object:DateTime 2017-12-15 17:20:14.877000000 Z content_type_id: image revision: 3 image: sys: id: 1RLyVKKV8MA4KEk4M28wqw created_at: !ruby/object:DateTime 2015-11-25 18:57:11.150000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:57:11.150000000 Z title: '2013,2034.13018' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1RLyVKKV8MA4KEk4M28wqw/044529be14a590fd1d0da7456630bb0b/2013_2034.13018.jpg" caption: This symbol is probably a ‘brand’ used on cattle that were killed and eaten at a Maa meat feast. Laikipia, Kenya. 2013,2034.13018 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3700193 - sys: id: 5UQc80DUBiqqm64akmCUYE created_at: !ruby/object:DateTime 2015-11-25 19:15:34.582000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:53:53.936000000 Z content_type_id: chapter revision: 4 title: Central African Rock Art title_internal: 'East Africa: regional, chapter 7' body: The rock art of central Africa is attributed to hunter-gatherers known as Batwa. This term is used widely in eastern central and southern Africa to denote any autochthonous hunter-gatherer people. The rock art of the Batwa can be divided into two categories which are quite distinctive stylistically from the Tanzanian depictions of the Sandawe and Hadza. Nearly 3,000 sites are currently known from within this area. The vast majority, around 90%, consist of finger-painted geometric designs; the remaining 10% include highly stylised animal forms (with a few human figures) and rows of finger dots. Both types are thought to date back many thousands of years. The two traditions co-occur over a vast area of eastern and central Africa and while often found in close proximity to each other are only found together at a few sites. However, it is the dominance of geometric motifs that make this rock art tradition very distinctive from other regions in Africa. - sys: id: 4m51rMBDX22msGmAcw8ESw created_at: !ruby/object:DateTime 2015-11-25 19:03:40.666000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:54:25.415000000 Z content_type_id: image revision: 4 image: sys: id: 2MOrR79hMcO2i8G2oAm2ik created_at: !ruby/object:DateTime 2015-11-25 18:56:49.737000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:56:49.737000000 Z title: '2013,2034.15306' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2MOrR79hMcO2i8G2oAm2ik/86179e84233956e34103566035c14b76/2013_2034.15306.jpg" caption: Paintings in red and originally in-filled in white cover the underside of a rock shelter roof. The art is attributed to central African Batwa; the age of the paintings is uncertain. Lake Victoria, Uganda. 2013,2034.15306 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3691242 - sys: id: 5rNOG3568geMmIEkIwOIac created_at: !ruby/object:DateTime 2015-11-25 19:16:07.130000000 Z updated_at: !ruby/object:DateTime 2015-11-25 19:16:19.722000000 Z content_type_id: chapter revision: 2 title_internal: 'East Africa: regional, chapter 8' body: "*__Engravings__*:\nThere are a few engravings occurring on inland plateaus but these have elicited little scientific interest and are not well documented. \ Those at the southern end of Lake Turkana have been categorised into two types: firstly, animals, human figures and geometric forms and also geometric forms thought to involve lineage symbols.\nIn southern Ethiopia, near the town of Dillo about 300 stelae, some of which stand up to two metres in height, are fixed into stones and mark grave sites. People living at the site ask its spirits for good harvests. \n" - sys: id: LrZuJZEH8OC2s402WQ0a6 created_at: !ruby/object:DateTime 2015-11-25 19:03:59.496000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:54:51.576000000 Z content_type_id: image revision: 5 image: sys: id: 1uc9hASXXeCIoeMgoOuO4e created_at: !ruby/object:DateTime 2015-11-25 18:57:11.176000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:57:11.176000000 Z title: '2013,2034.16206' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1uc9hASXXeCIoeMgoOuO4e/09a7504449897509778f3b9455a42f8d/2013_2034.16206.jpg" caption: Group of anthropomorphic stelae with carved faces. Tuto Fela, Southern Ethiopia. 2013,2034.16206 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3703754 - sys: id: 7EBTx1IjKw6y2AUgYUkAcm created_at: !ruby/object:DateTime 2015-11-25 19:16:37.210000000 Z updated_at: !ruby/object:DateTime 2015-12-11 11:22:04.007000000 Z content_type_id: chapter revision: 2 title_internal: 'East Africa: regional, chapter 9' body: In the Sidamo region of Ethiopia, around 50 images of cattle are engraved in bas-relief on the wall of a gorge. All the engravings face right and the cows’ udders are prominently displayed. Similar engravings of cattle, all close to flowing water, occur at five other sites in the area, although not in such large numbers. - sys: id: 6MUkxUNFW8oEK2aqIEcee created_at: !ruby/object:DateTime 2015-11-25 19:04:34.186000000 Z updated_at: !ruby/object:DateTime 2017-12-19 12:22:24.891000000 Z content_type_id: image revision: 3 image: sys: id: PlhtduNGSaOIOKU4iYu8A created_at: !ruby/object:DateTime 2015-11-25 18:56:43.849000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:56:43.849000000 Z title: '2013,2034.16235' description: url: "//images.ctfassets.net/xt8ne4gbbocd/PlhtduNGSaOIOKU4iYu8A/7625c8a21caf60046ea73f184e8b5c76/2013_2034.16235.jpg" caption: Around 50 images of cattle are engraved in bas-relief into the sandstone wall of a gorge in the Sidamo region of Ethiopia. 2013,2034.16235 © TARA/David Coulson col_link: http://bit.ly/2hMU0vm - sys: id: 6vT5DOy7JK2oqgGK8EOmCg created_at: !ruby/object:DateTime 2015-11-25 19:17:53.336000000 Z updated_at: !ruby/object:DateTime 2015-12-11 11:25:38.678000000 Z content_type_id: chapter revision: 3 title: Rock art in the Horn of Africa title_internal: 'East Africa: regional, chapter 10' body: "The Horn of Africa has historically been a crossroads area between the Eastern Sahara, the Subtropical regions to the South and the Arabic Peninsula. These mixed influences can be seen in many archaeological and historical features throughout the region, the rock art being no exception. Since the early stages of research in the 1930s, a strong relationship between the rock art in Ethiopia and the Arabian Peninsula was detected, leading to the establishment of the term *Ethiopian-Arabian* rock art by Pavel Červiček in 1971. This research thread proposes a progressive evolution from naturalism to schematism, ranging from the 4th-3rd millennium BC to the near past. Although the *Ethiopian-Arabian* proposal is still widely accepted and stylistic similarities between the rock art of Somalia, Ethiopia, Yemen or Saudi Arabia are undeniable, recent voices have been raised against the term because of its excessive generalisation and lack of operability. In addition, recent research to the south of Ethiopia have started to discover new rock art sites related to those found in Uganda and Kenya.\n\nRegarding the main themes of the Horn of Africa rock art, cattle depictions seem to have been paramount, with cows and bulls depicted either isolated or in herds, frequently associated with ritual scenes which show their importance in these communities. Other animals – zebus, camels, felines, dogs, etc. – are also represented, as well as rows of human figures, and fighting scenes between warriors or against lions. Geometric symbols are also common, usually associated with other depictions; and in some places they have been interpreted as tribal or clan marks. Both engraving and painting is common in most regions, with many regional variations. \n" - sys: id: 4XIIE3lDZYeqCG6CUOYsIG created_at: !ruby/object:DateTime 2015-11-25 19:04:53.913000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:55:12.472000000 Z content_type_id: image revision: 4 image: sys: id: 3ylztNmm2cYU0GgQuW0yiM created_at: !ruby/object:DateTime 2015-11-25 18:57:11.155000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:57:11.155000000 Z title: '2013,2034.15749' description: url: "//images.ctfassets.net/xt8ne4gbbocd/3ylztNmm2cYU0GgQuW0yiM/3be240bf82adfb5affc0d653e353350b/2013_2034.15749.jpg" caption: Painted roof of rock shelter showing decorated cows and human figures. <NAME>, Somaliland. 2013,2034.15749 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3691391 - sys: id: 2IKYx0YIVOyMSwkU8mQQM created_at: !ruby/object:DateTime 2015-11-25 19:18:28.056000000 Z updated_at: !ruby/object:DateTime 2015-12-11 11:26:13.401000000 Z content_type_id: chapter revision: 2 title_internal: 'East Africa: regional, chapter 11' body: |- Rock art in the Horn of Africa faces several challenges. One of them is the lack of consolidated chronologies and absolute dating for the paintings and engravings. Another is the uneven knowledge of rock art throughout the region, with research often affected by political unrest. Therefore, distributions of rock art in the region are steadily growing as research is undertaken in one of the most interactive areas in East Africa. The rock art of Central and East Africa is one of the least documented and well understood of the corpus of African rock art. However, in recent years scholars have undertaken some comprehensive reviews of existing sites and surveys of new sites to open up the debates and more fully understand the complexities of this region. citations: - sys: id: 7d9bmwn5kccgO2gKC6W2Ys created_at: !ruby/object:DateTime 2015-11-25 19:08:04.014000000 Z updated_at: !ruby/object:DateTime 2017-12-19 12:24:18.659000000 Z content_type_id: citation revision: 2 citation_line: "<NAME>. 1996. ‘Cultural Patterns in the Rock Art of Central Tanzania.’ in *The Prehistory of Africa*. XIII International Congress of Prehistoric and Protohistoric Sciences Forli-Italia-8/14 September.\n\nČerviček, P. 1971. ‘Rock paintings of Laga Oda (Ethiopia)’ in *Paideuma*, 17, pp.121-136.\n\nClark, <NAME>. 1954. *The Prehistoric Cultures of the Horn of Africa*. New York: Octagon Press.\n\nClark, J.C.D. 1959. ‘Rock Paintings of Northern Rhodesia and Nyasaland’, in Summers, R. (ed.) *Prehistoric Rock Art of the Federation of Rhodesia & Nyasaland*: Glasgow: National Publication Trust, pp.163- 220.\n\nJoussaume, R. (ed.) 1995. Tiya, *l’Ethiopie des mégalithes : du biface à l’art rupestre dans la Corne de l’Afrique*. Association des publications chauvinoises (A.P.C.), Chauvigny.\n\n<NAME>. 1983. *Africa’s Vanishing Art – The Rock Paintings of Tanzania*. London: Hamish Hamilton Ltd.\n\nMasao, F.T. 1979. *The Later Stone Age and the Rock Paintings of Central Tanzania*. Wiesbaden: Franz Steiner Verlag. \n\nNamono, Catherine. 2010. *A contextual interpretive approach to the rock art of Uganda*. Unpublished PhD Thesis. Johannesburg: University of Witwatersrand\n\nPhillipson, D.W. 1976. ‘The Rock Paintings of Eastern Zambia’, in *The Prehistory of Eastern Zambia: Memoir 6 of the british Institute in Eastern Africa*. Nairobi.\n\n<NAME>. (1995), Rock art in south-Central Africa: A study based on the pictographs of Dedza District, Malawi and Kasama District Zambia. dissertation. Cambridge: University of Cambridge, Unpublished Ph.D. dissertation.\n\n<NAME>. (1997), Zambia’s ancient rock art: The paintings of Kasama. Zambia: The National Heritage Conservation Commission of Zambia.\n\nSmith B.W. (2001), Forbidden images: Rock paintings and the Nyau secret society of Central Malaŵi and Eastern Zambia. *African Archaeological Review*18(4): 187–211.\n\n<NAME>. 2013, ‘Rock art research in Africa; in In: Lane, P. & Mitchell, P. (eds) *Handbook of African Archaeology*. Oxford: Oxford University Press, pp.145-162.\n\nTen Raa, E. 1974. ‘A record of some prehistoric and some recent Sandawe rock paintings’ in *Tanzania Notes and Records* 75, pp.9-27." background_images: - sys: id: 4aeKk2gBTiE6Es8qMC4eYq created_at: !ruby/object:DateTime 2015-12-07 19:42:27.348000000 Z updated_at: !ruby/object:DateTime 2017-12-19 12:25:55.914000000 Z title: '2013,2034.1298' description: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3592557 url: "//images.ctfassets.net/xt8ne4gbbocd/4aeKk2gBTiE6Es8qMC4eYq/31cde536c4abf1c0795761f8e35b255c/2013_2034.1298.jpg" - sys: id: 6DbMO4lEBOU06CeAsEE8aA created_at: !ruby/object:DateTime 2015-12-07 19:41:53.440000000 Z updated_at: !ruby/object:DateTime 2017-12-19 12:26:40.898000000 Z title: '2013,2034.15749' description: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3691391 url: "//images.ctfassets.net/xt8ne4gbbocd/6DbMO4lEBOU06CeAsEE8aA/9fc2e1d88f73a01852e1871f631bf4ff/2013_2034.15749.jpg" - sys: id: 2KyCxSpMowae0oksYsmawq created_at: !ruby/object:DateTime 2015-11-25 18:32:33.269000000 Z updated_at: !ruby/object:DateTime 2019-02-21 14:57:42.412000000 Z content_type_id: thematic revision: 5 title: 'The Country of the Standing Stones: Stela in Southern Ethiopia' slug: country-of-standing-stones lead_image: sys: id: 5N30tsfHVuW0AmIgeQo8Kk created_at: !ruby/object:DateTime 2015-11-25 18:01:40.103000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:01:40.103000000 Z title: ETHTBU0050002 description: url: "//images.ctfassets.net/xt8ne4gbbocd/5N30tsfHVuW0AmIgeQo8Kk/ad2ce21e5a6a89a0d4ea07bee897b525/ETHTBU0050002.jpg" chapters: - sys: id: 7lbvgOvsBO0sgeSkwU68K8 - sys: id: 3q8L69s3O8YOWsS4MAI0gk - sys: id: wMW6zfth1mIgEiSqIy04S - sys: id: 5BGRogcCPeYgq2SY62eyUk - sys: id: 3CBiLCh7ziUkMC264I4oSw - sys: id: 3OqDncSoogykaUgAyW0Mei - sys: id: 5NnJiqSSNGkOuooYIEYIWO - sys: id: 66kOG829XiiESyKSYUcOkI - sys: id: 66jbDvBWhykGwIOOmaYesY - sys: id: 3gftSkoIHSsmeCU6M8EkcE - sys: id: 41cBMB2SpOEqy0m66k64Gc - sys: id: 5DJsnYIbRKiAiOqYMWICau citations: - sys: id: 6LBJQl0eT62A06YmiSqc4W background_images: - sys: id: 3HHuQorm12WGUu0kC0Uce created_at: !ruby/object:DateTime 2015-11-25 18:02:09.630000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:02:09.630000000 Z title: ETHTBU0080002 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3HHuQorm12WGUu0kC0Uce/cf9d160fced55a45a8cb0cc9db8cbd54/ETHTBU0080002.jpg" - sys: id: 5zepzVfNDiOQy8gOyAkGig created_at: !ruby/object:DateTime 2015-11-25 18:02:34.369000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:02:34.369000000 Z title: ETHTBU0010003 description: url: "//images.ctfassets.net/xt8ne4gbbocd/5zepzVfNDiOQy8gOyAkGig/3131691f0940b7f5c823ec406b1acd03/ETHTBU0010003.jpg" country_introduction: sys: id: 1yZL5vCVKkSw0ue6EqCgm0 created_at: !ruby/object:DateTime 2017-12-12 00:55:17.028000000 Z updated_at: !ruby/object:DateTime 2017-12-12 00:55:17.028000000 Z content_type_id: country_information revision: 1 title: 'Nigeria: country introduction' chapters: - sys: id: 3fiSQDTIRakyMIookukQGA created_at: !ruby/object:DateTime 2017-11-16 17:47:22.283000000 Z updated_at: !ruby/object:DateTime 2017-11-17 17:49:16.694000000 Z content_type_id: chapter revision: 2 title: Introduction title_internal: 'Nigeria: country, chapter 1' body: In general, West Africa is not well known for its painted or engraved rock art and does not have a long history of rock art research. The scarcity of paintings may be predicated on the topography and more humid conditions of the climate, but the shortage of discovered sites to date may indicate that the paucity of evidence is genuine. Painted rock art occurs in the north of the country and comprises humpless cattle, monkeys, antelope and human figures, mainly painted in red. More unique sculptural forms include standing stones engraved with stylised faces and codified motifs, found to the south, and are reminiscent of the burial stelae at [Tuto Fela in Ethiopia](http://africanrockart.britishmuseum.org/#/article/country-of-standing-stones "Standing Stones of Ethiopia"). - sys: id: 2TEEwkKGBWa648eEAeik8O created_at: !ruby/object:DateTime 2017-11-17 17:51:57.172000000 Z updated_at: !ruby/object:DateTime 2017-11-17 17:51:57.172000000 Z content_type_id: chapter revision: 1 title: Geography and rock art distribution title_internal: 'Nigeria: country, chapter 2' body: Located in West Africa, the Federal Republic of Nigeria shares land borders with Benin in the west, Chad and Cameroon in the east, and Niger in the north. Its coastline lies in the south on the Gulf of Guinea in the Atlantic Ocean. The Niger and Benue River valleys make up Nigeria's most extensive region, merging into each other to form a distinctive 'Y' shape confluence. - sys: id: 5j33Z322RiqSIkgEa6W0MC created_at: !ruby/object:DateTime 2017-11-22 15:44:24.402000000 Z updated_at: !ruby/object:DateTime 2017-11-22 15:44:24.402000000 Z content_type_id: image revision: 1 image: sys: id: 1wpXiaFLE8kImw6a4O0yO8 created_at: !ruby/object:DateTime 2017-11-22 15:43:09.652000000 Z updated_at: !ruby/object:DateTime 2017-11-22 15:43:09.652000000 Z title: NIGCRMNAS0010006 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1wpXiaFLE8kImw6a4O0yO8/a299524cd0c60d521815d02eb3347c2f/NIGCRMNAS0010006.jpg" caption: View looking east from the Ikom area towards Cross River and the Cameroon border. 2013,2034.24321 © TARA/<NAME>son - sys: id: 4JWHrIYC4UgkUe2yqco4Om created_at: !ruby/object:DateTime 2017-11-22 15:56:27.091000000 Z updated_at: !ruby/object:DateTime 2017-11-22 16:05:16.491000000 Z content_type_id: chapter revision: 2 title_internal: 'Nigeria: country, chapter 3' body: 'Nigeria boasts a variety of landscapes - mangrove forests and swamps border the southern coastline; plains rise to the north of the valleys; rugged highlands are located in the southwest and to the southeast of the Benue River; hills and mountains extend to the border with Cameroon. Between the far south and far north is a vast savannah made up of three zones: the Guinean forest-savanna mosaic, the Sudanian savannah, and the Sahel savannah. Painted rock art is located in the northwest of the country, in the savannah zone, while engraved standing stones can be found in the more forested southeast.' - sys: id: 3kIQbhZ4xOgKeKqEwuoeOg created_at: !ruby/object:DateTime 2017-11-22 16:23:30.974000000 Z updated_at: !ruby/object:DateTime 2017-11-22 16:23:30.974000000 Z content_type_id: image revision: 1 image: sys: id: 6EygE2u9DUWkOAmoMayOQQ created_at: !ruby/object:DateTime 2017-11-22 16:21:19.288000000 Z updated_at: !ruby/object:DateTime 2017-11-22 16:21:19.288000000 Z title: NIGCRMNAS0010004 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6EygE2u9DUWkOAmoMayOQQ/b02ac0c0e9384d4c9e144434e63e8369/NIGCRMNAS0010004.jpg" caption: Boatman at Ofun-Nta, a seaport during the early years of trade on the Cross River. 2013,2034.24319 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/search.aspx?people=197356&place=37854 - sys: id: 8Gp0HoIrfiQUQGaMKmwO2 created_at: !ruby/object:DateTime 2017-11-22 16:56:06.115000000 Z updated_at: !ruby/object:DateTime 2017-11-22 16:56:06.115000000 Z content_type_id: chapter revision: 1 title: History of the research title_internal: 'Nigeria: country, chapter 4' body: | The existence of carved standing stones in Cross River State was first reported by an Officer of the British Administration in 1905 (Allison, 1967). In the 1960s, <NAME> undertook extensive surveying in the area, resulting in a major publication by the Nigerian Department of Antiquities in 1968. Research was undertaken in the run up to the Nigerian Civil War (also known as the Biafran War 1967-1970), during the course of which many of the monoliths were stolen and made their way on the international antiquities market. Today a number of these monoliths can be found in American and European museums, including [an example](http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=611818&partId=1&searchText=ikom&images=on&page=1) from the British Museum. The painted rock art found in the northeastern region of the country was first systematically studied and documented in the late 1950s. In 1964, the site of Birnin Kudu, in present-day Jigawa State was declared a National Historical Monument, as a means to promote tourism in the country. Unfortunately, criticism that the site has not been well-maintained or managed has impeded tourism development (Mangut and Mangut, 2012:37). - sys: id: Bhiu5cJqUgQCmwWuIMsKG created_at: !ruby/object:DateTime 2017-12-12 00:29:36.099000000 Z updated_at: !ruby/object:DateTime 2017-12-12 00:29:36.099000000 Z content_type_id: chapter revision: 1 title: Themes title_internal: 'Nigeria: country, chapter 5' body: "Painted rock art sites in northern Nigeria are often located adjacent to lithophones, also known as rock gongs - these are rocks and boulders that were used as percussion instruments. Painted rock art and lithophones occur systematically at Birnin Kudu, “where the lithophones produce eleven different notes“ and are associated with female rituals that precede marriage (Le Quellec, 2004:74). Depictions consist of humpless cattle and sheep as well as geometric signs. Although the original artists and meaning of the rock art are not known, local communities recognise them today as sacred sites and the images are thought to be associated with [shamanic activities](http://www.bradshawfoundation.com/africa/nigeria/birnin_kudu/index.php \"Documenting Rock Art in Nigeria Bradshaw Foundation\"). \n\nIn northern Nigeria, the painted rock art at Shira in Bauchi State consists of two traditions: naturalistic, consisting of humans and cattle with suckling calves, and anthropomorphic images. Paintings are usually executed in dark red on steep rock faces or overhangs (Mangut and Mangut, 2012:36). Anthropomorphic images have been found nearby at Geji and Birnin Kudu, and are associated with marriage and initiation (Vaughan, 1962). Also at Geji, subject matter is quite varied including humpless long-horned cattle, monkeys, horse, human figures and antelope. These are painted in three different styles, as solid figures, in outline, and outline and stripe (Mangut and Mangut, 2012:37).\n" - sys: id: F5aTJf3MqWMgUeuIsUMIY created_at: !ruby/object:DateTime 2017-12-12 00:47:57.513000000 Z updated_at: !ruby/object:DateTime 2017-12-12 00:47:57.513000000 Z content_type_id: chapter revision: 1 title: Meaning title_internal: 'Nigeria: country, chapter 6' body: | In the Marghi region, paintings are made with reddish clay that is found at the bottom of the river during the dry season. Cooked to enhance the brightness of the pigment it is mixed with karite butter. The clay is however rare and as such expensive, so poorer families replace the clay with charcoal ashes, resulting in black pigments. Thus, the differences seen in the colours used for rock paintings are “not related to chronology or symbolism but only to social status” (Le Quellec, 2004:77). Near Geji, there is a rock shelter known as <NAME>, that is visited by Fulani herders during the rainy season who peck the existing rock paintings to retrieve the pigment. The pigment is mixed with food for both humans and cattle and is consumed to protect “the fertility of the herd and the prosperity of the herders” (Le Quellec, 2004:77). The villagers of Geji did not presume these paintings had been made by humans but had appeared naturally from the rock, and if damaged or destroyed by pecking would reappear the next day (Le Quellec, 2004:79). Unfortunately, such practices have resulted in permanent damage or destruction of rock art. - sys: id: 5zxzzlmp2wSkAA82ukiEme created_at: !ruby/object:DateTime 2017-12-12 00:49:31.706000000 Z updated_at: !ruby/object:DateTime 2017-12-12 00:49:31.706000000 Z content_type_id: chapter revision: 1 title: Chronology title_internal: 'Nigeria: country, chapter 7' body: Based on the depictions of both long and short-horned humpless cattle at Birnin Kudu, it has been suggested that paintings predate the introduction of humped cattle into northern Nigeria, and may be at least a thousand years old (Shaw 1978). However, depictions of horse at Geji have been used to suggest that painted rock art in Nigeria are no earlier than the 15th century BC (Mangut and Mangut, 2012:38). The engraved standing stones at Cross River are thought to be up to 1500 years old. citations: - sys: id: 5XzFExCZYA4mKGY0ua6Iwc created_at: !ruby/object:DateTime 2017-12-12 00:54:17.136000000 Z updated_at: !ruby/object:DateTime 2017-12-12 00:54:17.136000000 Z content_type_id: citation revision: 1 citation_line: "<NAME>. 2014. ‘Beyond Anthropological and Associational discourse- interrogating the minimalism of Ikom Monoliths as concept and found object art’, in \n*Global Journal of Arts Humanities and Social Sciences*, Vol.2, Issue 1, pp.67-84.\n\nAllison P. 1967. *Cross River State Monoliths*. Lagos: Department of Antiquities, Federal Republic of Nigeria.\n\nEsu, B. B. and Ukata, S. 2012. ‘Enhancing the tourism value of Cross River state monoliths and stone circles through geo-mapping and ethnographic study (part 1)’, in *Journal of Hospitality Management and Tourism*, Vol. 3(6), pp. 106-116.\n\nLe Quellec, J-L. 2004. *Rock Art in Africa: Mythology and Legend*. Paris: Flammarion.\n\nMangut, J. and <NAME>. 2012. ‘Harnessing the Potentials of Rock Art Sites in Birnin Kudu, Jigawa State, Nigeria for Tourism Development’, in *Journal of Tourism and Heritage*, Vol.1 No. 1 pp: 36-42.\n\nShaw, T. 1978. *Nigeria its Archaeology and Early History*. London: Thames and\nHudson.\n\nUNESCO. 2007. \ ‘<NAME>oliths’ UNESCO [Online], Available at: http://whc.unesco.org/en/tentativelists/5173/\n\nVaughan J. H. 1962. ‘Rock paintings and Rock gong among the Marghi of\nNigeria’ in *Man*, 62, pp:49-52.\n\n\n" background_images: - sys: id: 6ndlBNzj4kC4IyysaSk20Y created_at: !ruby/object:DateTime 2017-12-12 01:02:00.372000000 Z updated_at: !ruby/object:DateTime 2017-12-12 01:02:00.372000000 Z title: NIGCRM0040011 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6ndlBNzj4kC4IyysaSk20Y/a9e3b2d35c3e0ee55a93cef88d92b9e3/NIGCRM0040011.jpg" - sys: id: 1wBaFXQ6iY2igSUc0Qwm02 created_at: !ruby/object:DateTime 2017-12-12 01:52:33.766000000 Z updated_at: !ruby/object:DateTime 2017-12-12 01:52:33.766000000 Z title: NIGCRM0070021 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1wBaFXQ6iY2igSUc0Qwm02/9bf58633776be1e68afbcc3a2bdf0279/NIGCRM0070021.jpg" - sys: id: 1FTDyPet3WiyQYiq2UYEeu created_at: !ruby/object:DateTime 2017-12-12 01:49:44.361000000 Z updated_at: !ruby/object:DateTime 2017-12-12 01:49:44.361000000 Z title: NIGCRM0020001 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1FTDyPet3WiyQYiq2UYEeu/5691015503e7f726f99676e2976ef569/NIGCRM0020001.jpg" region: Eastern and central Africa ---<file_sep>/script/cibuild #!/usr/bin/env bash # halt script on error set -e bundle exec rake build:prod bundle exec rake test:prod<file_sep>/_coll_country/namibia/twyfelfontein.md --- breadcrumbs: - label: Countries url: "../../" - label: Namibia url: "../" layout: featured_site contentful: sys: id: 2KwE2LvwScQG6CmU4eM2uw created_at: !ruby/object:DateTime 2016-09-26 14:56:44.920000000 Z updated_at: !ruby/object:DateTime 2016-09-26 14:56:44.920000000 Z content_type_id: featured_site revision: 1 title: Twyfelfontein, Namibia slug: twyfelfontein chapters: - sys: id: 8m8JIwGB9YyiOoIaeIsS2 created_at: !ruby/object:DateTime 2016-09-26 14:54:19.760000000 Z updated_at: !ruby/object:DateTime 2016-09-26 14:54:19.760000000 Z content_type_id: chapter revision: 1 title_internal: 'Namibia: featured site, chapter 1' body: 'The proliferation of rock engravings at Twyfelfontein | /Ui-//aes in the north-west of central Namibia, forms the largest single grouping of ancient engraved images in southern Africa. Covering about 57 hectares in the core area and home to over 2,000 engravings, the rock art sites are situated near a small but permanent spring. The site was first formally noted by <NAME> in a 1921 report to the Administrator of South West Africa, following a report to him from a surveyor named Volkmann mentioning the engravings, near a spring Volkmann named as Uais (/Ui-//aes= place among rocks or jumping waterhole in Khoekhoegowab, the language of the local Damara people). Later, the land came into the use of farmer <NAME>, whose concern over the survival of the spring led ultimately to its being referred to as Twyfelfontein (‘doubtful spring’ in Afrikaans). In 1963 <NAME> visited the site as part of his work to record rock art sites throughout South West Africa. Scherz documented around 2,500 images in the wider valley area, while a 2005 survey of the core site found 2,075 individual images on 235 separate rock surfaces. ' - sys: id: guZseTx3LaEuKOia8Yuei created_at: !ruby/object:DateTime 2016-09-26 14:54:31.866000000 Z updated_at: !ruby/object:DateTime 2018-05-10 13:43:41.409000000 Z content_type_id: image revision: 2 image: sys: id: 4CdBm63EZaG0uscOGAOimI created_at: !ruby/object:DateTime 2016-09-26 14:54:28.378000000 Z updated_at: !ruby/object:DateTime 2016-09-26 14:54:28.378000000 Z title: '1' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4CdBm63EZaG0uscOGAOimI/e0f06c9a18388056521cd57dc8e096aa/1.jpg" caption: Engravings of animals including giraffe, elephant and rhinoceros showing the surrounding sandstone. Twyfelfontein | /Ui-//aes, Namibia. 2013,2034.23755 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3772379&partId=1&searchText=2013,2034.23755&page=1 - sys: id: 6vS54wtOMwQ0Ce4w2s0Wa0 created_at: !ruby/object:DateTime 2016-09-26 14:54:37.644000000 Z updated_at: !ruby/object:DateTime 2016-09-26 14:54:37.644000000 Z content_type_id: chapter revision: 1 title_internal: 'Namibia: featured site, chapter 2' body: The engravings are found in several loose conglomerations, on sandstone surfaces at the base of a hill scarp within the basin of the ephemeral Huab River, while the few painted panels in the area are found on the underside of sandstone rock overhangs. The engraved images are pecked and/or ground/polished and are made in a variety of styles, with ubiquitous geometric patterns of cross-hatched, looped and linear forms, as well as circles and polished depressions and cupules. In addition there are numerous depictions of animals, ranging in style from more naturalistic to stylised and distorted. Chief among the animal images is the giraffe, which is most numerous. Also common are images of rhinoceroses, zebra, gemsbok antelope and ostriches. There are occasional depictions of cattle but images of human beings are almost absent. Also featured are images of human footprints and animal spoor (hoof and paw prints). - sys: id: 5AxeKFL1lYm4Oqm2wG2eow created_at: !ruby/object:DateTime 2016-09-26 14:54:49.830000000 Z updated_at: !ruby/object:DateTime 2018-05-10 13:44:40.593000000 Z content_type_id: image revision: 2 image: sys: id: 4TZJHdTWc0kgOOEqek4OUs created_at: !ruby/object:DateTime 2016-09-26 14:54:46.709000000 Z updated_at: !ruby/object:DateTime 2016-09-26 14:54:46.709000000 Z title: NAMDMT0010096 description: url: "//images.ctfassets.net/xt8ne4gbbocd/4TZJHdTWc0kgOOEqek4OUs/f55aa0aabccb385ac37c124564f330e7/NAMDMT0010096.jpg" caption: 'Engraved giraffes showing a pecked shading technique. Twyfelfontein | /Ui-//aes, Namibia. 2013,2034.22118 © TARA/<NAME> ' col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3763224&partId=1&searchText=2013,2034.22118&page=1 - sys: id: 6gb3MFviE0sMWWy4s2UQGi created_at: !ruby/object:DateTime 2016-09-26 14:55:05.395000000 Z updated_at: !ruby/object:DateTime 2016-09-30 17:03:01.797000000 Z content_type_id: chapter revision: 3 title_internal: 'Namibia: featured site, chapter 3' body: The figurative images in the engraved art feature several different distinct styles, ranging from very naturalistic outlines of animals such as giraffes and rhinoceroses, through carefully delineated but stylised or distorted renditions of these animals with exaggerated extremities, to very schematic pecked outlines. One particular aspect of style is a form of relief engraving, whereby in some deeply pecked figures' muscle masses are delineated. In others, the infill pecking is graded and sparser in the centre of a figure, giving the impression of shading. A few of the engravings are highly polished. Perhaps most renowned among these is the “dancing kudu” image, a stylised image of a kudu antelope cow rendered atop a flat slab of rock and surrounded by geometric shapes. - sys: id: 5sBqpeSh9uUUosCg2IikCu created_at: !ruby/object:DateTime 2016-09-26 14:55:17.975000000 Z updated_at: !ruby/object:DateTime 2016-09-26 14:55:17.975000000 Z content_type_id: image revision: 1 image: sys: id: XPX1r31GCsUmOaAIIMQy8 created_at: !ruby/object:DateTime 2016-09-26 14:55:14.554000000 Z updated_at: !ruby/object:DateTime 2016-09-26 14:55:14.554000000 Z title: NAMDMT0010076 description: url: "//images.ctfassets.net/xt8ne4gbbocd/XPX1r31GCsUmOaAIIMQy8/c9899e3e4af9424a8bec265ed775b558/NAMDMT0010076.jpg" caption: Highly polished engraved kudu cow with geometric engravings. Twyfelfontein | /Ui-//aes, Namibia. 2013,2034.22098 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3763207&partId=1&searchText=+2013,2034.22098&page=1 - sys: id: 16KMXlLrLAiU2mqWAscMCo created_at: !ruby/object:DateTime 2016-09-26 14:55:26.702000000 Z updated_at: !ruby/object:DateTime 2016-09-26 14:55:26.702000000 Z content_type_id: chapter revision: 1 title_internal: 'Namibia: featured site, chapter 4' body: "It appears that the kudu figure is pregnant and it has been suggested that the choice of this animal may have been made in relation to female initiation practices. This is because the female kudu has a symbolic importance relating to women’s behaviour in the cosmology of some San&#124;Bushman¹ people, traditionally hunter-gatherer people whose ancestors are thought to have made most of southern Africa’s rock paintings and engravings. Other animals known to have symbolic and metaphorical significance to San&#124;Bushman people are also depicted here (giraffe images are most numerous) and these images have been interpreted in the vein of other southern African rock art sites, where images are thought to reflect the experiences of shamans while in a trance state, and may have multiple metaphorical and other cultural meanings. \n\nThe engravings were certainly made in strategic locations and not simply on any available rock surface, with some images having been deliberately made in places that are difficult to reach and to see. The reason for this is unclear, though it has been suggested that such placement might be in relation to the images serving a preparatory function for shamans preparing to enter a trance. Some of the engravings have exaggerated features such as elongated limbs and extremities which may reflect trance experience. One of the engravings appears to depict a lion with pugmarks (paw prints) instead of feet and third at the end of the tail. Each of those in the feet have five instead of the correct four pads and this has been interpreted as meaning that the figure represents a human shaman in trance who has taken on lion form. A similar suggestion has been made regarding the frequent depictions of ostriches (Kinahan, 2006). \n\n¹ San&#124;Bushmen is a collective term used to describe the many different hunter-gatherer-fisher groups living in southern Africa who have related languages and cultural traditions. Both 'San' and 'Bushmen' are considered offensive terms by some members of these groups, although others have positively adopted them.\n" - sys: id: 7264zOqUmIAMsgq4QKMgOE created_at: !ruby/object:DateTime 2016-09-26 14:55:40.171000000 Z updated_at: !ruby/object:DateTime 2018-05-10 13:45:12.694000000 Z content_type_id: image revision: 3 image: sys: id: 5qTBuuWKukMoO4kcQYiQWa created_at: !ruby/object:DateTime 2016-09-26 14:47:45.908000000 Z updated_at: !ruby/object:DateTime 2016-09-26 14:47:45.908000000 Z title: NAMDMT0020004 description: url: "//images.ctfassets.net/xt8ne4gbbocd/5qTBuuWKukMoO4kcQYiQWa/9b1c7477a36f65573bca76410c122d3f/NAMDMT0020004.jpg" caption: Painted human figures and an ostrich. Twyfelfontein | /Ui-//aes, Namibia. 2013,2034.22122 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3763727&partId=1&searchText=2013,2034.22122+&page=1 - sys: id: 5wA7wWhUVaEywmwauICIiK created_at: !ruby/object:DateTime 2016-09-26 14:55:53.771000000 Z updated_at: !ruby/object:DateTime 2016-09-26 14:55:53.771000000 Z content_type_id: chapter revision: 1 title_internal: 'Namibia: featured site, chapter 5' body: "Such interpretations are made on the basis that the artists followed the same cultural tradition as the ancestral San&#124;Bushman. The few examples of painted rock art at the site certainly appear to conform to the hunter-gatherer tradition found elsewhere in Namibia. Following this approach, the geometric engraved forms may be interpreted as illustrative of so-called ‘entoptic’ phenomena: shapes and patterns observed when entering a trance state, though an alternative origin for some of the geometrics with particular line and circle motifs has also been suggested. This proposal suggests that they were made by ancestral Khoenkhoen herder people, rather than hunter-gatherers, perhaps in relation to initiation practices. \n\nAttempting to date or sequence the images based on superimpositioning or patina is difficult – superimposition of engravings at the site is rare and a range of patination colours seem to indicate these works having been created over a wide timescale, though it has been noted that a certain style of spoor images sometimes overlie some of the animal figures, indicating that this is a younger tradition. Archaeological fieldwork around the site undertaken in 1968 by <NAME> recovered evidence of occupation including stone tools, worked ostrich eggshell and stone structures. The dates recovered from radiocarbon dating ranged widely from c.5,850-180 BP (years before present). The relationship between periods of occupation/site use and the production of rock art is not known, but based on archaeological evidence from around the wider area it is thought that engravings in the styles found at Twyfelfontein range from around 6,000 to around 1,000 years old, though some may be more recent.\n" - sys: id: 6uFGb5fXZ6yEESYw6C4S0C created_at: !ruby/object:DateTime 2016-09-26 14:56:10.408000000 Z updated_at: !ruby/object:DateTime 2016-09-26 14:56:10.408000000 Z content_type_id: image revision: 1 image: sys: id: 6AdC84mjBuuGMsQo2oCCYo created_at: !ruby/object:DateTime 2016-09-26 14:56:05.842000000 Z updated_at: !ruby/object:DateTime 2016-09-26 14:56:05.842000000 Z title: NAMDMT0040014 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6AdC84mjBuuGMsQo2oCCYo/27ba7c664835ba741ab1f4aa43582f1e/NAMDMT0040014.jpg" caption: Engraved panel showing the figures of giraffe and other animals, rows of dots, hoof prints and hand prints showing the range of juxtapositioning and superimposition at the site. Twyfelfontein | /Ui-//aes, Namibia. 2013,2034.22143 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3763757&partId=1&searchText=2013,2034.22143&page=1 - sys: id: 68rfcJmZDaAKGU0WAAysU0 created_at: !ruby/object:DateTime 2016-09-26 14:56:16.915000000 Z updated_at: !ruby/object:DateTime 2016-09-26 14:56:16.915000000 Z content_type_id: chapter revision: 1 title_internal: 'Namibia: featured site, chapter 6' body: 'In 1952 the site was made a National Monument and in 2007 Twyfelfontein | /Ui-//aes was inscribed on the UNESCO World Heritage list. Portions of it are currently open to the public for supervised visits and tours. ' citations: - sys: id: 2IwYq7P2DuyykIC6iwciC0 background_images: - sys: id: 1awSXvy0R0IsIOu2IeqEeK created_at: !ruby/object:DateTime 2016-09-26 14:56:32.301000000 Z updated_at: !ruby/object:DateTime 2016-09-26 14:56:32.301000000 Z title: NAMDMT0040003 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1awSXvy0R0IsIOu2IeqEeK/fccea4215104a2f0d107c85e2bf2abf4/NAMDMT0040003.jpg" - sys: id: 7eyjgnirUkqiwIQmwc8uoe created_at: !ruby/object:DateTime 2016-09-26 14:56:40.370000000 Z updated_at: !ruby/object:DateTime 2016-09-26 14:56:40.370000000 Z title: NAMDMT0010062 description: url: "//images.ctfassets.net/xt8ne4gbbocd/7eyjgnirUkqiwIQmwc8uoe/827acd6affabc436c4124be861493437/NAMDMT0010062.jpg" ---<file_sep>/_coll_country/kenya.md --- contentful: sys: id: 20R5BacInqWCOAss00yQYs created_at: !ruby/object:DateTime 2015-11-26 18:44:17.012000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:09:13.279000000 Z content_type_id: country revision: 12 name: Kenya slug: kenya col_url: http://www.britishmuseum.org/research/collection_online/search.aspx?people=197356&place=40899 map_progress: true intro_progress: true image_carousel: - sys: id: QcwzqQBmEuGWGqC8yKYEM created_at: !ruby/object:DateTime 2015-12-08 18:21:55.079000000 Z updated_at: !ruby/object:DateTime 2019-02-12 02:09:37.621000000 Z title: '2013,2034.14238' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3685727&partId=1&searchText=KENVIC0010004&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/QcwzqQBmEuGWGqC8yKYEM/18c3688b65a4a7c3e395e86ced3eec07/KENVIC0010004_1.jpg" - sys: id: 4egfSRDx3qCckaKuOsOOMC created_at: !ruby/object:DateTime 2015-12-08 18:21:55.087000000 Z updated_at: !ruby/object:DateTime 2019-02-12 02:11:24.671000000 Z title: '2013,2034.13018' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3700186&partId=1&searchText=KENLAI0060017&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/4egfSRDx3qCckaKuOsOOMC/7acacc9bb5777123390902f431833a08/KENLAI0060017_1.jpg" featured_site: sys: id: 2kZmXHcYEkaWQGMK4sGq0Y created_at: !ruby/object:DateTime 2015-11-25 12:47:03.425000000 Z updated_at: !ruby/object:DateTime 2015-12-08 18:51:10.317000000 Z content_type_id: featured_site revision: 6 title: Mfangano Island, Kenya slug: mfangano-island chapters: - sys: id: 4ffcl2AJFuUmcS2oykeieO created_at: !ruby/object:DateTime 2015-11-25 13:54:02.102000000 Z updated_at: !ruby/object:DateTime 2015-11-25 13:54:02.102000000 Z content_type_id: chapter revision: 1 title_internal: 'Kenya: featured site, chapter 1' body: 'Lake Victoria is the largest lake in Africa, and at 69,484km², the second largest in the world by surface area. Sitting in a depression in the plateau between the eastern and western valley branches of the geological East African Rift System, its shores are in Uganda, Tanzania, and to the south-east, in Kenya. Mfangano Island, rising 300m out of the lake near the Kenyan shore, is home to some of the most prominent rock painting sites in the country, featuring abstract patterned paintings thought to have been created between 1,000 and 4,000 years ago by hunter-gatherers. The rock paintings on Mfangano Island are found at two principal sites: in a cave near the sea known as Mawanga, and at a rock shelter further inland called Kwitone.' - sys: id: Ak4bSLKQyOCQESmSuukEk created_at: !ruby/object:DateTime 2015-11-25 12:47:44.566000000 Z updated_at: !ruby/object:DateTime 2017-01-23 16:45:35.105000000 Z content_type_id: image revision: 4 image: sys: id: 37G9MkkxFuC0mu6qGwcs2y created_at: !ruby/object:DateTime 2015-12-08 18:49:22.433000000 Z updated_at: !ruby/object:DateTime 2015-12-08 18:49:22.433000000 Z title: KENVIC0010032 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/37G9MkkxFuC0mu6qGwcs2y/20dfc41bbaef46d2cc5b733269b032ce/KENVIC0010032_1.jpg" caption: Lake Victoria. 2013,2034.14266 © <NAME>/TARA. col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3692066&partId=1&searchText=2013,2034.14266&page=1 - sys: id: 3MSOAnbnKoq0ACuaYEK0AK created_at: !ruby/object:DateTime 2015-11-25 13:55:03.942000000 Z updated_at: !ruby/object:DateTime 2015-11-25 13:55:03.942000000 Z content_type_id: chapter revision: 1 title_internal: 'Kenya: featured site, chapter 2' body: Mawanga is a roughly triangular limestone cavern, about 18m wide across the mouth and 12m deep. The roof slopes sharply to the back towards a raised platform against the rear of the left wall, on which 12 images of concentric circles and spirals in white and red have been painted. Kwitone has similar paintings, situated at one end of a long overhang in a sandstone cliff, below the shoulder of a ridge. The rock art at Kwitone is at the far end on the shelter wall, several metres above a cleared floor section. The paintings here feature 11 distinct shapes including concentric circles and oblongs. One of these is a prominent sunburst pattern in brown, with rays emanating from the outermost band. The images are larger than those at Mawanga, averaging around 40cm in diameter, and less faded, exhibiting more brown pigment, although both sites appear to reflect the same artistic tradition. These are finger paintings, with pigment probably made of haematite or white clay mixed with a natural binder such as egg white or urine. There is evidence that the surface may also have also been prepared prior to painting, by polishing, and that some of the images may have reapplied or retouched over time. - sys: id: 2W5cMhvviwo6OEMc04u40E created_at: !ruby/object:DateTime 2015-11-25 12:49:05.022000000 Z updated_at: !ruby/object:DateTime 2017-01-23 16:46:53.507000000 Z content_type_id: image revision: 3 image: sys: id: 4RTDlc6IOIikMaMg8mQaoc created_at: !ruby/object:DateTime 2015-12-08 18:49:43.951000000 Z updated_at: !ruby/object:DateTime 2015-12-08 18:49:43.951000000 Z title: KENVIC0020005 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/4RTDlc6IOIikMaMg8mQaoc/2572f0ad5751cb16ffb281daccfc39d3/KENVIC0020005_1.jpg" caption: Painted panel at Mawanga Cave. 2013,2034.14278 © <NAME>/TARA. col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3692333&partId=1&searchText=2013,2034.14278&page=1 - sys: id: 5yjxz7az7yYSQi2u4UQaIk created_at: !ruby/object:DateTime 2015-11-25 12:49:47.517000000 Z updated_at: !ruby/object:DateTime 2017-01-23 16:47:08.898000000 Z content_type_id: image revision: 3 image: sys: id: 516BFdHg1G4yO6IkWOQimW created_at: !ruby/object:DateTime 2015-12-08 18:49:43.951000000 Z updated_at: !ruby/object:DateTime 2015-12-08 18:49:43.951000000 Z title: KENVIC0010001 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/516BFdHg1G4yO6IkWOQimW/7c7491674484c9ae4d39ccc06d98b6be/KENVIC0010001_1.jpg" caption: Spiral and sunburst at Kwitone. 2013,2034.14250 © <NAME>/TARA. col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3685756&partId=1&searchText=2013,2034.14250&page=1 - sys: id: 2UpIfZaJVSIyUweYYKak64 created_at: !ruby/object:DateTime 2015-11-25 13:55:35.312000000 Z updated_at: !ruby/object:DateTime 2015-11-25 13:55:35.312000000 Z content_type_id: chapter revision: 1 title_internal: 'Kenya: featured site, chapter 3' body: The circular shapes seen here are typical of an apparent wider East and Central African rock art tradition featuring a preponderance of circular motifs, usually attributed to people known as the Batwa, a Bantu-origin name for a series of culturally related groups historically living around Africa’s Great Lakes region and more widely throughout Central Africa. Like the San people, who are known to have been the creators of most of the famous rock art of Southern Africa, Batwa were traditionally hunter-gatherers, and are considered the most ancient indigenous populations of the area. In the early 20th century, it was proposed that East African rock art of this tradition could have been the work of ancestral San people, but it is now generally assumed to be of Batwa origin with, for example, possible parallels to be seen in the symbolic iconography with contemporary barkcloth designs of the related Mbuti people from the Democratic Republic of Congo (Namono, 2010). - sys: id: 1AWKNMNRSImMCASQusuWc0 created_at: !ruby/object:DateTime 2015-11-25 12:50:25.070000000 Z updated_at: !ruby/object:DateTime 2017-01-23 17:17:59.954000000 Z content_type_id: image revision: 3 image: sys: id: 2wD915QEYQqsQCCyEusyoW created_at: !ruby/object:DateTime 2015-12-08 18:49:35.128000000 Z updated_at: !ruby/object:DateTime 2015-12-08 18:49:35.128000000 Z title: UGAVIC0060005 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/2wD915QEYQqsQCCyEusyoW/1d5d5b96ebac21badfaaa87cbb154ca5/UGAVIC0060005_1.jpg" caption: "“Dumbbell” shapes at nearby Lolui Island. 2013,2304.15306 © David Coulson/TARA." col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3691242&partId=1 - sys: id: 7KbMWDFuY8CwgkwiQuiWew created_at: !ruby/object:DateTime 2015-11-25 13:56:16.375000000 Z updated_at: !ruby/object:DateTime 2015-11-25 13:56:16.375000000 Z content_type_id: chapter revision: 1 title_internal: 'Kenya: featured site, chapter 4' body: 'Further examples of apparently Batwa origin rock art can be seen in neighbouring Uganda and Tanzania, a reminder that contemporary political borders do not reflect physical partitions in the spatial coverage of rock art traditions. Lolui Island, about 50km north west of Mfangano Island and in Ugandan waters, is another important Lake Victoria rock art environment, featuring both painting sites and rock gongs (sonorous natural percussive instruments with the wear of use) which seem to be associated with the painting sites. There are also numerous sets of cupules—ground circular depressions in the rocks. Some of these are referred to locally as Omweso, due to their bearing some resemblance to the depressions used for holding gaming pieces in the so-named local variant of the Mancala-type board games played widely throughout eastern Africa. However, their original significance and use is unknown. Cupule sites are also found on the Kenyan mainland and on Mfangano island. Many of these are clearly anthropogenic, however an unusual phenomenon is to be noted in the spectacular array of naturally formed cupule-like depressions in the limestone of Mawanga cave. This may remind us to exercise caution in ascribing ‘rock art’ status to all apparently patterned rock formations. The cause of these multitudinous small depressions is so far unknown. ' - sys: id: 5j3ZVzX81O8qs44GE4i6Oa created_at: !ruby/object:DateTime 2015-11-25 12:51:05.574000000 Z updated_at: !ruby/object:DateTime 2017-01-23 17:18:53.166000000 Z content_type_id: image revision: 3 image: sys: id: iF8lN8WDzqKWeu2OUQ8gc created_at: !ruby/object:DateTime 2015-12-08 18:49:22.434000000 Z updated_at: !ruby/object:DateTime 2015-12-08 18:49:22.434000000 Z title: KENVIC0020012 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/iF8lN8WDzqKWeu2OUQ8gc/1ea0ae4e085ae7da13cb701cb35493c5/KENVIC0020012_1.jpg" caption: Natural “cupules”, Mawanga Cave. 2013,2034.14285 © <NAME>/TARA. col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3692304&partId=1&searchText=2013,2034.14285&page=1 - sys: id: 1MO5OjJiaQyeUYEkA0ioOi created_at: !ruby/object:DateTime 2015-11-25 13:57:11.093000000 Z updated_at: !ruby/object:DateTime 2015-11-25 13:57:11.093000000 Z content_type_id: chapter revision: 1 title_internal: 'Kenya: featured site, chapter 5' body: 'The rock art sites of the eastern Lake Victoria region retain spiritual connotations for the communities living around them, even if their denoted modern significance differs from that envisioned by the original artists. The modern inhabitants of Mfangano Island are the Abasuba people, a Bantu language-speaking group unrelated to the Batwa who have nevertheless appropriated the sites as arenas of spiritual importance. Members of the Wasamo clan in the area around Mawanga remember their having used the site for rain making rituals until a few decades ago, with red and white pigment apparently representing the moon and sun respectively. Soot on the cave roof may indicate other recent human activity there. When the archaeologist <NAME>—who first investigated the Kwitone site in the 1960s—visited it later, he was told by local Wagimbe clan people that they also held the paintings there to be associated with some taboos, and connected it with ancestor worship. These beliefs reflect events of the recent past, as the Abasuba only moved into the area in the last 400 years. This followed an earlier occupation by Luo peoples, prior to which habitation by the Batwa is assumed. The local importance of the sites is highlighted in their stewardship by the Abasuba Peace Museum, which fosters a continuing relationship with the sites and those who live around them. ' - sys: id: 38TIUovoUMimQ6G4UmiCOS created_at: !ruby/object:DateTime 2015-11-25 12:51:38.839000000 Z updated_at: !ruby/object:DateTime 2017-01-23 17:19:17.336000000 Z content_type_id: image revision: 3 image: sys: id: 4QK41OYhpSa0qogICAW2aQ created_at: !ruby/object:DateTime 2015-12-08 18:49:22.436000000 Z updated_at: !ruby/object:DateTime 2015-12-08 18:49:22.436000000 Z title: KENVIC0010039 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/4QK41OYhpSa0qogICAW2aQ/fddcfe64e7040cb2dfde96be8d043a2d/KENVIC0010039_1.jpg" caption: Sign leading to the rock art on Mfangano Island. 2013,2034.14273 © <NAME>/TARA. col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3692275&partId=1&searchText=2013,2034.14273&page=1 - sys: id: 6872dmGUjSMsOgWqW0GKOa created_at: !ruby/object:DateTime 2015-11-25 13:59:14.477000000 Z updated_at: !ruby/object:DateTime 2015-11-25 13:59:14.477000000 Z content_type_id: chapter revision: 1 title_internal: 'Kenya: featured site, chapter 6' body: In 2014, <NAME>, curator of the Abasuba Peace Museum, [visited The British Museum](http://www.britishmuseum.org/pdf/BM_Africa_Programme_Newsletter_spring_2015.pdf) for a training and skills exercise as part of the [Africa Programme](http://www.britishmuseum.org/about_us/skills-sharing/africa_programme.aspx), which works closely with national and independent museums across the continent to develop training initiatives. citations: - sys: id: t1Gh6AyCYKqaQ442MgGUI created_at: !ruby/object:DateTime 2015-11-25 12:52:31.875000000 Z updated_at: !ruby/object:DateTime 2015-11-25 12:52:31.875000000 Z content_type_id: citation revision: 1 citation_line: |- <NAME>. 1974. *The Prehistoric rock art of the lake Victoria region*. Azania, IX, 1-50. <NAME>, 2010. *Surrogate Surfaces: a contextual interpretive approach to the rock art of Uganda*. Unpublished PhD Thesis, Graduate School of Humanities, University of the Witwatersrand, Johannesburg Odede, <NAME>., <NAME>. & Agong, <NAME>. 2014. *Rock Paintings and Engravings in Suba Region along the Eastern Shores of Lake Victoria Basin*. Kenya International Journal of Business and Social Research, Issue 04, Volume 10 pp. 15-24 2014 background_images: - sys: id: 37G9MkkxFuC0mu6qGwcs2y created_at: !ruby/object:DateTime 2015-12-08 18:49:22.433000000 Z updated_at: !ruby/object:DateTime 2015-12-08 18:49:22.433000000 Z title: KENVIC0010032 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/37G9MkkxFuC0mu6qGwcs2y/20dfc41bbaef46d2cc5b733269b032ce/KENVIC0010032_1.jpg" - sys: id: iF8lN8WDzqKWeu2OUQ8gc created_at: !ruby/object:DateTime 2015-12-08 18:49:22.434000000 Z updated_at: !ruby/object:DateTime 2015-12-08 18:49:22.434000000 Z title: KENVIC0020012 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/iF8lN8WDzqKWeu2OUQ8gc/1ea0ae4e085ae7da13cb701cb35493c5/KENVIC0020012_1.jpg" key_facts: sys: id: 3IwY0pYKpOaGSUWK6aU8WW created_at: !ruby/object:DateTime 2015-11-27 15:25:45.996000000 Z updated_at: !ruby/object:DateTime 2015-11-27 15:25:45.996000000 Z content_type_id: country_key_facts revision: 1 title_internal: 'Kenya: key facts' image_count: 1381 images date_range: Mostly 1,000 BC to the 20th century main_areas: Throughout, particularly Turkana, the Laikipia Plateau and Lake Victoria techniques: Pecked engraving, finger painting main_themes: Geometric motifs and symbols, giraffe, cattle, occasionally modern items such as vehicles thematic_articles: - sys: id: 6h9anIEQRGmu8ASywMeqwc created_at: !ruby/object:DateTime 2015-11-25 17:07:20.920000000 Z updated_at: !ruby/object:DateTime 2015-12-07 20:49:54.244000000 Z content_type_id: thematic revision: 4 title: Geometric motifs and cattle brands slug: geometric-motifs lead_image: sys: id: 5yD7fOuAdU4cemkewCqCMO created_at: !ruby/object:DateTime 2015-11-25 16:56:44.778000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:56:44.778000000 Z title: '2013,2034.12976' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5yD7fOuAdU4cemkewCqCMO/4d203afb0318bee69decb23327864c79/2013_2034.12976.jpg" chapters: - sys: id: 5plObOxqdq6MuC0k4YkCQ8 created_at: !ruby/object:DateTime 2015-11-25 17:02:35.234000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:05:34.964000000 Z content_type_id: chapter revision: 3 title_internal: 'Geometric motifs: thematic, chapter 1' body: |- The rock art of eastern Africa is characterised by a wide range of non-figurative images, broadly defined as geometric. Occurring in a number of different patterns or designs, they are thought to have been in existence in this region for thousands of years, although often it is difficult to attribute the art to particular cultural groups. Geometric rock art is difficult to interpret, and designs have been variously associated with sympathetic magic, symbols of climate or fertility and altered states of consciousness (Coulson and Campbell, 2010:220). However, in some cases the motifs painted or engraved on the rock face resemble the same designs used for branding livestock and are intimately related to people’s lives and world views in this region. First observed in Kenya in the 1970s with the work of Gramly (1975) at Lukenya Hill and Lynch and Robbins (1977) at Namoratung’a, some geometric motifs seen in the rock art of the region were observed to have had their counterparts on the hides of cattle of local communities. Although cattle branding is known to be practised by several Kenyan groups, Gramly concluded that “drawing cattle brands on the walls of rock shelters appears to be confined to the regions formerly inhabited by the Maa-speaking pastoralists or presently occupied by them”&dagger;(Gramly, 1977:117). - sys: id: 71cjHu2xrOC8O6IwSmMSS2 created_at: !ruby/object:DateTime 2015-11-25 16:57:39.559000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:06:07.592000000 Z content_type_id: image revision: 2 image: sys: id: 5yD7fOuAdU4cemkewCqCMO created_at: !ruby/object:DateTime 2015-11-25 16:56:44.778000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:56:44.778000000 Z title: '2013,2034.12976' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5yD7fOuAdU4cemkewCqCMO/4d203afb0318bee69decb23327864c79/2013_2034.12976.jpg" caption: White symbolic designs possibly representing Maa clans and livestock brands, Laikipia, Kenya. 2013,2034.12976 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3693276&partId=1&searchText=2013,2034.12976&page=1 - sys: id: 36QhSWVHKgOeMQmSMcGeWs created_at: !ruby/object:DateTime 2015-11-25 17:03:05.920000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:03:05.920000000 Z content_type_id: chapter revision: 1 title: title_internal: 'Geometric motifs: thematic, chapter 2' body: In the case of Lukenya Hill, the rock shelters on whose walls these geometric symbols occur are associated with meat-feasting ceremonies. Meat-feasting shelters exist from northern Tanzania through Kenya to Lake Turkana, and are places where Maa-speaking initiated men, who are not permitted to eat meat in their homes, gather to kill and feast on animals, predominantly cattle. During or after feasting, symbols of the animals that had been eaten were painted on the shelter ceiling in white or less often red. Maa speakers brand their cattle and camels with symbols that signify the lineage of their owners, but may also indicate if an animal has been treated for a particular disease. Different symbols may be used for male and female animals. - sys: id: 4t76LZy5zaSMGM4cUAsYOq created_at: !ruby/object:DateTime 2015-11-25 16:58:35.447000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:07:35.181000000 Z content_type_id: image revision: 2 image: sys: id: 1lBqQePHxK2Iw8wW8S8Ygw created_at: !ruby/object:DateTime 2015-11-25 16:56:44.764000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:56:44.764000000 Z title: '2013,2034.12846' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1lBqQePHxK2Iw8wW8S8Ygw/68fffb37b845614214e96ce78879c0b0/2013_2034.12846.jpg" caption: View of the long rock shelter below the waterfall showing white abstract Maasai paintings made probably quite recently during meat feasting ceremonies, Enkinyoi, Kenya. 2013,2034.12846 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3694558&partId=1&searchText=2013,2034.12846&page=1 - sys: id: 3HGWtlhoS424kQCMo6soOe created_at: !ruby/object:DateTime 2015-11-25 17:03:28.158000000 Z updated_at: !ruby/object:DateTime 2016-05-19 07:35:38.155000000 Z content_type_id: chapter revision: 2 title_internal: 'Geometric motifs: thematic, chapter 3' body: The sites of Namoratung’a near Lake Turkana in northern Kenya showed a similar visible relationship. The southernmost site is well known for its 167 megalithic stones marking male burials on which are engraved hundreds of geometric motifs. Some of these motifs bear a striking resemblance to the brand marks that the Turkana mark on their cattle, camels, donkeys and other livestock in the area, although local people claim no authorship for the funerary engravings (Russell, 2013:4). - sys: id: kgoyTkeS0oQIoaOaaWwwm created_at: !ruby/object:DateTime 2015-11-25 16:59:05.484000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:08:12.169000000 Z content_type_id: image revision: 2 image: sys: id: 19lqDiCw7UOomiMmYagQmq created_at: !ruby/object:DateTime 2015-11-25 16:56:44.756000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:56:44.756000000 Z title: '2013,2034.13006' description: url: "//images.ctfassets.net/xt8ne4gbbocd/19lqDiCw7UOomiMmYagQmq/6f54d106aaec53ed9a055dc7bf3ac014/2013_2034.13006.jpg" caption: Ndorobo man with bow and quiver of arrows kneels at a rock shelter adorned with white symbolic paintings suggesting meat-feasting rituals. Laikipia, Kenya. 2013,2034.13006 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3700172&partId=1&searchText=2013,2034.13006&page=1 - sys: id: 2JZ8EjHqi4U8kWae8oEOEw created_at: !ruby/object:DateTime 2015-11-25 17:03:56.190000000 Z updated_at: !ruby/object:DateTime 2016-05-19 07:35:15.319000000 Z content_type_id: chapter revision: 2 title_internal: 'Geometric motifs: thematic, chapter 4' body: Recent research (Russell, 2013) has shown that at Namoratung’a the branding of animals signifies a sense of belonging rather than a mark of ownership as we understand it in a modern farming context; all livestock, cattle, camel, goats, sheep and donkeys are branded according to species and sex (Russell, 2013:7). Ethnographic accounts document that clan membership can only be determined by observing someone with their livestock (Russell, 2013:9). The symbol itself is not as important as the act of placing it on the animal’s skin, and local people have confirmed that they never mark rock with brand marks. Thus, the geometric motifs on the grave markers may have been borrowed by local Turkana to serve as identity markers, but in a different context. In the Horn of Africa, some geometric rock art is located in the open landscape and on graves. It has been suggested that these too are brand or clan marks, possibly made by camel keeping pastoralists to mark achievement, territory or ownership (Russell, 2013:18). Some nomadic pastoralists, further afield, such as the Tuareg, place their clan marks along the routes they travel, carved onto salt blocks, trees and wells (Mohamed, 1990; Landais, 2001). - sys: id: 3sW37nPBleC8WSwA8SEEQM created_at: !ruby/object:DateTime 2015-11-25 16:59:47.649000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:59:47.649000000 Z content_type_id: image revision: 1 image: sys: id: 5yUlpG85GMuW2IiMeYCgyy created_at: !ruby/object:DateTime 2015-11-25 16:56:44.766000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:56:44.766000000 Z title: '2013,2034.13451' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5yUlpG85GMuW2IiMeYCgyy/a234f96f9931ec3fdddcf1ab54a33cd9/2013_2034.13451.jpg" caption: Borana cattle brands. Namoratung’a, Kenya. 2013,2034.13451. © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3660359&partId=1&searchText=2013,2034.13451&page=1 - sys: id: 6zBkbWkTaEoMAugoiuAwuK created_at: !ruby/object:DateTime 2015-11-25 17:04:38.446000000 Z updated_at: !ruby/object:DateTime 2016-05-19 07:34:17.646000000 Z content_type_id: chapter revision: 3 title_internal: 'Geometric motifs: thematic, chapter 5' body: "However, not all pastoralist geometric motifs can be associated with meat-feasting or livestock branding; they may have wider symbolism or be symbolic of something else (Russell, 2013:17). For example, informants from the Samburu people reported that while some of the painted motifs found at Samburu meat-feasting shelters were of cattle brands, others represented female headdresses or were made to mark an initiation, and in some Masai shelters there are also clear representations of warriors’ shields. In Uganda, a ceremonial rock in Karamoja, shows a dung painting consisting of large circles bisected by a cross which is said to represent cattle enclosures (Robbins, 1972). Geometric symbols, painted in fat and red ochre, on large phallic-shaped fertility stones on the Mesakin and Korongo Hills in south Sudan indicate the sex of the child to whom prayers are offered (Bell, 1936). A circle bisected by a line or circles bisected by two crosses represent boys. Girls are represented by a cross (drawn diagonally) or a slanting line (like a forward slash)(Russell, 2013: 17).\n\nAlthough pastoralist geometric motifs are widespread in the rock art of eastern Africa, attempting to find the meaning behind geometric designs is problematic. The examples discussed here demonstrate that motifs can have multiple authors, even in the same location, and that identical symbols can be the products of very different behaviours. \n" citations: - sys: id: 2oNK384LbeCqEuSIWWSGwc created_at: !ruby/object:DateTime 2015-11-25 17:01:10.748000000 Z updated_at: !ruby/object:DateTime 2016-05-19 07:33:26.748000000 Z content_type_id: citation revision: 3 citation_line: |- <NAME>. 1936. ‘Nuba fertility stones’, in *Sudan Notes and Records* 19(2), pp.313–314. <NAME> 1975. ‘Meat-feasting sites and cattle brands: Patterns of rock-shelter utilization in East Africa’ in *Azania*, 10, pp.107–121. <NAME>. 2001. ‘The marking of livestock in traditional pastoral societies’, *Scientific and Technical Review of the Office International des Epizooties* (Paris), 20 (2), pp.463–479. <NAME>. and <NAME>. 1977. ‘Animal brands and the interpretation of rock art in East Africa’ in *Current Anthropology *18, pp.538–539. Robbins LH (1972) Archaeology in the Turkana district, Kenya. Science 176(4033): 359–366 <NAME>. 2013. ‘Through the skin: exploring pastoralist marks and their meanings to understand parts of East African rock art’, in *Journal of Social Archaeology* 13:1, pp.3-30 &dagger; The term Maa relates to a group of closely related Eastern Nilotic languages, which historically dominated the east African hinterland; and today is spoken by around a million people. background_images: - sys: id: 1TDQd4TutiKwIAE8mOkYEU created_at: !ruby/object:DateTime 2015-12-07 19:16:42.825000000 Z updated_at: !ruby/object:DateTime 2015-12-07 19:16:42.825000000 Z title: KENLOK0030053 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1TDQd4TutiKwIAE8mOkYEU/718ff84615930ddafb1f1fdc67b5e479/KENLOK0030053.JPG" - sys: id: 2SCvEkDjAcIewkiu6iSGC4 created_at: !ruby/object:DateTime 2015-12-07 19:16:42.845000000 Z updated_at: !ruby/object:DateTime 2015-12-07 19:16:42.845000000 Z title: KENKAJ0030008 description: url: "//images.ctfassets.net/xt8ne4gbbocd/2SCvEkDjAcIewkiu6iSGC4/b2e2e928e5d9a6a25aca5c99058dfd76/KENKAJ0030008.jpg" - sys: id: 5HZTuIVN8AASS4ikIea6m6 created_at: !ruby/object:DateTime 2017-12-19 12:27:08.508000000 Z updated_at: !ruby/object:DateTime 2017-12-19 12:27:08.508000000 Z content_type_id: thematic revision: 1 title: Introduction to rock art in central and eastern Africa slug: rock-art-in-central-and-east-africa lead_image: sys: id: 3esXNapo5GOWIKSImcY4QW created_at: !ruby/object:DateTime 2015-11-25 18:56:43.836000000 Z updated_at: !ruby/object:DateTime 2017-12-15 17:01:05.082000000 Z title: '2013,2034.12982' description: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3776396 url: "//images.ctfassets.net/xt8ne4gbbocd/3esXNapo5GOWIKSImcY4QW/6436b2034659eccb953844b21a400070/2013_2034.12982.jpg" chapters: - sys: id: 4ln5fQLq2saMKsOA4WSAgc created_at: !ruby/object:DateTime 2015-11-25 19:09:33.580000000 Z updated_at: !ruby/object:DateTime 2015-12-11 11:17:25.155000000 Z content_type_id: chapter revision: 4 title: Central and East Africa title_internal: 'East Africa: regional, chapter 1' body: |- Central Africa is dominated by vast river systems and lakes, particularly the Congo River Basin. Characterised by hot and wet weather on both sides of the equator, central Africa has no regular dry season, but aridity increases in intensity both north and south of the equator. Covered with a forest of about 400,000 m² (1,035,920 km²), it is one of the greenest parts of the continent. The rock art of central Africa stretches from the Zambezi River to the Angolan Atlantic coast and reaches as far north as Cameroon and Uganda. Termed the ‘schematic rock art zone’ by <NAME> (1959), it is dominated by finger-painted geometric motifs and designs, thought to extend back many thousands of years. Eastern Africa, from the Zambezi River Valley to Lake Turkana, consists largely of a vast inland plateau with the highest elevations on the continent, such as Mount Kilimanjaro (5,895m above sea level) and Mount Kenya (5,199 m above sea level). Twin parallel rift valleys run through the region, which includes the world’s second largest freshwater lake, Lake Victoria. The climate is atypical of an equatorial region, being cool and dry due to the high altitude and monsoon winds created by the Ethiopian Highlands. The rock art of eastern Africa is concentrated on this plateau and consists mainly of paintings that include animal and human representations. Found mostly in central Tanzania, eastern Zambia and Malawi; in comparison to the widespread distribution of geometric rock art, this figurative tradition is much more localised, and found at just a few hundred sites in a region of less than 100km in diameter. - sys: id: 4nyZGLwHTO2CK8a2uc2q6U created_at: !ruby/object:DateTime 2015-11-25 18:57:48.121000000 Z updated_at: !ruby/object:DateTime 2017-12-15 17:05:00.916000000 Z content_type_id: image revision: 2 image: sys: id: 3esXNapo5GOWIKSImcY4QW created_at: !ruby/object:DateTime 2015-11-25 18:56:43.836000000 Z updated_at: !ruby/object:DateTime 2017-12-15 17:01:05.082000000 Z title: '2013,2034.12982' description: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3776396 url: "//images.ctfassets.net/xt8ne4gbbocd/3esXNapo5GOWIKSImcY4QW/6436b2034659eccb953844b21a400070/2013_2034.12982.jpg" caption: <NAME>. 2013,2034.12982 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3776396 - sys: id: 1OvIWDPyXaCO2gCWw04s06 created_at: !ruby/object:DateTime 2015-11-25 19:10:23.723000000 Z updated_at: !ruby/object:DateTime 2015-12-11 11:18:19.325000000 Z content_type_id: chapter revision: 2 title_internal: 'East Africa: regional, chapter 2' body: This collection from Central and East Africa comprises rock art from Kenya, Uganda and Tanzania, as well as the Horn of Africa; although predominantly paintings, engravings can be found in most countries. - sys: id: 4JqI2c7CnYCe8Wy2SmesCi created_at: !ruby/object:DateTime 2015-11-25 19:10:59.991000000 Z updated_at: !ruby/object:DateTime 2016-10-17 13:34:14.653000000 Z content_type_id: chapter revision: 3 title: History of research title_internal: 'East Africa: regional, chapter 3' body: |- The rock art of East Africa, in particular the red paintings from Tanzania, was extensively studied by Mary and <NAME> in the 1930s and 1950s. <NAME> observed Sandawe people of Tanzania making rock paintings in the mid-20th century, and on the basis of oral traditions argued that the rock art was made for three main purposes: casual art; magic art (for hunting purposes or connected to health and fertility) and sacrificial art (to appease ancestral spirits). Subsequently, during the 1970s Fidelis Masao and <NAME> recorded numerous sites, classifying the art in broad chronological and stylistic categories, proposing tentative interpretations with regard to meaning. There has much debate and uncertainty about Central African rock art. The history of the region has seen much mobility and interaction of cultural groups and understanding how the rock art relates to particular groups has been problematic. Pioneering work in this region was undertaken by <NAME> in central Malawi in the early 1920s, <NAME> R<NAME>e visited Zambia in 1936 and attempted to provide a chronological sequence and some insight into the meaning of the rock art. Since the 1950s (Clarke, 1959), archaeologists have attempted to situate rock art within broader archaeological frameworks in order to resolve chronologies, and to categorise the art with reference to style, colour, superimposition, subject matter, weathering, and positioning of depictions within the panel (Phillipson, 1976). Building on this work, our current understanding of rock in this region has been advanced by <NAME> (1995, 1997, 2001) with his work in Zambia and Malawi. - sys: id: 35HMFoiKViegWSY044QY8K created_at: !ruby/object:DateTime 2015-11-25 18:59:25.796000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:51:25.789000000 Z content_type_id: image revision: 5 image: sys: id: 6KOxC43Z9mYCuIuqcC8Qw0 created_at: !ruby/object:DateTime 2015-11-25 18:57:00.077000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:57:00.077000000 Z title: '2013,2034.17450' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6KOxC43Z9mYCuIuqcC8Qw0/e25141d07f483d0100c4cf5604e3e525/2013_2034.17450.jpg" caption: This painting of a large antelope is possibly one of the earliest extant paintings. <NAME> believes similar paintings could be more than 28,000 years old. 2013,2034.17450 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3711689 - sys: id: 1dSBI9UNs86G66UGSEOOkS created_at: !ruby/object:DateTime 2015-12-09 11:56:31.754000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:50:18.203000000 Z content_type_id: chapter revision: 5 title: East African Rock Art title_internal: Intro to east africa, chapter 3.5 body: "Rock art of East Africa consists mainly of paintings, most of which are found in central Tanzania, and are fewer in number in eastern Zambia and Malawi; scholars have categorised them as follows:\n\n*__Red Paintings__*: \nRed paintings can be sub-divided into those found in central Tanzania and those found stretching from Zambia to the Indian Ocean.\nTanzanian red paintings include large, naturalistic animals with occasional geometric motifs. The giraffe is the most frequently painted animal, but antelope, zebra, elephant, rhino, felines and ostrich are also depicted. Later images show figures with highly distinctive stylised human head forms or hairstyles and body decoration, sometimes in apparent hunting and domestic scenes. The Sandawe and Hadza, hunter-gatherer groups, indigenous to north-central and central Tanzania respectively, claim their ancestors were responsible for some of the later art.\n\nThe area in which Sandawe rock art is found is less than 100km in diameter and occurs at just a few hundred sites, but corresponds closely to the known distribution of this group. There have been some suggestions that Sandawe were making rock art early into the 20th century, linking the art to particular rituals, in particular simbo; a trance dance in which the Sandawe communicate with the spirit world by taking on the power of an animal. The art displays a range of motifs and postures, features that can be understood by reference to simbo and to trance experiences; such as groups of human figures bending at the waist (which occurs during the *simbo* dance), taking on animal features such as ears and tails, and floating or flying; reflecting the experiences of those possessed in the dance." - sys: id: 7dIhjtbR5Y6u0yceG6y8c0 created_at: !ruby/object:DateTime 2015-11-25 19:00:07.434000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:51:51.887000000 Z content_type_id: image revision: 5 image: sys: id: 1fy9DD4BWwugeqkakqWiUA created_at: !ruby/object:DateTime 2015-11-25 18:57:11.188000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:57:11.188000000 Z title: '2013,2034.16849' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1fy9DD4BWwugeqkakqWiUA/9f8f1330c6c0bc0ff46d744488daa152/2013_2034.16849.jpg" caption: Three schematic figures formed by the use of multiple thin parallel lines. The shape and composition of the heads suggests either headdresses or elaborate hairstyles. Kondoa, Tanzania. 2013,2034.16849 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3709812 - sys: id: 1W573pi2Paks0iA8uaiImy created_at: !ruby/object:DateTime 2015-11-25 19:12:00.544000000 Z updated_at: !ruby/object:DateTime 2015-12-11 11:21:09.647000000 Z content_type_id: chapter revision: 8 title_internal: 'East Africa: regional, chapter 4' body: "Zambian rock art does not share any similarities with Tanzanian rock art and can be divided into two categories; animals (with a few depictions of humans), and geometric motifs. Animals are often highly stylised and superimposed with rows of dots. Geometric designs include, circles, some of which have radiating lines, concentric circles, parallel lines and ladder shapes. Predominantly painted in red, the remains of white pigment is still often visible. David Phillipson (1976) proposed that the naturalistic animals were earlier in date than geometric designs. Building on Phillipson’s work, <NAME> studied ethnographic records and demonstrated that geometric motifs were made by women or controlling the weather.\n\n*__Pastoralist paintings__*: \nPastoralist paintings are rare, with only a few known sites in Kenya and other possible sites in Malawi. Usually painted in black, white and grey, but also in other colours, they include small outlines, often infilled, of cattle and are occasional accompanied by geometric motifs. Made during the period from 3,200 to 1,800 years ago the practice ceased after Bantu language speaking people had settled in eastern Africa. Similar paintings are found in Ethiopia but not in southern Africa, and it has been assumed that these were made by Cushitic or Nilotic speaking groups, but their precise attribution remains unclear (Smith, 2013:154).\n" - sys: id: 5jReHrdk4okicG0kyCsS6w created_at: !ruby/object:DateTime 2015-11-25 19:00:41.789000000 Z updated_at: !ruby/object:DateTime 2017-12-15 17:10:04.890000000 Z content_type_id: image revision: 3 image: sys: id: 1hoZEK3d2Oi8iiWqoWACo created_at: !ruby/object:DateTime 2015-11-25 18:56:43.848000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:56:43.848000000 Z title: '2013,2034.13653' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1hoZEK3d2Oi8iiWqoWACo/1a1adcfad5d5a1cf0a341316725d61c4/2013_2034.13653.jpg" caption: Two red bulls face right. Mt Elgon, Kenya. 2013,2034.13653. © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3700058 - sys: id: 7rFAK9YoBqYs0u0EmCiY64 created_at: !ruby/object:DateTime 2015-11-25 19:00:58.494000000 Z updated_at: !ruby/object:DateTime 2017-12-15 17:11:37.760000000 Z content_type_id: image revision: 3 image: sys: id: 3bqDVyvXlS0S6AeY2yEmS8 created_at: !ruby/object:DateTime 2015-11-25 18:56:43.880000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:56:43.880000000 Z title: '2013,2034.13635' description: url: "//images.ctfassets.net/xt8ne4gbbocd/3bqDVyvXlS0S6AeY2yEmS8/c9921f3d8080bcef03c96c6b8f1b0323/2013_2034.13635.jpg" caption: Two cattle with horns in twisted perspective. Mt Elgon, Kenya. 2013,2034.13635. © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3698905 - sys: id: 1tX4nhIUgAGmyQ4yoG6WEY created_at: !ruby/object:DateTime 2015-11-25 19:14:33.823000000 Z updated_at: !ruby/object:DateTime 2015-11-25 19:14:33.823000000 Z content_type_id: chapter revision: 1 title_internal: 'East Africa: regional, chapter 5' body: |- *__Late White Paintings__*: Commonly painted in white, or off-white with the fingers, so-called ‘Late White’ depictions include quite large crudely rendered representations of wild animals, mythical animals, human figures and numerous geometric motifs. These paintings are attributed to Bantu language speaking, iron-working farmers who entered eastern Africa about 2,000 years ago from the west on the border of Nigeria and Cameroon. Moving through areas occupied by the Batwa it is thought they learned the use of symbols painted on rock, skin, bark cloth and in sand. Chewa peoples, Bantu language speakers who live in modern day Zambia and Malawi claim their ancestors made many of the more recent paintings which they used in rites of passage ceremonies. - sys: id: 35dNvNmIxaKoUwCMeSEO2Y created_at: !ruby/object:DateTime 2015-11-25 19:01:26.458000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:52:15.838000000 Z content_type_id: image revision: 4 image: sys: id: 6RGZZQ13qMQwmGI86Ey8ei created_at: !ruby/object:DateTime 2015-11-25 18:57:11.188000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:57:11.188000000 Z title: '2013,2034.16786' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6RGZZQ13qMQwmGI86Ey8ei/6d37a5bed439caf7a1223aca27dc27f8/2013_2034.16786.jpg" caption: Under a long narrow granite overhang, Late White designs including rectangular grids, concentric circles and various ‘square’ shapes. 2013,2034.16786 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3709608 - sys: id: 2XW0X9BzFCa8u2qiKu6ckK created_at: !ruby/object:DateTime 2015-11-25 19:01:57.959000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:53:21.559000000 Z content_type_id: image revision: 4 image: sys: id: 1UT4r6kWRiyiUIYSkGoACm created_at: !ruby/object:DateTime 2015-11-25 18:57:11.138000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:57:11.138000000 Z title: '2013,2034.16797' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1UT4r6kWRiyiUIYSkGoACm/fe915c6869b6c195d55b5ef805df7671/2013_2034.16797.jpg" caption: A monuments guard stands next to Late White paintings attributed to Bantu speaking farmers in Tanzania, probably made during the last 700 years. 2013,2034.16797 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3709628 - sys: id: 3z28O8A58AkgMUocSYEuWw created_at: !ruby/object:DateTime 2015-11-25 19:15:04.047000000 Z updated_at: !ruby/object:DateTime 2015-11-25 19:15:04.047000000 Z content_type_id: chapter revision: 1 title_internal: 'East Africa: regional, chapter 6' body: |- *__Meat-feasting paintings__*: Meat-feasting shelters exist from northern Tanzania through Kenya to Lake Turkana, and are places where Maa-speaking initiated men, who are not permitted to eat meat in their homes, gather to kill and feast on animals, predominantly cattle. The term Maa relates to a group of closely related Eastern Nilotic languages, which historically dominated the east African hinterland; and today is spoken by around a million people. During or after feasting, symbols of the animals that had been eaten were painted on the shelter ceiling in white or less often red. Maa speakers brand their cattle and camels with symbols that signify the lineage of their owners, but may also indicate if an animal has been treated for a particular disease. Different symbols may be used for male and female animals. Over the centuries, because the depictions are on the ceiling of meat feasting rock shelters, and because sites are used even today, a build-up of soot has obscured or obliterated the paintings. Unfortunately, few have been recorded or mapped. - sys: id: 1yjQJMFd3awKmGSakUqWGo created_at: !ruby/object:DateTime 2015-11-25 19:02:23.595000000 Z updated_at: !ruby/object:DateTime 2017-12-15 17:19:11.619000000 Z content_type_id: image revision: 3 image: sys: id: p4E0BRJzossaus6uUUkuG created_at: !ruby/object:DateTime 2015-11-25 18:56:49.743000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:56:49.743000000 Z title: '2013,2034.13004' description: url: "//images.ctfassets.net/xt8ne4gbbocd/p4E0BRJzossaus6uUUkuG/13562eee76ac2a9efe8c0d12e62fa23a/2013_2034.13004.jpg" caption: Huge granite boulder with Ndorobo man standing before a rock overhang used for meat-feasting. Laikipia, Kenya. 2013,2034. 13004. © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3700175 - sys: id: 6lgjLZVYrY606OwmwgcmG2 created_at: !ruby/object:DateTime 2015-11-25 19:02:45.427000000 Z updated_at: !ruby/object:DateTime 2017-12-15 17:20:14.877000000 Z content_type_id: image revision: 3 image: sys: id: 1RLyVKKV8MA4KEk4M28wqw created_at: !ruby/object:DateTime 2015-11-25 18:57:11.150000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:57:11.150000000 Z title: '2013,2034.13018' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1RLyVKKV8MA4KEk4M28wqw/044529be14a590fd1d0da7456630bb0b/2013_2034.13018.jpg" caption: This symbol is probably a ‘brand’ used on cattle that were killed and eaten at a Maa meat feast. Laikipia, Kenya. 2013,2034.13018 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3700193 - sys: id: 5UQc80DUBiqqm64akmCUYE created_at: !ruby/object:DateTime 2015-11-25 19:15:34.582000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:53:53.936000000 Z content_type_id: chapter revision: 4 title: Central African Rock Art title_internal: 'East Africa: regional, chapter 7' body: The rock art of central Africa is attributed to hunter-gatherers known as Batwa. This term is used widely in eastern central and southern Africa to denote any autochthonous hunter-gatherer people. The rock art of the Batwa can be divided into two categories which are quite distinctive stylistically from the Tanzanian depictions of the Sandawe and Hadza. Nearly 3,000 sites are currently known from within this area. The vast majority, around 90%, consist of finger-painted geometric designs; the remaining 10% include highly stylised animal forms (with a few human figures) and rows of finger dots. Both types are thought to date back many thousands of years. The two traditions co-occur over a vast area of eastern and central Africa and while often found in close proximity to each other are only found together at a few sites. However, it is the dominance of geometric motifs that make this rock art tradition very distinctive from other regions in Africa. - sys: id: 4m51rMBDX22msGmAcw8ESw created_at: !ruby/object:DateTime 2015-11-25 19:03:40.666000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:54:25.415000000 Z content_type_id: image revision: 4 image: sys: id: 2MOrR79hMcO2i8G2oAm2ik created_at: !ruby/object:DateTime 2015-11-25 18:56:49.737000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:56:49.737000000 Z title: '2013,2034.15306' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2MOrR79hMcO2i8G2oAm2ik/86179e84233956e34103566035c14b76/2013_2034.15306.jpg" caption: Paintings in red and originally in-filled in white cover the underside of a rock shelter roof. The art is attributed to central African Batwa; the age of the paintings is uncertain. Lake Victoria, Uganda. 2013,2034.15306 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3691242 - sys: id: 5rNOG3568geMmIEkIwOIac created_at: !ruby/object:DateTime 2015-11-25 19:16:07.130000000 Z updated_at: !ruby/object:DateTime 2015-11-25 19:16:19.722000000 Z content_type_id: chapter revision: 2 title_internal: 'East Africa: regional, chapter 8' body: "*__Engravings__*:\nThere are a few engravings occurring on inland plateaus but these have elicited little scientific interest and are not well documented. \ Those at the southern end of Lake Turkana have been categorised into two types: firstly, animals, human figures and geometric forms and also geometric forms thought to involve lineage symbols.\nIn southern Ethiopia, near the town of Dillo about 300 stelae, some of which stand up to two metres in height, are fixed into stones and mark grave sites. People living at the site ask its spirits for good harvests. \n" - sys: id: LrZuJZEH8OC2s402WQ0a6 created_at: !ruby/object:DateTime 2015-11-25 19:03:59.496000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:54:51.576000000 Z content_type_id: image revision: 5 image: sys: id: 1uc9hASXXeCIoeMgoOuO4e created_at: !ruby/object:DateTime 2015-11-25 18:57:11.176000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:57:11.176000000 Z title: '2013,2034.16206' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1uc9hASXXeCIoeMgoOuO4e/09a7504449897509778f3b9455a42f8d/2013_2034.16206.jpg" caption: Group of anthropomorphic stelae with carved faces. <NAME>, Southern Ethiopia. 2013,2034.16206 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3703754 - sys: id: 7EBTx1IjKw6y2AUgYUkAcm created_at: !ruby/object:DateTime 2015-11-25 19:16:37.210000000 Z updated_at: !ruby/object:DateTime 2015-12-11 11:22:04.007000000 Z content_type_id: chapter revision: 2 title_internal: 'East Africa: regional, chapter 9' body: In the Sidamo region of Ethiopia, around 50 images of cattle are engraved in bas-relief on the wall of a gorge. All the engravings face right and the cows’ udders are prominently displayed. Similar engravings of cattle, all close to flowing water, occur at five other sites in the area, although not in such large numbers. - sys: id: 6MUkxUNFW8oEK2aqIEcee created_at: !ruby/object:DateTime 2015-11-25 19:04:34.186000000 Z updated_at: !ruby/object:DateTime 2017-12-19 12:22:24.891000000 Z content_type_id: image revision: 3 image: sys: id: PlhtduNGSaOIOKU4iYu8A created_at: !ruby/object:DateTime 2015-11-25 18:56:43.849000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:56:43.849000000 Z title: '2013,2034.16235' description: url: "//images.ctfassets.net/xt8ne4gbbocd/PlhtduNGSaOIOKU4iYu8A/7625c8a21caf60046ea73f184e8b5c76/2013_2034.16235.jpg" caption: Around 50 images of cattle are engraved in bas-relief into the sandstone wall of a gorge in the Sidamo region of Ethiopia. 2013,2034.16235 © TARA/David Coulson col_link: http://bit.ly/2hMU0vm - sys: id: 6vT5DOy7JK2oqgGK8EOmCg created_at: !ruby/object:DateTime 2015-11-25 19:17:53.336000000 Z updated_at: !ruby/object:DateTime 2015-12-11 11:25:38.678000000 Z content_type_id: chapter revision: 3 title: Rock art in the Horn of Africa title_internal: 'East Africa: regional, chapter 10' body: "The Horn of Africa has historically been a crossroads area between the Eastern Sahara, the Subtropical regions to the South and the Arabic Peninsula. These mixed influences can be seen in many archaeological and historical features throughout the region, the rock art being no exception. Since the early stages of research in the 1930s, a strong relationship between the rock art in Ethiopia and the Arabian Peninsula was detected, leading to the establishment of the term *Ethiopian-Arabian* rock art by <NAME> in 1971. This research thread proposes a progressive evolution from naturalism to schematism, ranging from the 4th-3rd millennium BC to the near past. Although the *Ethiopian-Arabian* proposal is still widely accepted and stylistic similarities between the rock art of Somalia, Ethiopia, Yemen or Saudi Arabia are undeniable, recent voices have been raised against the term because of its excessive generalisation and lack of operability. In addition, recent research to the south of Ethiopia have started to discover new rock art sites related to those found in Uganda and Kenya.\n\nRegarding the main themes of the Horn of Africa rock art, cattle depictions seem to have been paramount, with cows and bulls depicted either isolated or in herds, frequently associated with ritual scenes which show their importance in these communities. Other animals – zebus, camels, felines, dogs, etc. – are also represented, as well as rows of human figures, and fighting scenes between warriors or against lions. Geometric symbols are also common, usually associated with other depictions; and in some places they have been interpreted as tribal or clan marks. Both engraving and painting is common in most regions, with many regional variations. \n" - sys: id: 4XIIE3lDZYeqCG6CUOYsIG created_at: !ruby/object:DateTime 2015-11-25 19:04:53.913000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:55:12.472000000 Z content_type_id: image revision: 4 image: sys: id: 3ylztNmm2cYU0GgQuW0yiM created_at: !ruby/object:DateTime 2015-11-25 18:57:11.155000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:57:11.155000000 Z title: '2013,2034.15749' description: url: "//images.ctfassets.net/xt8ne4gbbocd/3ylztNmm2cYU0GgQuW0yiM/3be240bf82adfb5affc0d653e353350b/2013_2034.15749.jpg" caption: Painted roof of rock shelter showing decorated cows and human figures. <NAME>, Somaliland. 2013,2034.15749 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3691391 - sys: id: 2IKYx0YIVOyMSwkU8mQQM created_at: !ruby/object:DateTime 2015-11-25 19:18:28.056000000 Z updated_at: !ruby/object:DateTime 2015-12-11 11:26:13.401000000 Z content_type_id: chapter revision: 2 title_internal: 'East Africa: regional, chapter 11' body: |- Rock art in the Horn of Africa faces several challenges. One of them is the lack of consolidated chronologies and absolute dating for the paintings and engravings. Another is the uneven knowledge of rock art throughout the region, with research often affected by political unrest. Therefore, distributions of rock art in the region are steadily growing as research is undertaken in one of the most interactive areas in East Africa. The rock art of Central and East Africa is one of the least documented and well understood of the corpus of African rock art. However, in recent years scholars have undertaken some comprehensive reviews of existing sites and surveys of new sites to open up the debates and more fully understand the complexities of this region. citations: - sys: id: 7d9bmwn5kccgO2gKC6W2Ys created_at: !ruby/object:DateTime 2015-11-25 19:08:04.014000000 Z updated_at: !ruby/object:DateTime 2017-12-19 12:24:18.659000000 Z content_type_id: citation revision: 2 citation_line: "<NAME>. 1996. ‘Cultural Patterns in the Rock Art of Central Tanzania.’ in *The Prehistory of Africa*. XIII International Congress of Prehistoric and Protohistoric Sciences Forli-Italia-8/14 September.\n\nČerviček, P. 1971. ‘Rock paintings of Laga Oda (Ethiopia)’ in *Paideuma*, 17, pp.121-136.\n\nClark, <NAME>. 1954. *The Prehistoric Cultures of the Horn of Africa*. New York: Octagon Press.\n\n<NAME>. 1959. ‘Rock Paintings of Northern Rhodesia and Nyasaland’, in Summers, R. (ed.) *Prehistoric Rock Art of the Federation of Rhodesia & Nyasaland*: Glasgow: National Publication Trust, pp.163- 220.\n\nJoussaume, R. (ed.) 1995. Tiya, *l’Ethiopie des mégalithes : du biface à l’art rupestre dans la Corne de l’Afrique*. Association des publications chauvinoises (A.P.C.), Chauvigny.\n\n<NAME>. 1983. *Africa’s Vanishing Art – The Rock Paintings of Tanzania*. London: Hamish Hamilton Ltd.\n\nMasao, F.T. 1979. *The Later Stone Age and the Rock Paintings of Central Tanzania*. Wiesbaden: <NAME>. \n\nNamono, Catherine. 2010. *A contextual interpretive approach to the rock art of Uganda*. Unpublished PhD Thesis. Johannesburg: University of Witwatersrand\n\nPhillipson, D.W. 1976. ‘The Rock Paintings of Eastern Zambia’, in *The Prehistory of Eastern Zambia: Memoir 6 of the british Institute in Eastern Africa*. Nairobi.\n\n<NAME>. (1995), Rock art in south-Central Africa: A study based on the pictographs of Dedza District, Malawi and Kasama District Zambia. dissertation. Cambridge: University of Cambridge, Unpublished Ph.D. dissertation.\n\n<NAME>. (1997), Zambia’s ancient rock art: The paintings of Kasama. Zambia: The National Heritage Conservation Commission of Zambia.\n\nSmith B.W. (2001), Forbidden images: Rock paintings and the Nyau secret society of Central Malaŵi and Eastern Zambia. *African Archaeological Review*18(4): 187–211.\n\n<NAME>. 2013, ‘Rock art research in Africa; in In: Lane, P. & Mitchell, P. (eds) *Handbook of African Archaeology*. Oxford: Oxford University Press, pp.145-162.\n\nTen Raa, E. 1974. ‘A record of some prehistoric and some recent Sandawe rock paintings’ in *Tanzania Notes and Records* 75, pp.9-27." background_images: - sys: id: 4aeKk2gBTiE6Es8qMC4eYq created_at: !ruby/object:DateTime 2015-12-07 19:42:27.348000000 Z updated_at: !ruby/object:DateTime 2017-12-19 12:25:55.914000000 Z title: '2013,2034.1298' description: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3592557 url: "//images.ctfassets.net/xt8ne4gbbocd/4aeKk2gBTiE6Es8qMC4eYq/31cde536c4abf1c0795761f8e35b255c/2013_2034.1298.jpg" - sys: id: 6DbMO4lEBOU06CeAsEE8aA created_at: !ruby/object:DateTime 2015-12-07 19:41:53.440000000 Z updated_at: !ruby/object:DateTime 2017-12-19 12:26:40.898000000 Z title: '2013,2034.15749' description: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3691391 url: "//images.ctfassets.net/xt8ne4gbbocd/6DbMO4lEBOU06CeAsEE8aA/9fc2e1d88f73a01852e1871f631bf4ff/2013_2034.15749.jpg" country_introduction: sys: id: 142GjmRwVygmAiU6Q0AYmA created_at: !ruby/object:DateTime 2015-11-26 15:35:38.627000000 Z updated_at: !ruby/object:DateTime 2015-12-07 13:43:02.363000000 Z content_type_id: country_information revision: 2 title: 'Kenya: country introduction' chapters: - sys: id: 2sEl2XznyQ66Eg22skoqYu created_at: !ruby/object:DateTime 2015-11-26 15:28:45.582000000 Z updated_at: !ruby/object:DateTime 2015-12-11 11:51:02.714000000 Z content_type_id: chapter revision: 2 title: Introduction title_internal: 'Kenya: country, chapter 1' body: Rock art is distributed widely throughout Kenya, although historically rock art research has not been as extensive as in neighbouring countries such as Tanzania. Some of Kenya's various rock art traditions are attributed to or associated with the ancestors of modern regional cultural groups, and as such sites sometimes retain local religious importance. Both painted and engraved imagery tends towards the symbolic and geometric, with occasional depictions of schematic animals and people. It must be noted that there are still probably many Kenyan rock art sites which have not yet become known outside of their local communities, if they are known at all. - sys: id: 6nL6NLL93GQUyiQaWAgakG created_at: !ruby/object:DateTime 2015-11-26 15:23:16.663000000 Z updated_at: !ruby/object:DateTime 2017-01-13 16:02:48.785000000 Z content_type_id: image revision: 3 image: sys: id: 191BlqkgSUmU20ckCQqCyk created_at: !ruby/object:DateTime 2015-12-08 18:49:22.434000000 Z updated_at: !ruby/object:DateTime 2015-12-08 18:49:22.434000000 Z title: KENMTE0010018 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/191BlqkgSUmU20ckCQqCyk/72813bbadf5ed408fa5515940ff369f8/KENMTE0010018_1.jpg" caption: Painted panel with cattle. Kakapel, south of Mount Elgon 2013,2034.13640 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3699416&partId=1&searchText=2013,2034.13640&page=1 - sys: id: 2VIFeJyqys02i4Uc4wGmas created_at: !ruby/object:DateTime 2015-11-26 15:29:20.719000000 Z updated_at: !ruby/object:DateTime 2017-01-13 16:15:40.192000000 Z content_type_id: chapter revision: 3 title: Geography and rock art distribution title_internal: 'Kenya: country, chapter 2' body: Kenya covers about 569,140km², bordering Ethiopia and Somalia in the north and east and Tanzania and Uganda in the south and west. The country stretches from a low-lying eastern coastal strip, inland to highland regions in the west of the country. Kenya's western half is divided by the eastern section of the East African Rift, the long area of tectonic divergence which runs from the coasts of Djibouti, Eritrea and Somalia down through Ethiopia and Kenya and into Uganda, curving around the eastern edge of the Lake Victoria basin. There are a significant number of painted rock art sites throughout west-central and southern Kenya. - sys: id: 69Hu2xajVCWIyOCCI6cQuC created_at: !ruby/object:DateTime 2015-11-26 15:23:43.746000000 Z updated_at: !ruby/object:DateTime 2018-05-17 16:39:32.374000000 Z content_type_id: image revision: 4 image: sys: id: 4ZkoqzwyVaAuciGqmAUqwC created_at: !ruby/object:DateTime 2015-12-08 18:49:17.623000000 Z updated_at: !ruby/object:DateTime 2015-12-08 18:49:17.623000000 Z title: KENKAJ0010017 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/4ZkoqzwyVaAuciGqmAUqwC/240ce914ba1f5a1a6c05c71b1f587617/KENKAJ0010017_1.jpg" caption: 'View of the Rift Valley near Mount Suswa 2013,2034.12836 © <NAME>/TARA. ' col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3776423&partId=1 - sys: id: 54kNwI6Yq4wU88i6MoaM0K created_at: !ruby/object:DateTime 2015-11-26 15:30:05.512000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:30:05.512000000 Z content_type_id: chapter revision: 1 title: Research history title_internal: 'Kenya: country, chapter 3' body: 'Although researchers had been noting and investigating rock art in the neighbouring countries of Tanzania and Uganda from the early years of the 20th Century, the first published mention of Kenyan rock art appeared only in 1946, with <NAME>''s descriptions of engravings at Surima, in the northern Turkana region. It was in the 1960s that sustained academic attention began to be paid to other sites in the country. In 1961 <NAME> published an account of a rock shelter (now known as Kiptogot Cave) with painted images of cattle on the slopes of Mount Elgon near Kitale. Wright suggested potential parallels in style with some Ethiopian pastoralist rock art. In 1968 Robert Soper was the first archaeologist to investigate the unique Namoratung’a burial sites to the east of Lake Turkana, with their engraved standing stones, the interpretation of which would be continued with the work of <NAME> and <NAME> in the 1970s. In the same decade significant painting sites at Lake Victoria, north of the lake near the Ugandan border, and in the far south were also reported on by <NAME>, Os<NAME> and <NAME>. Research and discovery has continued and is likely that many rock art sites in Kenya remain to be documented. As recently as 2005, 21 previously unknown rock art sites in the Samburu area of central Kenya were recorded during dedicated survey work organised by the British Institute in East Africa. ' - sys: id: 1VQjZKKOhCUCC0sMKmI2EG created_at: !ruby/object:DateTime 2015-11-26 15:24:16.333000000 Z updated_at: !ruby/object:DateTime 2017-01-13 17:16:53.891000000 Z content_type_id: image revision: 3 image: sys: id: 3o8IJEfzbWI4qiywkMu8WM created_at: !ruby/object:DateTime 2015-12-08 18:49:17.505000000 Z updated_at: !ruby/object:DateTime 2015-12-08 18:49:17.505000000 Z title: KENVIC0010004 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3o8IJEfzbWI4qiywkMu8WM/6c5d99356b89ab8e961c347207547889/KENVIC0010004_1.jpg" caption: Painted panel showing concentric circles and spirals. Kwitone Shelter, Mfangano Island. 2013,2034.14238 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3685727&partId=1&searchText=2013,2034.14238&page=1 - sys: id: 4t7LVO1JeES8agW2AK2Q0k created_at: !ruby/object:DateTime 2015-11-26 15:31:05.485000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:31:13.826000000 Z content_type_id: chapter revision: 2 title: Themes title_internal: 'Kenya: country, chapter 4' body: "Figurative imagery only features prominently in about 10% of the known rock art sites of Kenya. That which exists tends to consist of very schematic images of cattle, wild animals and people. The majority of both painted and engraved rock art iconography throughout Kenya comprises symbols, with common patterns including circles, sometimes concentric or containing crosses, spirals, parallel or cross-hatched lines and curvilinear shapes. Circular ground depressions in the rock surface, known as cupules, are also a common variant of rock art in Kenya, along with rock gongs, which show evidence of the use of natural rock formations as percussive instruments.\n\nInterpretation, cultural attribution and proposed dates for these works vary widely across technique and area, although there are common themes. It has been suggested that the schematic nature and similarities in the art may point to shared East African symbolic understandings common to different cultural groups, for example equating circular shapes (some of the most popular motifs in Eastern and Central African rock art in general) with chieftainship or the sun, or acting as navigation devices.\n\nGiven the variations in distance, age and nature of the sites, there is a danger of generalising, but there are factors which may contribute to more incisive interpretations of specific sites and symbols. One set of interpretations for geometric shapes in Kenyan rock art points to the similarities of certain of these symbols to cattle brands used by Nilotic peoples throughout Kenya, including the Turkana, Samburu and Masai groups. Although the engravings at Namoratung'a are not thought to have been made by ancestral Turkana people, Lynch and Robbins noted the similarities of some of the symbols found there to contemporary local Turkana cattle brands. These symbols are pecked on stones at graves containing mens’ remains and have been proposed to represent male lineages, as animal brands traditionally do in contemporary Nilotic ethnic groups. Further south, it is known that some more recent rock paintings representing brand and shield patterns were made by Masai and Samburu men, in shelters used for meat-feasting—a practice forbidden in their home compounds after their formal initiation as warriors—or as initiation sites. Actual representations of cattle are rare, with the vibrant paintings at Kakapel near the Ugandan border the most reknowned. Their creators are unknown although Masai and Samburu have been known to paint occasional schematic cattle in the past. \n" - sys: id: 2J6pAiklT2mgAqmGWYiKm4 created_at: !ruby/object:DateTime 2015-11-26 15:24:54.228000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:24:54.228000000 Z content_type_id: image revision: 1 image: sys: id: 6sJEag1degeScYa0IYY66a created_at: !ruby/object:DateTime 2015-11-26 15:19:31.878000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:19:31.878000000 Z title: '2013,2034.13567' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6sJEag1degeScYa0IYY66a/7b598c98a08f07a8af2290ee301c897d/KENLOK0040007.jpg" caption: Stone circles at Namoratung’a. 2013,2034.13567 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3660580&partId=1&searchText=2013,2034.13567&page=1 - sys: id: 2FBovUnIEU0om2mG2qCKAM created_at: !ruby/object:DateTime 2015-11-26 15:31:50.127000000 Z updated_at: !ruby/object:DateTime 2017-01-13 17:19:42.052000000 Z content_type_id: chapter revision: 3 title_internal: 'Kenya: country, chapter 5' body: Not all of Kenya's rock art is associated with pastoralists. Much of the symbolic art, particularly to the south and west, is attributed to the ’Batwa’, ancestors of modern Batwa and related, traditionally hunter-gatherer cultural groups living around the Great Lakes Region of East and Central Africa. Circular designs and “Sunburst” symbols are some of the most common motifs usually associated with the Batwa rock art tradition; it has been proposed that they may have been associated with fertility or rainmaking. Some rock art on Mfangano Island, in the Kenyan portion of Lake Victoria, has retained the latter association, having been used until the recent past by local Abasuba people for rainmaking purposes, despite their not having produced it originally. This re-use of symbolic sites in Kenya and the difficulty of dating further confuses the question of attribution for the art. The same rock art sites used by different cultural groups at different times and for different reasons. Such is the case at Kakapel for example, where it is posited that the earliest paintings may be hunter-gatherer in origin, with more recent cattle images added later, and Namoratung’a, with some engravings apparently hundreds of years old and others made within the last century. - sys: id: 1Rc5KyPQDS0KG8mY0g2CwI created_at: !ruby/object:DateTime 2015-11-26 15:25:30.561000000 Z updated_at: !ruby/object:DateTime 2017-01-13 17:20:10.830000000 Z content_type_id: image revision: 2 image: sys: id: 1rIqvHUlxCgqW2caioAo4I created_at: !ruby/object:DateTime 2015-11-26 15:18:52.034000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:22:07.193000000 Z title: '2013,2034.13018' description: url: "//downloads.ctfassets.net/xt8ne4gbbocd/1rIqvHUlxCgqW2caioAo4I/eaa5e32c3a5c09c5904157da0d3a9f0b/KENLAI0060017.jpg" caption: Ndorobo man observing Maa-speaker symbols, possibly representing cattle brands. Laikipia 2013,2034.13018 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3700186&partId=1&searchText=2013,2034.13018&page=1 - sys: id: 63k9ZNUpEW0wseK2kKmSS2 created_at: !ruby/object:DateTime 2015-11-26 15:32:19.445000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:32:19.445000000 Z content_type_id: chapter revision: 1 title_internal: 'Kenya: country, chapter 6' body: It is instructive to consider the use of rock art sites within their physical contexts as well as the rock art motifs themselves. Locality and landscape are significant, for example at Namoratung’a, where the engraved basalt pillars at a related nearby site have been posited to be positioned according to astronomical calculations, based on an ancient Cushitic calendar. There are various ways in which the creation and continued use of sites in Kenya may have been significantly interactive, such as in the ritual playing of rock gongs, or in the potential use of rows of cupules as gaming boards for forms of Mancala, a token game common through central and Southern Africa which was originally introduced to Kenya via Indian Ocean trade. It is not known if cupules were actually created for this purpose—it has been suggested for example that in some areas, cupules were formed for purely practical purposes, in the pulverising of food or materials for smelting activities. In Kenya, as elsewhere, what actually constitutes rock art is not always easy to identify. - sys: id: 473wFp8s7CKyuyuIW22KCs created_at: !ruby/object:DateTime 2015-11-26 15:26:01.650000000 Z updated_at: !ruby/object:DateTime 2017-01-23 16:01:02.004000000 Z content_type_id: image revision: 2 image: sys: id: 6CNVylYrKwUkk0YCcaYmE4 created_at: !ruby/object:DateTime 2015-11-26 15:20:17.930000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:20:17.930000000 Z title: '2013,2034.13694' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6CNVylYrKwUkk0YCcaYmE4/084ab0278a8863a0cbc3ac1f631eceea/KENNEP0020002.jpg" caption: Rock gong with cupules. Lewa Downs Conservancy, Kenya. 2013,2034.13694 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3701781&partId=1&searchText=2013,2034.13694&page=1 - sys: id: 24Sdya41Gk4migwmYa60SW created_at: !ruby/object:DateTime 2015-11-26 15:32:57.237000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:32:57.237000000 Z content_type_id: chapter revision: 1 title: Chronology title_internal: 'Kenya: country, chapter 7' body: "Rock art ascribed to Batwa peoples could be anywhere between 15,000-1,000 years old, while pastoralist art is more recent. Radiocarbon dating of rock art is difficult unless it is buried and associated with other uncontaminated organic remains and as such, scientifically dated rock art from Kenya is rare. \ Radiocarbon dates from human remains in graves at Namoratung’a South date from the mid-1st Century BC to the mid-1st Millennium AD, but as dates like these are not directly relatable to the rock art, researchers have tended to concentrate on assigning chronologies based on varying levels of patination and style, without being able to ascribe more than estimated production dates. \ \n\nThere are occasionally defining limits which aid in dating specific sites, for example, cattle did not arrive in Eastern Africa until about 2,000 BC, so representations of cattle must postdate this. In addition, in some cases, artworks known to have been associated with certain groups cannot have been produced prior to, or post, certain dates for political reasons. For example, Masai paintings at Lukenya Hill are known to have been painted prior to 1915, as Masai people were displaced from this area by European settlers after this date. \n\nThe diversity of Kenyan rock art in motif, distribution and cultural context so far frustrates any attempts for a cohesive chronology, but the continuing local engagement with rock art sites in Kenya can potentially serve as a useful dating and interpretive resource for researchers alongside continuing archaeological research." - sys: id: 5FBcxryfEQMUwYeYakwMSo created_at: !ruby/object:DateTime 2015-11-26 15:26:31.130000000 Z updated_at: !ruby/object:DateTime 2017-01-23 16:41:13.806000000 Z content_type_id: image revision: 4 image: sys: id: 4dt5Tw7AXeoiMOkAqGIoWa created_at: !ruby/object:DateTime 2015-12-08 18:49:43.959000000 Z updated_at: !ruby/object:DateTime 2015-12-08 18:49:43.959000000 Z title: KENTUR0010065 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/4dt5Tw7AXeoiMOkAqGIoWa/53ffe55ad755f4931e5651e84da47892/KENTUR0010065_1.jpg" caption: Engraved rock art showing giraffes and human figures. Turkana County, Lewa Downs Conservancy, Kenya. 2013,2034.13848 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3663256&partId=1&searchText=2013,2034.13848+&page=1 citations: - sys: id: 1r3TUrs7ziOaQ08iEOQ2gC created_at: !ruby/object:DateTime 2015-11-26 15:27:37.639000000 Z updated_at: !ruby/object:DateTime 2015-12-11 11:55:17.747000000 Z content_type_id: citation revision: 2 citation_line: | <NAME>. 1975. *Meat-feasting Sites and Cattle Brands: Patterns of Rock-shelter Utilization in East Africa*. Azania, Vol. 10, Issue 1, pp. 107-122 <NAME>. & <NAME>. 2011. *A re-consideration of the rock engravings at the burial site of Namoratung'a South, Northern Kenya and their relationship to modern Turkana livestock brands*. South African Archaeological Bulletin Vol. 66, Issue194, pp. 121-128 <NAME>. 1992. *Ethnographic Context of Rock Art Sites in East Africa in Rock Art and Ethnology*. AURA Occasional Papers, (5) pp. 67-70, Australian Rock Art Research Association, Melbourne <NAME>. 1974. *The Prehistoric rock art of the lake Victoria region*. Azania, IX, 1-50. background_images: - sys: id: 7JF9Ak3hSweI08A2yGWmS6 created_at: !ruby/object:DateTime 2015-12-07 14:41:52.645000000 Z updated_at: !ruby/object:DateTime 2015-12-07 14:41:52.645000000 Z title: KENLAI0100040 description: url: "//images.ctfassets.net/xt8ne4gbbocd/7JF9Ak3hSweI08A2yGWmS6/fc1cbbd8cb63d11171e90628da912f56/KENLAI0100040.jpg" - sys: id: 2YMos8alGoki4kygMAoaAe created_at: !ruby/object:DateTime 2015-12-08 18:21:55.084000000 Z updated_at: !ruby/object:DateTime 2015-12-08 18:21:55.084000000 Z title: KENMTE0010018 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/2YMos8alGoki4kygMAoaAe/6d3bf422e638dc9ca68529fff280ab54/KENMTE0010018_1.jpg" - sys: id: 6CNVylYrKwUkk0YCcaYmE4 created_at: !ruby/object:DateTime 2015-11-26 15:20:17.930000000 Z updated_at: !ruby/object:DateTime 2015-11-26 15:20:17.930000000 Z title: '2013,2034.13694' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6CNVylYrKwUkk0YCcaYmE4/084ab0278a8863a0cbc3ac1f631eceea/KENNEP0020002.jpg" region: Eastern and central Africa ---<file_sep>/_coll_country/angola.md --- contentful: sys: id: 2ewvBc9EUU0soG8q6G0sYi created_at: !ruby/object:DateTime 2015-12-08 11:21:05.925000000 Z updated_at: !ruby/object:DateTime 2019-03-19 12:17:58.161000000 Z content_type_id: country revision: 12 name: Angola slug: angola col_url: http://www.britishmuseum.org/research/collection_online/search.aspx?people=197356&place=40180|108377|108375|108376 map_progress: true intro_progress: true image_carousel: - sys: id: 60WuYok9POoqaG2QuksOWI created_at: !ruby/object:DateTime 2016-07-27 07:46:34.096000000 Z updated_at: !ruby/object:DateTime 2019-02-12 02:16:12.785000000 Z title: '2013,2034.21210' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3744322&partId=1&searchText=ANGTCH0010007&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/60WuYok9POoqaG2QuksOWI/0786f5b209c940eb57e2fa98b10f6cfb/ANGTCH0010007.jpg" - sys: id: 2QisYKsWSc80c2yUiIk0Go created_at: !ruby/object:DateTime 2016-07-27 07:46:34.027000000 Z updated_at: !ruby/object:DateTime 2019-02-12 02:16:58.564000000 Z title: '2013,2034.21221' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3744353&partId=1&searchText=ANGTCH0010018&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/2QisYKsWSc80c2yUiIk0Go/3c8a4c79db40f226e509bdd5f725d22e/ANGTCH0010018.jpg" - sys: id: 63TUaYUyIgSsWOuuAS0AKC created_at: !ruby/object:DateTime 2016-07-27 07:46:33.976000000 Z updated_at: !ruby/object:DateTime 2019-02-12 02:18:14.201000000 Z title: '2013,2034.21212' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3744320&partId=1&searchText=ANGTCH0010009&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/63TUaYUyIgSsWOuuAS0AKC/4ca377114c3f9c20f61be18259c7e5bc/ANGTCH0010009.jpg" - sys: id: 3jSBg1HwJiC2MmWkuWmOUs created_at: !ruby/object:DateTime 2016-07-27 07:46:33.302000000 Z updated_at: !ruby/object:DateTime 2019-02-12 02:19:05.735000000 Z title: '2013,2034.21224' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3744348&partId=1&searchText=ANGTCH0010021&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/3jSBg1HwJiC2MmWkuWmOUs/b5f46574259ccb7c9f94f830abaae640/ANGTCH0010021.jpg" featured_site: sys: id: 4COYtGhxoAuK82cGysc2cu created_at: !ruby/object:DateTime 2016-07-27 07:45:12.121000000 Z updated_at: !ruby/object:DateTime 2017-11-29 19:47:47.835000000 Z content_type_id: featured_site revision: 3 title: Tchitundu-Hulu slug: tchitundu-hulu chapters: - sys: id: 26QSCtJ2726k0U4WG4uCS2 created_at: !ruby/object:DateTime 2016-07-27 07:45:13.927000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:45:13.927000000 Z content_type_id: chapter revision: 1 title_internal: 'Angola: featured site, chapter 1' body: 'Tchitundu-Hulu is the generic name for a group of four rock art sites located in the Namibe province on the south-west corner of Angola, by the edge of the Namib desert, about 120 km from the sea. It is a semi-arid plain characterized by the presence of several inselbergs (isolated hills rising from the plain), the most important of which is Tchitundu-Hulu Mulume. The group of rock art sites are surrounded by several seasonal rivers, within a maximum distance of 1 km. Tchitundu-Hulu was first documented by <NAME> in 1953, and since then it has become one of the most studied rock art sites in Angola, attracting the interest of renowned researchers such as <NAME>, J. <NAME> and Santos Junior. In 2014 one of the sites was the subject of a Masters dissertation (Caema 2014), the latest addition to the long term research on the site. ' - sys: id: 4gU0r5PSy4CC8Q00ccMMuY created_at: !ruby/object:DateTime 2016-07-27 07:45:15.741000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:45:15.741000000 Z content_type_id: image revision: 1 image: sys: id: 7MqUsgyUhi8IIoM8sGKKAO created_at: !ruby/object:DateTime 2016-07-27 07:46:36.210000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:36.210000000 Z title: ANGTCH0010003 description: url: "//images.ctfassets.net/xt8ne4gbbocd/7MqUsgyUhi8IIoM8sGKKAO/01aa753abbbd4fa8224263f644d78b1c/ANGTCH0010003.jpg" caption: "landscape showing an inselberg in the background. Tchitundu-Hulu, Angola. 2013,2034.21206 © TARA/<NAME> \t" col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3744327&partId=1 - sys: id: 3PYi7QceDKQa44gamOE0o4 created_at: !ruby/object:DateTime 2016-07-27 07:45:13.877000000 Z updated_at: !ruby/object:DateTime 2018-05-09 16:30:01.864000000 Z content_type_id: chapter revision: 2 title_internal: 'Angola: featured site, chapter 2' body: 'As forementioned, Tchitundu-Hulu comprises four rock art sites: Tchitundu-Hulu Mulume, Tchitundu-Hulu Mucai, Pedra das Zebras and Pedra da Lagoa. The first two combine paintings and engravings, while the latter only have engravings. Pedra das Zebras and Pedra da Lagoa are Portuguese names which can be translated as the Rock of the Zebras and the Rock of the Pond, but the name of Tchitundu-Hulu has different interpretations in the local languages –the hill of heaven, the hill of the souls or the sacred hill- while Mulume and Mucai are translated as man and woman, respectively. Therefore, the local names of the site point to a deep meaning within the communities that inhabited the region. ' - sys: id: fm44bXnRYc0OiwS4Ywogw created_at: !ruby/object:DateTime 2016-07-27 07:45:13.865000000 Z updated_at: !ruby/object:DateTime 2018-05-09 16:30:34.170000000 Z content_type_id: chapter revision: 2 title_internal: 'Angola: featured site, chapter 3' body: 'Of the four sites, Tchitundu-Hulu Mulume is the largest , located at the top of the inselberg, 726m in height. The slopes of the outcrop are covered by large engravings, most of them consisting of circle-like shapes (simple or concentric circles, solar-like images), although some depictions of human figures or animals are also present. In a shelter on the top of the outcrop more than 180 images can be found painted in red or white, with geometric shapes being again widely predominant. The depictions have abundant superimpositions and cover the walls, roof and base of the shelter. ' - sys: id: 35UGg2OapGC2qG4O4Eo2I0 created_at: !ruby/object:DateTime 2016-07-27 07:45:15.726000000 Z updated_at: !ruby/object:DateTime 2018-05-09 16:42:06.863000000 Z content_type_id: image revision: 2 image: sys: id: 2KFJl6V2WsekUsMaq8M4Ga created_at: !ruby/object:DateTime 2016-07-27 07:46:36.151000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:36.151000000 Z title: ANGTCH0010019 description: url: "//images.ctfassets.net/xt8ne4gbbocd/2KFJl6V2WsekUsMaq8M4Ga/8fd5bad6be6601f1a589674820b0770d/ANGTCH0010019.jpg" caption: Pecked concentric lines. Tchitundu-Hulu Mulume, Angola. 2013,2034.21222 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3744352&partId=1 - sys: id: 4RvVnpbsXK0YcYSUUYyw68 created_at: !ruby/object:DateTime 2016-07-27 07:45:13.862000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:45:13.862000000 Z content_type_id: chapter revision: 1 title_internal: 'Angola: featured site, chapter 4' body: 'In comparison, Tchitundu-Hulu Mucai is situated on the plain around 1,000 m from the inselberg, in a rock outcrop containing engravings on the top and a shelter at its base covered by painted rock art. The characteristics of both engravings and paintings are similar to those of Tchitundu-Hulu Mulume, although some black figures are present, too. Paintings often combine two, three or even more colours, and consist mainly of geometric signs, although there are anthropomorphs and zoomorphs, in some cases grouped in what seem hunting scenes. The other two sites (the Rock of the Zebras and the Rock of the Pond) consist of engravings similar to those of Tchitundu-Hulu Mulume, and in some cases their different patinas show that they were made in different periods. ' - sys: id: iZUL3BpxqEII82IQGGGGC created_at: !ruby/object:DateTime 2016-07-27 07:45:14.951000000 Z updated_at: !ruby/object:DateTime 2018-05-09 16:42:37.270000000 Z content_type_id: image revision: 2 image: sys: id: 1HfdgOK6lC4aCke6we2UGW created_at: !ruby/object:DateTime 2016-07-27 07:46:36.033000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:36.033000000 Z title: ANGTCH0010005 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1HfdgOK6lC4aCke6we2UGW/308f6b611eeec141c864e431073bf615/ANGTCH0010005.jpg" caption: Paintings at Tchitundu-Hulu Mulume, Angola. 2013,2034.21208 © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3744324&partId=1 - sys: id: 5ngD52eGekKEMI2UMeGUWs created_at: !ruby/object:DateTime 2016-07-27 07:45:13.771000000 Z updated_at: !ruby/object:DateTime 2016-07-27 09:29:43.491000000 Z content_type_id: chapter revision: 2 title: '' title_internal: 'Angola: featured site, chapter 5' body: 'The chronology of the Tchitundu-Hulu rock art is difficult to establish, and it is unclear if the four sites are of the same period at all. Theories based on the lithic tools dispersed throughout the area ascribed the paintings to an ancient time period, possibly tens of thousands of years old. Radiocarbon samples coming from the excavation of Tchitundu-Hulu Mulume showed a date in the early 1st millennium BC, although the relation of the archaeological remains and the paintings has not been proved and archaeological materials of a more modern period were also located. A sample taken from the pigments at the site rendered a date of the beginning of the first centuries of the 1st millennium AD. In any case, Tchitundu-Hulu hosts some of the oldest examples of rock art in the country, and it has been linked to the schematic traditions that characterize the rock art of Central Africa, more abundant in central Mozambique and Malawi. ' - sys: id: 6MjjzjwufSQ6QqMqwweiaE created_at: !ruby/object:DateTime 2016-07-27 07:45:14.829000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:45:14.829000000 Z content_type_id: image revision: 1 image: sys: id: 6u3Ewi14cgUU28MWOQ0WMI created_at: !ruby/object:DateTime 2016-07-27 07:46:36.182000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:36.182000000 Z title: ANGTCH0010011 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6u3Ewi14cgUU28MWOQ0WMI/6b84b50d8dd0daaefff6ac33cf7799a3/ANGTCH0010011.jpg" caption: Red and white oval-like figure (bird?). 2013,2034.21214 © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3744318&partId=1 - sys: id: 4pyURXLHpYAWm8m882EKqw created_at: !ruby/object:DateTime 2016-07-27 07:45:13.737000000 Z updated_at: !ruby/object:DateTime 2016-07-27 09:30:49.386000000 Z content_type_id: chapter revision: 2 title: '' title_internal: 'Angola: featured site, chapter 6' body: The question of who made the engravings or paintings is another complex issue for the interpretation of the Tchitundu-Hulu depictions. The harsh conditions of this semi-desert area probably favoured a seasonal occupation of the region during the rainy season. The location of Tchitundu-Hulu at the edge of the desert could also have made this place a strategic site for the communities living in the region. Several local groups - Kwisi, Kuvale - have traditionally inhabited the area, but the authorship of these engravings and paintings and the motives for creating them remains obscure, as does the purpose and cultural context of the complex images of Tchitundu-Hulu. citations: - sys: id: txWp29xSGOSkuqgOYgeSi created_at: !ruby/object:DateTime 2016-07-27 07:45:30.621000000 Z updated_at: !ruby/object:DateTime 2016-07-27 09:59:36.553000000 Z content_type_id: citation revision: 3 citation_line: "<NAME>. (2014): 'As pinturas do abrigo do Tchitundu-Hulu Mucai. Um contributo para o conhecimento da arte rupestre da região.' Unpublished Masters dissertation \nInstituto Politécnico de Tomar – Universidade de Trás-os-Montes e Alto Douro. Available at <http://comum.rcaap.pt/handle/10400.26/8309>\n" background_images: - sys: id: 60WuYok9POoqaG2QuksOWI created_at: !ruby/object:DateTime 2016-07-27 07:46:34.096000000 Z updated_at: !ruby/object:DateTime 2019-02-12 02:16:12.785000000 Z title: '2013,2034.21210' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3744322&partId=1&searchText=ANGTCH0010007&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/60WuYok9POoqaG2QuksOWI/0786f5b209c940eb57e2fa98b10f6cfb/ANGTCH0010007.jpg" - sys: id: 40lIKwvi8gwo4ckmuKguYk created_at: !ruby/object:DateTime 2016-07-27 07:47:54.905000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:47:54.905000000 Z title: ANGTCH0010022` description: url: "//images.ctfassets.net/xt8ne4gbbocd/40lIKwvi8gwo4ckmuKguYk/074e930f8099bbfdf9dd872f874c3a32/ANGTCH0010022.jpg" key_facts: sys: id: 2onItF5XAo8ka8YWUsIAsu created_at: !ruby/object:DateTime 2016-07-27 07:45:24.354000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:45:24.354000000 Z content_type_id: country_key_facts revision: 1 title_internal: 'Angola: Key Facts' image_count: '26' date_range: 1,000 BC BC to 17th century AD main_areas: Tchitundu-Hulu techniques: Engravings and paintings main_themes: Wild animals, human figures, hunting or war scenes, geometric symbols thematic_articles: - sys: id: 5HZTuIVN8AASS4ikIea6m6 created_at: !ruby/object:DateTime 2017-12-19 12:27:08.508000000 Z updated_at: !ruby/object:DateTime 2017-12-19 12:27:08.508000000 Z content_type_id: thematic revision: 1 title: Introduction to rock art in central and eastern Africa slug: rock-art-in-central-and-east-africa lead_image: sys: id: 3esXNapo5GOWIKSImcY4QW created_at: !ruby/object:DateTime 2015-11-25 18:56:43.836000000 Z updated_at: !ruby/object:DateTime 2017-12-15 17:01:05.082000000 Z title: '2013,2034.12982' description: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3776396 url: "//images.ctfassets.net/xt8ne4gbbocd/3esXNapo5GOWIKSImcY4QW/6436b2034659eccb953844b21a400070/2013_2034.12982.jpg" chapters: - sys: id: 4ln5fQLq2saMKsOA4WSAgc created_at: !ruby/object:DateTime 2015-11-25 19:09:33.580000000 Z updated_at: !ruby/object:DateTime 2015-12-11 11:17:25.155000000 Z content_type_id: chapter revision: 4 title: Central and East Africa title_internal: 'East Africa: regional, chapter 1' body: |- Central Africa is dominated by vast river systems and lakes, particularly the Congo River Basin. Characterised by hot and wet weather on both sides of the equator, central Africa has no regular dry season, but aridity increases in intensity both north and south of the equator. Covered with a forest of about 400,000 m² (1,035,920 km²), it is one of the greenest parts of the continent. The rock art of central Africa stretches from the Zambezi River to the Angolan Atlantic coast and reaches as far north as Cameroon and Uganda. Termed the ‘schematic rock art zone’ by <NAME> (1959), it is dominated by finger-painted geometric motifs and designs, thought to extend back many thousands of years. Eastern Africa, from the Zambezi River Valley to Lake Turkana, consists largely of a vast inland plateau with the highest elevations on the continent, such as Mount Kilimanjaro (5,895m above sea level) and Mount Kenya (5,199 m above sea level). Twin parallel rift valleys run through the region, which includes the world’s second largest freshwater lake, Lake Victoria. The climate is atypical of an equatorial region, being cool and dry due to the high altitude and monsoon winds created by the Ethiopian Highlands. The rock art of eastern Africa is concentrated on this plateau and consists mainly of paintings that include animal and human representations. Found mostly in central Tanzania, eastern Zambia and Malawi; in comparison to the widespread distribution of geometric rock art, this figurative tradition is much more localised, and found at just a few hundred sites in a region of less than 100km in diameter. - sys: id: 4nyZGLwHTO2CK8a2uc2q6U created_at: !ruby/object:DateTime 2015-11-25 18:57:48.121000000 Z updated_at: !ruby/object:DateTime 2017-12-15 17:05:00.916000000 Z content_type_id: image revision: 2 image: sys: id: 3esXNapo5GOWIKSImcY4QW created_at: !ruby/object:DateTime 2015-11-25 18:56:43.836000000 Z updated_at: !ruby/object:DateTime 2017-12-15 17:01:05.082000000 Z title: '2013,2034.12982' description: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3776396 url: "//images.ctfassets.net/xt8ne4gbbocd/3esXNapo5GOWIKSImcY4QW/6436b2034659eccb953844b21a400070/2013_2034.12982.jpg" caption: <NAME>. 2013,2034.12982 © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3776396 - sys: id: 1OvIWDPyXaCO2gCWw04s06 created_at: !ruby/object:DateTime 2015-11-25 19:10:23.723000000 Z updated_at: !ruby/object:DateTime 2015-12-11 11:18:19.325000000 Z content_type_id: chapter revision: 2 title_internal: 'East Africa: regional, chapter 2' body: This collection from Central and East Africa comprises rock art from Kenya, Uganda and Tanzania, as well as the Horn of Africa; although predominantly paintings, engravings can be found in most countries. - sys: id: 4JqI2c7CnYCe8Wy2SmesCi created_at: !ruby/object:DateTime 2015-11-25 19:10:59.991000000 Z updated_at: !ruby/object:DateTime 2016-10-17 13:34:14.653000000 Z content_type_id: chapter revision: 3 title: History of research title_internal: 'East Africa: regional, chapter 3' body: |- The rock art of East Africa, in particular the red paintings from Tanzania, was extensively studied by Mary and <NAME> in the 1930s and 1950s. <NAME> observed Sandawe people of Tanzania making rock paintings in the mid-20th century, and on the basis of oral traditions argued that the rock art was made for three main purposes: casual art; magic art (for hunting purposes or connected to health and fertility) and sacrificial art (to appease ancestral spirits). Subsequently, during the 1970s Fidelis Masao and <NAME> recorded numerous sites, classifying the art in broad chronological and stylistic categories, proposing tentative interpretations with regard to meaning. There has much debate and uncertainty about Central African rock art. The history of the region has seen much mobility and interaction of cultural groups and understanding how the rock art relates to particular groups has been problematic. Pioneering work in this region was undertaken by <NAME> in central Malawi in the early 1920s, <NAME> visited Zambia in 1936 and attempted to provide a chronological sequence and some insight into the meaning of the rock art. Since the 1950s (Clarke, 1959), archaeologists have attempted to situate rock art within broader archaeological frameworks in order to resolve chronologies, and to categorise the art with reference to style, colour, superimposition, subject matter, weathering, and positioning of depictions within the panel (Phillipson, 1976). Building on this work, our current understanding of rock in this region has been advanced by <NAME> (1995, 1997, 2001) with his work in Zambia and Malawi. - sys: id: 35HMFoiKViegWSY044QY8K created_at: !ruby/object:DateTime 2015-11-25 18:59:25.796000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:51:25.789000000 Z content_type_id: image revision: 5 image: sys: id: 6KOxC43Z9mYCuIuqcC8Qw0 created_at: !ruby/object:DateTime 2015-11-25 18:57:00.077000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:57:00.077000000 Z title: '2013,2034.17450' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6KOxC43Z9mYCuIuqcC8Qw0/e25141d07f483d0100c4cf5604e3e525/2013_2034.17450.jpg" caption: This painting of a large antelope is possibly one of the earliest extant paintings. <NAME> believes similar paintings could be more than 28,000 years old. 2013,2034.17450 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3711689 - sys: id: 1dSBI9UNs86G66UGSEOOkS created_at: !ruby/object:DateTime 2015-12-09 11:56:31.754000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:50:18.203000000 Z content_type_id: chapter revision: 5 title: East African Rock Art title_internal: Intro to east africa, chapter 3.5 body: "Rock art of East Africa consists mainly of paintings, most of which are found in central Tanzania, and are fewer in number in eastern Zambia and Malawi; scholars have categorised them as follows:\n\n*__Red Paintings__*: \nRed paintings can be sub-divided into those found in central Tanzania and those found stretching from Zambia to the Indian Ocean.\nTanzanian red paintings include large, naturalistic animals with occasional geometric motifs. The giraffe is the most frequently painted animal, but antelope, zebra, elephant, rhino, felines and ostrich are also depicted. Later images show figures with highly distinctive stylised human head forms or hairstyles and body decoration, sometimes in apparent hunting and domestic scenes. The Sandawe and Hadza, hunter-gatherer groups, indigenous to north-central and central Tanzania respectively, claim their ancestors were responsible for some of the later art.\n\nThe area in which Sandawe rock art is found is less than 100km in diameter and occurs at just a few hundred sites, but corresponds closely to the known distribution of this group. There have been some suggestions that Sandawe were making rock art early into the 20th century, linking the art to particular rituals, in particular simbo; a trance dance in which the Sandawe communicate with the spirit world by taking on the power of an animal. The art displays a range of motifs and postures, features that can be understood by reference to simbo and to trance experiences; such as groups of human figures bending at the waist (which occurs during the *simbo* dance), taking on animal features such as ears and tails, and floating or flying; reflecting the experiences of those possessed in the dance." - sys: id: 7dIhjtbR5Y6u0yceG6y8c0 created_at: !ruby/object:DateTime 2015-11-25 19:00:07.434000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:51:51.887000000 Z content_type_id: image revision: 5 image: sys: id: 1fy9DD4BWwugeqkakqWiUA created_at: !ruby/object:DateTime 2015-11-25 18:57:11.188000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:57:11.188000000 Z title: '2013,2034.16849' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1fy9DD4BWwugeqkakqWiUA/9f8f1330c6c0bc0ff46d744488daa152/2013_2034.16849.jpg" caption: Three schematic figures formed by the use of multiple thin parallel lines. The shape and composition of the heads suggests either headdresses or elaborate hairstyles. Kondoa, Tanzania. 2013,2034.16849 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3709812 - sys: id: 1W573pi2Paks0iA8uaiImy created_at: !ruby/object:DateTime 2015-11-25 19:12:00.544000000 Z updated_at: !ruby/object:DateTime 2015-12-11 11:21:09.647000000 Z content_type_id: chapter revision: 8 title_internal: 'East Africa: regional, chapter 4' body: "Zambian rock art does not share any similarities with Tanzanian rock art and can be divided into two categories; animals (with a few depictions of humans), and geometric motifs. Animals are often highly stylised and superimposed with rows of dots. Geometric designs include, circles, some of which have radiating lines, concentric circles, parallel lines and ladder shapes. Predominantly painted in red, the remains of white pigment is still often visible. <NAME> (1976) proposed that the naturalistic animals were earlier in date than geometric designs. Building on Phillipson’s work, <NAME> studied ethnographic records and demonstrated that geometric motifs were made by women or controlling the weather.\n\n*__Pastoralist paintings__*: \nPastoralist paintings are rare, with only a few known sites in Kenya and other possible sites in Malawi. Usually painted in black, white and grey, but also in other colours, they include small outlines, often infilled, of cattle and are occasional accompanied by geometric motifs. Made during the period from 3,200 to 1,800 years ago the practice ceased after Bantu language speaking people had settled in eastern Africa. Similar paintings are found in Ethiopia but not in southern Africa, and it has been assumed that these were made by Cushitic or Nilotic speaking groups, but their precise attribution remains unclear (Smith, 2013:154).\n" - sys: id: 5jReHrdk4okicG0kyCsS6w created_at: !ruby/object:DateTime 2015-11-25 19:00:41.789000000 Z updated_at: !ruby/object:DateTime 2017-12-15 17:10:04.890000000 Z content_type_id: image revision: 3 image: sys: id: 1hoZEK3d2Oi8iiWqoWACo created_at: !ruby/object:DateTime 2015-11-25 18:56:43.848000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:56:43.848000000 Z title: '2013,2034.13653' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1hoZEK3d2Oi8iiWqoWACo/1a1adcfad5d5a1cf0a341316725d61c4/2013_2034.13653.jpg" caption: Two red bulls face right. <NAME>. 2013,2034.13653. © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3700058 - sys: id: 7rFAK9YoBqYs0u0EmCiY64 created_at: !ruby/object:DateTime 2015-11-25 19:00:58.494000000 Z updated_at: !ruby/object:DateTime 2017-12-15 17:11:37.760000000 Z content_type_id: image revision: 3 image: sys: id: 3bqDVyvXlS0S6AeY2yEmS8 created_at: !ruby/object:DateTime 2015-11-25 18:56:43.880000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:56:43.880000000 Z title: '2013,2034.13635' description: url: "//images.ctfassets.net/xt8ne4gbbocd/3bqDVyvXlS0S6AeY2yEmS8/c9921f3d8080bcef03c96c6b8f1b0323/2013_2034.13635.jpg" caption: Two cattle with horns in twisted perspective. Mt Elgon, Kenya. 2013,2034.13635. © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3698905 - sys: id: 1tX4nhIUgAGmyQ4yoG6WEY created_at: !ruby/object:DateTime 2015-11-25 19:14:33.823000000 Z updated_at: !ruby/object:DateTime 2015-11-25 19:14:33.823000000 Z content_type_id: chapter revision: 1 title_internal: 'East Africa: regional, chapter 5' body: |- *__Late White Paintings__*: Commonly painted in white, or off-white with the fingers, so-called ‘Late White’ depictions include quite large crudely rendered representations of wild animals, mythical animals, human figures and numerous geometric motifs. These paintings are attributed to Bantu language speaking, iron-working farmers who entered eastern Africa about 2,000 years ago from the west on the border of Nigeria and Cameroon. Moving through areas occupied by the Batwa it is thought they learned the use of symbols painted on rock, skin, bark cloth and in sand. Chewa peoples, Bantu language speakers who live in modern day Zambia and Malawi claim their ancestors made many of the more recent paintings which they used in rites of passage ceremonies. - sys: id: 35dNvNmIxaKoUwCMeSEO2Y created_at: !ruby/object:DateTime 2015-11-25 19:01:26.458000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:52:15.838000000 Z content_type_id: image revision: 4 image: sys: id: 6RGZZQ13qMQwmGI86Ey8ei created_at: !ruby/object:DateTime 2015-11-25 18:57:11.188000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:57:11.188000000 Z title: '2013,2034.16786' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6RGZZQ13qMQwmGI86Ey8ei/6d37a5bed439caf7a1223aca27dc27f8/2013_2034.16786.jpg" caption: Under a long narrow granite overhang, Late White designs including rectangular grids, concentric circles and various ‘square’ shapes. 2013,2034.16786 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3709608 - sys: id: 2XW0X9BzFCa8u2qiKu6ckK created_at: !ruby/object:DateTime 2015-11-25 19:01:57.959000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:53:21.559000000 Z content_type_id: image revision: 4 image: sys: id: 1UT4r6kWRiyiUIYSkGoACm created_at: !ruby/object:DateTime 2015-11-25 18:57:11.138000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:57:11.138000000 Z title: '2013,2034.16797' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1UT4r6kWRiyiUIYSkGoACm/fe915c6869b6c195d55b5ef805df7671/2013_2034.16797.jpg" caption: A monuments guard stands next to Late White paintings attributed to Bantu speaking farmers in Tanzania, probably made during the last 700 years. 2013,2034.16797 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3709628 - sys: id: 3z28O8A58AkgMUocSYEuWw created_at: !ruby/object:DateTime 2015-11-25 19:15:04.047000000 Z updated_at: !ruby/object:DateTime 2015-11-25 19:15:04.047000000 Z content_type_id: chapter revision: 1 title_internal: 'East Africa: regional, chapter 6' body: |- *__Meat-feasting paintings__*: Meat-feasting shelters exist from northern Tanzania through Kenya to Lake Turkana, and are places where Maa-speaking initiated men, who are not permitted to eat meat in their homes, gather to kill and feast on animals, predominantly cattle. The term Maa relates to a group of closely related Eastern Nilotic languages, which historically dominated the east African hinterland; and today is spoken by around a million people. During or after feasting, symbols of the animals that had been eaten were painted on the shelter ceiling in white or less often red. Maa speakers brand their cattle and camels with symbols that signify the lineage of their owners, but may also indicate if an animal has been treated for a particular disease. Different symbols may be used for male and female animals. Over the centuries, because the depictions are on the ceiling of meat feasting rock shelters, and because sites are used even today, a build-up of soot has obscured or obliterated the paintings. Unfortunately, few have been recorded or mapped. - sys: id: 1yjQJMFd3awKmGSakUqWGo created_at: !ruby/object:DateTime 2015-11-25 19:02:23.595000000 Z updated_at: !ruby/object:DateTime 2017-12-15 17:19:11.619000000 Z content_type_id: image revision: 3 image: sys: id: p4E0BRJzossaus6uUUkuG created_at: !ruby/object:DateTime 2015-11-25 18:56:49.743000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:56:49.743000000 Z title: '2013,2034.13004' description: url: "//images.ctfassets.net/xt8ne4gbbocd/p4E0BRJzossaus6uUUkuG/13562eee76ac2a9efe8c0d12e62fa23a/2013_2034.13004.jpg" caption: Huge granite boulder with Ndorobo man standing before a rock overhang used for meat-feasting. Laikipia, Kenya. 2013,2034. 13004. © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3700175 - sys: id: 6lgjLZVYrY606OwmwgcmG2 created_at: !ruby/object:DateTime 2015-11-25 19:02:45.427000000 Z updated_at: !ruby/object:DateTime 2017-12-15 17:20:14.877000000 Z content_type_id: image revision: 3 image: sys: id: 1RLyVKKV8MA4KEk4M28wqw created_at: !ruby/object:DateTime 2015-11-25 18:57:11.150000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:57:11.150000000 Z title: '2013,2034.13018' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1RLyVKKV8MA4KEk4M28wqw/044529be14a590fd1d0da7456630bb0b/2013_2034.13018.jpg" caption: This symbol is probably a ‘brand’ used on cattle that were killed and eaten at a Maa meat feast. Laikipia, Kenya. 2013,2034.13018 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3700193 - sys: id: 5UQc80DUBiqqm64akmCUYE created_at: !ruby/object:DateTime 2015-11-25 19:15:34.582000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:53:53.936000000 Z content_type_id: chapter revision: 4 title: Central African Rock Art title_internal: 'East Africa: regional, chapter 7' body: The rock art of central Africa is attributed to hunter-gatherers known as Batwa. This term is used widely in eastern central and southern Africa to denote any autochthonous hunter-gatherer people. The rock art of the Batwa can be divided into two categories which are quite distinctive stylistically from the Tanzanian depictions of the Sandawe and Hadza. Nearly 3,000 sites are currently known from within this area. The vast majority, around 90%, consist of finger-painted geometric designs; the remaining 10% include highly stylised animal forms (with a few human figures) and rows of finger dots. Both types are thought to date back many thousands of years. The two traditions co-occur over a vast area of eastern and central Africa and while often found in close proximity to each other are only found together at a few sites. However, it is the dominance of geometric motifs that make this rock art tradition very distinctive from other regions in Africa. - sys: id: 4m51rMBDX22msGmAcw8ESw created_at: !ruby/object:DateTime 2015-11-25 19:03:40.666000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:54:25.415000000 Z content_type_id: image revision: 4 image: sys: id: 2MOrR79hMcO2i8G2oAm2ik created_at: !ruby/object:DateTime 2015-11-25 18:56:49.737000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:56:49.737000000 Z title: '2013,2034.15306' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2MOrR79hMcO2i8G2oAm2ik/86179e84233956e34103566035c14b76/2013_2034.15306.jpg" caption: Paintings in red and originally in-filled in white cover the underside of a rock shelter roof. The art is attributed to central African Batwa; the age of the paintings is uncertain. Lake Victoria, Uganda. 2013,2034.15306 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3691242 - sys: id: 5rNOG3568geMmIEkIwOIac created_at: !ruby/object:DateTime 2015-11-25 19:16:07.130000000 Z updated_at: !ruby/object:DateTime 2015-11-25 19:16:19.722000000 Z content_type_id: chapter revision: 2 title_internal: 'East Africa: regional, chapter 8' body: "*__Engravings__*:\nThere are a few engravings occurring on inland plateaus but these have elicited little scientific interest and are not well documented. \ Those at the southern end of Lake Turkana have been categorised into two types: firstly, animals, human figures and geometric forms and also geometric forms thought to involve lineage symbols.\nIn southern Ethiopia, near the town of Dillo about 300 stelae, some of which stand up to two metres in height, are fixed into stones and mark grave sites. People living at the site ask its spirits for good harvests. \n" - sys: id: LrZuJZEH8OC2s402WQ0a6 created_at: !ruby/object:DateTime 2015-11-25 19:03:59.496000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:54:51.576000000 Z content_type_id: image revision: 5 image: sys: id: 1uc9hASXXeCIoeMgoOuO4e created_at: !ruby/object:DateTime 2015-11-25 18:57:11.176000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:57:11.176000000 Z title: '2013,2034.16206' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1uc9hASXXeCIoeMgoOuO4e/09a7504449897509778f3b9455a42f8d/2013_2034.16206.jpg" caption: Group of anthropomorphic stelae with carved faces. <NAME>, Southern Ethiopia. 2013,2034.16206 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3703754 - sys: id: 7EBTx1IjKw6y2AUgYUkAcm created_at: !ruby/object:DateTime 2015-11-25 19:16:37.210000000 Z updated_at: !ruby/object:DateTime 2015-12-11 11:22:04.007000000 Z content_type_id: chapter revision: 2 title_internal: 'East Africa: regional, chapter 9' body: In the Sidamo region of Ethiopia, around 50 images of cattle are engraved in bas-relief on the wall of a gorge. All the engravings face right and the cows’ udders are prominently displayed. Similar engravings of cattle, all close to flowing water, occur at five other sites in the area, although not in such large numbers. - sys: id: 6MUkxUNFW8oEK2aqIEcee created_at: !ruby/object:DateTime 2015-11-25 19:04:34.186000000 Z updated_at: !ruby/object:DateTime 2017-12-19 12:22:24.891000000 Z content_type_id: image revision: 3 image: sys: id: PlhtduNGSaOIOKU4iYu8A created_at: !ruby/object:DateTime 2015-11-25 18:56:43.849000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:56:43.849000000 Z title: '2013,2034.16235' description: url: "//images.ctfassets.net/xt8ne4gbbocd/PlhtduNGSaOIOKU4iYu8A/7625c8a21caf60046ea73f184e8b5c76/2013_2034.16235.jpg" caption: Around 50 images of cattle are engraved in bas-relief into the sandstone wall of a gorge in the Sidamo region of Ethiopia. 2013,2034.16235 © TARA/David Coulson col_link: http://bit.ly/2hMU0vm - sys: id: 6vT5DOy7JK2oqgGK8EOmCg created_at: !ruby/object:DateTime 2015-11-25 19:17:53.336000000 Z updated_at: !ruby/object:DateTime 2015-12-11 11:25:38.678000000 Z content_type_id: chapter revision: 3 title: Rock art in the Horn of Africa title_internal: 'East Africa: regional, chapter 10' body: "The Horn of Africa has historically been a crossroads area between the Eastern Sahara, the Subtropical regions to the South and the Arabic Peninsula. These mixed influences can be seen in many archaeological and historical features throughout the region, the rock art being no exception. Since the early stages of research in the 1930s, a strong relationship between the rock art in Ethiopia and the Arabian Peninsula was detected, leading to the establishment of the term *Ethiopian-Arabian* rock art by <NAME> in 1971. This research thread proposes a progressive evolution from naturalism to schematism, ranging from the 4th-3rd millennium BC to the near past. Although the *Ethiopian-Arabian* proposal is still widely accepted and stylistic similarities between the rock art of Somalia, Ethiopia, Yemen or Saudi Arabia are undeniable, recent voices have been raised against the term because of its excessive generalisation and lack of operability. In addition, recent research to the south of Ethiopia have started to discover new rock art sites related to those found in Uganda and Kenya.\n\nRegarding the main themes of the Horn of Africa rock art, cattle depictions seem to have been paramount, with cows and bulls depicted either isolated or in herds, frequently associated with ritual scenes which show their importance in these communities. Other animals – zebus, camels, felines, dogs, etc. – are also represented, as well as rows of human figures, and fighting scenes between warriors or against lions. Geometric symbols are also common, usually associated with other depictions; and in some places they have been interpreted as tribal or clan marks. Both engraving and painting is common in most regions, with many regional variations. \n" - sys: id: 4XIIE3lDZYeqCG6CUOYsIG created_at: !ruby/object:DateTime 2015-11-25 19:04:53.913000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:55:12.472000000 Z content_type_id: image revision: 4 image: sys: id: 3ylztNmm2cYU0GgQuW0yiM created_at: !ruby/object:DateTime 2015-11-25 18:57:11.155000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:57:11.155000000 Z title: '2013,2034.15749' description: url: "//images.ctfassets.net/xt8ne4gbbocd/3ylztNmm2cYU0GgQuW0yiM/3be240bf82adfb5affc0d653e353350b/2013_2034.15749.jpg" caption: Painted roof of rock shelter showing decorated cows and human figures. Laas Geel, Somaliland. 2013,2034.15749 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3691391 - sys: id: 2IKYx0YIVOyMSwkU8mQQM created_at: !ruby/object:DateTime 2015-11-25 19:18:28.056000000 Z updated_at: !ruby/object:DateTime 2015-12-11 11:26:13.401000000 Z content_type_id: chapter revision: 2 title_internal: 'East Africa: regional, chapter 11' body: |- Rock art in the Horn of Africa faces several challenges. One of them is the lack of consolidated chronologies and absolute dating for the paintings and engravings. Another is the uneven knowledge of rock art throughout the region, with research often affected by political unrest. Therefore, distributions of rock art in the region are steadily growing as research is undertaken in one of the most interactive areas in East Africa. The rock art of Central and East Africa is one of the least documented and well understood of the corpus of African rock art. However, in recent years scholars have undertaken some comprehensive reviews of existing sites and surveys of new sites to open up the debates and more fully understand the complexities of this region. citations: - sys: id: 7d9bmwn5kccgO2gKC6W2Ys created_at: !ruby/object:DateTime 2015-11-25 19:08:04.014000000 Z updated_at: !ruby/object:DateTime 2017-12-19 12:24:18.659000000 Z content_type_id: citation revision: 2 citation_line: "<NAME>. 1996. ‘Cultural Patterns in the Rock Art of Central Tanzania.’ in *The Prehistory of Africa*. XIII International Congress of Prehistoric and Protohistoric Sciences Forli-Italia-8/14 September.\n\nČerviček, P. 1971. ‘Rock paintings of Laga Oda (Ethiopia)’ in *Paideuma*, 17, pp.121-136.\n\nClark, <NAME>. 1954. *The Prehistoric Cultures of the Horn of Africa*. New York: Octagon Press.\n\nClark, J.C.D. 1959. ‘Rock Paintings of Northern Rhodesia and Nyasaland’, in Summers, R. (ed.) *Prehistoric Rock Art of the Federation of Rhodesia & Nyasaland*: Glasgow: National Publication Trust, pp.163- 220.\n\nJoussaume, R. (ed.) 1995. Tiya, *l’Ethiopie des mégalithes : du biface à l’art rupestre dans la Corne de l’Afrique*. Association des publications chauvinoises (A.P.C.), Chauvigny.\n\nLeakey, M. 1983. *Africa’s Vanishing Art – The Rock Paintings of Tanzania*. London: Hamish Hamilton Ltd.\n\nMasao, F.T. 1979. *The Later Stone Age and the Rock Paintings of Central Tanzania*. Wiesbaden: Franz Steiner Verlag. \n\nNamono, Catherine. 2010. *A contextual interpretive approach to the rock art of Uganda*. Unpublished PhD Thesis. Johannesburg: University of Witwatersrand\n\nPhillipson, D.W. 1976. ‘The Rock Paintings of Eastern Zambia’, in *The Prehistory of Eastern Zambia: Memoir 6 of the british Institute in Eastern Africa*. Nairobi.\n\n<NAME>. (1995), Rock art in south-Central Africa: A study based on the pictographs of Dedza District, Malawi and Kasama District Zambia. dissertation. Cambridge: University of Cambridge, Unpublished Ph.D. dissertation.\n\n<NAME>. (1997), Zambia’s ancient rock art: The paintings of Kasama. Zambia: The National Heritage Conservation Commission of Zambia.\n\nSmith B.W. (2001), Forbidden images: Rock paintings and the Nyau secret society of Central Malaŵi and Eastern Zambia. *African Archaeological Review*18(4): 187–211.\n\n<NAME>. 2013, ‘Rock art research in Africa; in In: Lane, P. & Mitchell, P. (eds) *Handbook of African Archaeology*. Oxford: Oxford University Press, pp.145-162.\n\nTen Raa, E. 1974. ‘A record of some prehistoric and some recent Sandawe rock paintings’ in *Tanzania Notes and Records* 75, pp.9-27." background_images: - sys: id: 4aeKk2gBTiE6Es8qMC4eYq created_at: !ruby/object:DateTime 2015-12-07 19:42:27.348000000 Z updated_at: !ruby/object:DateTime 2017-12-19 12:25:55.914000000 Z title: '2013,2034.1298' description: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3592557 url: "//images.ctfassets.net/xt8ne4gbbocd/4aeKk2gBTiE6Es8qMC4eYq/31cde536c4abf1c0795761f8e35b255c/2013_2034.1298.jpg" - sys: id: 6DbMO4lEBOU06CeAsEE8aA created_at: !ruby/object:DateTime 2015-12-07 19:41:53.440000000 Z updated_at: !ruby/object:DateTime 2017-12-19 12:26:40.898000000 Z title: '2013,2034.15749' description: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3691391 url: "//images.ctfassets.net/xt8ne4gbbocd/6DbMO4lEBOU06CeAsEE8aA/9fc2e1d88f73a01852e1871f631bf4ff/2013_2034.15749.jpg" - sys: id: 6h9anIEQRGmu8ASywMeqwc created_at: !ruby/object:DateTime 2015-11-25 17:07:20.920000000 Z updated_at: !ruby/object:DateTime 2015-12-07 20:49:54.244000000 Z content_type_id: thematic revision: 4 title: Geometric motifs and cattle brands slug: geometric-motifs lead_image: sys: id: 5yD7fOuAdU4cemkewCqCMO created_at: !ruby/object:DateTime 2015-11-25 16:56:44.778000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:56:44.778000000 Z title: '2013,2034.12976' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5yD7fOuAdU4cemkewCqCMO/4d203afb0318bee69decb23327864c79/2013_2034.12976.jpg" chapters: - sys: id: 5plObOxqdq6MuC0k4YkCQ8 created_at: !ruby/object:DateTime 2015-11-25 17:02:35.234000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:05:34.964000000 Z content_type_id: chapter revision: 3 title_internal: 'Geometric motifs: thematic, chapter 1' body: |- The rock art of eastern Africa is characterised by a wide range of non-figurative images, broadly defined as geometric. Occurring in a number of different patterns or designs, they are thought to have been in existence in this region for thousands of years, although often it is difficult to attribute the art to particular cultural groups. Geometric rock art is difficult to interpret, and designs have been variously associated with sympathetic magic, symbols of climate or fertility and altered states of consciousness (Coulson and Campbell, 2010:220). However, in some cases the motifs painted or engraved on the rock face resemble the same designs used for branding livestock and are intimately related to people’s lives and world views in this region. First observed in Kenya in the 1970s with the work of Gramly (1975) at Lukenya Hill and Lynch and Robbins (1977) at Namoratung’a, some geometric motifs seen in the rock art of the region were observed to have had their counterparts on the hides of cattle of local communities. Although cattle branding is known to be practised by several Kenyan groups, Gramly concluded that “drawing cattle brands on the walls of rock shelters appears to be confined to the regions formerly inhabited by the Maa-speaking pastoralists or presently occupied by them”&dagger;(Gramly, 1977:117). - sys: id: 71cjHu2xrOC8O6IwSmMSS2 created_at: !ruby/object:DateTime 2015-11-25 16:57:39.559000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:06:07.592000000 Z content_type_id: image revision: 2 image: sys: id: 5yD7fOuAdU4cemkewCqCMO created_at: !ruby/object:DateTime 2015-11-25 16:56:44.778000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:56:44.778000000 Z title: '2013,2034.12976' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5yD7fOuAdU4cemkewCqCMO/4d203afb0318bee69decb23327864c79/2013_2034.12976.jpg" caption: White symbolic designs possibly representing Maa clans and livestock brands, Laikipia, Kenya. 2013,2034.12976 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3693276&partId=1&searchText=2013,2034.12976&page=1 - sys: id: 36QhSWVHKgOeMQmSMcGeWs created_at: !ruby/object:DateTime 2015-11-25 17:03:05.920000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:03:05.920000000 Z content_type_id: chapter revision: 1 title: title_internal: 'Geometric motifs: thematic, chapter 2' body: In the case of Lukenya Hill, the rock shelters on whose walls these geometric symbols occur are associated with meat-feasting ceremonies. Meat-feasting shelters exist from northern Tanzania through Kenya to Lake Turkana, and are places where Maa-speaking initiated men, who are not permitted to eat meat in their homes, gather to kill and feast on animals, predominantly cattle. During or after feasting, symbols of the animals that had been eaten were painted on the shelter ceiling in white or less often red. Maa speakers brand their cattle and camels with symbols that signify the lineage of their owners, but may also indicate if an animal has been treated for a particular disease. Different symbols may be used for male and female animals. - sys: id: 4t76LZy5zaSMGM4cUAsYOq created_at: !ruby/object:DateTime 2015-11-25 16:58:35.447000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:07:35.181000000 Z content_type_id: image revision: 2 image: sys: id: 1lBqQePHxK2Iw8wW8S8Ygw created_at: !ruby/object:DateTime 2015-11-25 16:56:44.764000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:56:44.764000000 Z title: '2013,2034.12846' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1lBqQePHxK2Iw8wW8S8Ygw/68fffb37b845614214e96ce78879c0b0/2013_2034.12846.jpg" caption: View of the long rock shelter below the waterfall showing white abstract Maasai paintings made probably quite recently during meat feasting ceremonies, Enkinyoi, Kenya. 2013,2034.12846 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3694558&partId=1&searchText=2013,2034.12846&page=1 - sys: id: 3HGWtlhoS424kQCMo6soOe created_at: !ruby/object:DateTime 2015-11-25 17:03:28.158000000 Z updated_at: !ruby/object:DateTime 2016-05-19 07:35:38.155000000 Z content_type_id: chapter revision: 2 title_internal: 'Geometric motifs: thematic, chapter 3' body: The sites of Namoratung’a near Lake Turkana in northern Kenya showed a similar visible relationship. The southernmost site is well known for its 167 megalithic stones marking male burials on which are engraved hundreds of geometric motifs. Some of these motifs bear a striking resemblance to the brand marks that the Turkana mark on their cattle, camels, donkeys and other livestock in the area, although local people claim no authorship for the funerary engravings (Russell, 2013:4). - sys: id: kgoyTkeS0oQIoaOaaWwwm created_at: !ruby/object:DateTime 2015-11-25 16:59:05.484000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:08:12.169000000 Z content_type_id: image revision: 2 image: sys: id: 19lqDiCw7UOomiMmYagQmq created_at: !ruby/object:DateTime 2015-11-25 16:56:44.756000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:56:44.756000000 Z title: '2013,2034.13006' description: url: "//images.ctfassets.net/xt8ne4gbbocd/19lqDiCw7UOomiMmYagQmq/6f54d106aaec53ed9a055dc7bf3ac014/2013_2034.13006.jpg" caption: Ndorobo man with bow and quiver of arrows kneels at a rock shelter adorned with white symbolic paintings suggesting meat-feasting rituals. Laikipia, Kenya. 2013,2034.13006 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3700172&partId=1&searchText=2013,2034.13006&page=1 - sys: id: 2JZ8EjHqi4U8kWae8oEOEw created_at: !ruby/object:DateTime 2015-11-25 17:03:56.190000000 Z updated_at: !ruby/object:DateTime 2016-05-19 07:35:15.319000000 Z content_type_id: chapter revision: 2 title_internal: 'Geometric motifs: thematic, chapter 4' body: Recent research (Russell, 2013) has shown that at Namoratung’a the branding of animals signifies a sense of belonging rather than a mark of ownership as we understand it in a modern farming context; all livestock, cattle, camel, goats, sheep and donkeys are branded according to species and sex (Russell, 2013:7). Ethnographic accounts document that clan membership can only be determined by observing someone with their livestock (Russell, 2013:9). The symbol itself is not as important as the act of placing it on the animal’s skin, and local people have confirmed that they never mark rock with brand marks. Thus, the geometric motifs on the grave markers may have been borrowed by local Turkana to serve as identity markers, but in a different context. In the Horn of Africa, some geometric rock art is located in the open landscape and on graves. It has been suggested that these too are brand or clan marks, possibly made by camel keeping pastoralists to mark achievement, territory or ownership (Russell, 2013:18). Some nomadic pastoralists, further afield, such as the Tuareg, place their clan marks along the routes they travel, carved onto salt blocks, trees and wells (Mohamed, 1990; Landais, 2001). - sys: id: 3sW37nPBleC8WSwA8SEEQM created_at: !ruby/object:DateTime 2015-11-25 16:59:47.649000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:59:47.649000000 Z content_type_id: image revision: 1 image: sys: id: 5yUlpG85GMuW2IiMeYCgyy created_at: !ruby/object:DateTime 2015-11-25 16:56:44.766000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:56:44.766000000 Z title: '2013,2034.13451' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5yUlpG85GMuW2IiMeYCgyy/a234f96f9931ec3fdddcf1ab54a33cd9/2013_2034.13451.jpg" caption: Borana cattle brands. Namoratung’a, Kenya. 2013,2034.13451. © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3660359&partId=1&searchText=2013,2034.13451&page=1 - sys: id: 6zBkbWkTaEoMAugoiuAwuK created_at: !ruby/object:DateTime 2015-11-25 17:04:38.446000000 Z updated_at: !ruby/object:DateTime 2016-05-19 07:34:17.646000000 Z content_type_id: chapter revision: 3 title_internal: 'Geometric motifs: thematic, chapter 5' body: "However, not all pastoralist geometric motifs can be associated with meat-feasting or livestock branding; they may have wider symbolism or be symbolic of something else (Russell, 2013:17). For example, informants from the Samburu people reported that while some of the painted motifs found at Samburu meat-feasting shelters were of cattle brands, others represented female headdresses or were made to mark an initiation, and in some Masai shelters there are also clear representations of warriors’ shields. In Uganda, a ceremonial rock in Karamoja, shows a dung painting consisting of large circles bisected by a cross which is said to represent cattle enclosures (Robbins, 1972). Geometric symbols, painted in fat and red ochre, on large phallic-shaped fertility stones on the Mesakin and Korongo Hills in south Sudan indicate the sex of the child to whom prayers are offered (Bell, 1936). A circle bisected by a line or circles bisected by two crosses represent boys. Girls are represented by a cross (drawn diagonally) or a slanting line (like a forward slash)(Russell, 2013: 17).\n\nAlthough pastoralist geometric motifs are widespread in the rock art of eastern Africa, attempting to find the meaning behind geometric designs is problematic. The examples discussed here demonstrate that motifs can have multiple authors, even in the same location, and that identical symbols can be the products of very different behaviours. \n" citations: - sys: id: 2oNK384LbeCqEuSIWWSGwc created_at: !ruby/object:DateTime 2015-11-25 17:01:10.748000000 Z updated_at: !ruby/object:DateTime 2016-05-19 07:33:26.748000000 Z content_type_id: citation revision: 3 citation_line: |- <NAME>. 1936. ‘Nuba fertility stones’, in *Sudan Notes and Records* 19(2), pp.313–314. Gramly R 1975. ‘Meat-feasting sites and cattle brands: Patterns of rock-shelter utilization in East Africa’ in *Azania*, 10, pp.107–121. <NAME>. 2001. ‘The marking of livestock in traditional pastoral societies’, *Scientific and Technical Review of the Office International des Epizooties* (Paris), 20 (2), pp.463–479. <NAME>. and <NAME>. 1977. ‘Animal brands and the interpretation of rock art in East Africa’ in *Current Anthropology *18, pp.538–539. Robbins LH (1972) Archaeology in the Turkana district, Kenya. Science 176(4033): 359–366 <NAME>. 2013. ‘Through the skin: exploring pastoralist marks and their meanings to understand parts of East African rock art’, in *Journal of Social Archaeology* 13:1, pp.3-30 &dagger; The term Maa relates to a group of closely related Eastern Nilotic languages, which historically dominated the east African hinterland; and today is spoken by around a million people. background_images: - sys: id: 1TDQd4TutiKwIAE8mOkYEU created_at: !ruby/object:DateTime 2015-12-07 19:16:42.825000000 Z updated_at: !ruby/object:DateTime 2015-12-07 19:16:42.825000000 Z title: KENLOK0030053 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1TDQd4TutiKwIAE8mOkYEU/718ff84615930ddafb1f1fdc67b5e479/KENLOK0030053.JPG" - sys: id: 2SCvEkDjAcIewkiu6iSGC4 created_at: !ruby/object:DateTime 2015-12-07 19:16:42.845000000 Z updated_at: !ruby/object:DateTime 2015-12-07 19:16:42.845000000 Z title: KENKAJ0030008 description: url: "//images.ctfassets.net/xt8ne4gbbocd/2SCvEkDjAcIewkiu6iSGC4/b2e2e928e5d9a6a25aca5c99058dfd76/KENKAJ0030008.jpg" country_introduction: sys: id: 3FI9toCf966mwqGkewwm62 created_at: !ruby/object:DateTime 2016-07-27 07:44:28.009000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:44:28.009000000 Z content_type_id: country_information revision: 1 title: 'Angola: country introduction' chapters: - sys: id: 4c7LrgmhRm6oEIsmKMyICO created_at: !ruby/object:DateTime 2016-07-27 07:45:13.048000000 Z updated_at: !ruby/object:DateTime 2016-07-27 09:10:43.664000000 Z content_type_id: chapter revision: 2 title: Introduction title_internal: 'Angola: country, chapter 1' body: 'Angola is a country located in the south-west of Africa, stretching from the Atlantic Ocean to the centre of the continent. Angolan rock art consists both of engravings and paintings, and is mostly located relatively near to the coast, although some sites have also been documented in the easternmost part of the country, near the border with Zambia. Depictions are very varied, representing animals, human figures and geometric signs, in many cases grouped in hunting or war scenes. In some cases, firearms appear represented, showing the period of contact with Europeans from the 1500s onwards. ' - sys: id: 6d4OdBQujeqc8gYMAUaQ8 created_at: !ruby/object:DateTime 2016-07-27 07:45:16.855000000 Z updated_at: !ruby/object:DateTime 2017-01-24 16:43:02.760000000 Z content_type_id: image revision: 3 image: sys: id: 3fc97FP7N6Q4qaYY82yMee created_at: !ruby/object:DateTime 2016-07-27 07:48:02.366000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:48:02.366000000 Z title: ANGTCH0010008 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3fc97FP7N6Q4qaYY82yMee/f28490284dadb197c3aafc749fd9de88/ANGTCH0010008.jpg" caption: "Painted group of white, red and dark red geometric signs. Tchitundu-Hulu Mucai, Angola. 2013,2034.21211\t© TARA/<NAME>" col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3744321&partId=1 - sys: id: 1LCP4wqQiYI4wSiSqsagwK created_at: !ruby/object:DateTime 2016-07-27 07:45:12.894000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:45:12.894000000 Z content_type_id: chapter revision: 1 title: Geography and rock art distribution title_internal: 'Angola: country, chapter 2' body: Angola has a variety of climates. The flat coastal plain ranges between 25 and 150 km in width, and is a semiarid region covered by scrub, turning into sand dunes to the south, near Namibia. The coastal region abruptly gives way to a series of mountains and escarpments divided by the Cuanza River. The northern part has an average height of 500 m, but the southern region is far higher, with the peaks occasionally exceeding 2,300 m. This mountainous region is in fact a transitional area between the coastal plain and the great central plateau of Africa. This plateau dominates Angola’s geography with an altitude from 1,200 to 1,800 m, and consists of a region of plains and low hills with a tropical climate. The climate becomes drier to the south and wetter to the north, where a wide region of the country can be defined as rainforest. - sys: id: 4hwTXZMXe00gwO6uoyKY0Y created_at: !ruby/object:DateTime 2016-07-27 07:45:16.770000000 Z updated_at: !ruby/object:DateTime 2017-01-24 16:43:30.163000000 Z content_type_id: image revision: 3 image: sys: id: 2EhlaF5U6Qui8SueE66KUO created_at: !ruby/object:DateTime 2016-07-27 07:48:02.353000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:48:02.353000000 Z title: ANGTCH0010001 description: url: "//images.ctfassets.net/xt8ne4gbbocd/2EhlaF5U6Qui8SueE66KUO/0329cbdac83a8bc3b9bbaff953025630/ANGTCH0010001.jpg" caption: Aerial view of landscape showing a valley and a plateau in south-western Angola. Namibe Province, Angola. 2013,2034.21204 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3744306&partId=1 - sys: id: 6oDRzpZCTe0cioMMk0WmGs created_at: !ruby/object:DateTime 2016-07-27 07:45:12.825000000 Z updated_at: !ruby/object:DateTime 2016-07-27 10:00:25.820000000 Z content_type_id: chapter revision: 2 title: '' title_internal: 'Angola: country, chapter 3' body: 'Rock art in Angola is primarily located in the coastal region, from north to south, with a clear concentration in its central area. However some rock art sites have also been discovered in the interior of the country, especially in its east-central region, and therefore this concentration in the coast could be explained by different research priorities in the past. Although both paintings and engravings are present in Angolan rock art, the latter seem to be predominant near the coast, while paintings are more common in the interior and to the south. ' - sys: id: 48podTUsCQm2Aai0M2CkqY created_at: !ruby/object:DateTime 2016-07-27 07:45:12.824000000 Z updated_at: !ruby/object:DateTime 2016-10-17 15:35:38.140000000 Z content_type_id: chapter revision: 2 title: Research history title_internal: 'Angola: country, chapter 4' body: 'Although there are some references in Portuguese chronicles from the 1500s and 1600s which could correspond to rock art paintings, the first clear mention of a rock art site was made in 1816 with research only starting in 1939, when <NAME> published the first news about engravings of Angola. Since then, research was intermittent until the 1950s, when the important site of Tchitundu-Hulu was studied and published. The relevance of Tchitundu-Hulu attracted the attention of important scholars such as Desmond Clark and the Abbé Breuil, who along with Portuguese researchers contextualized Angolan rock art within the continent. Research increased significantly over the next two decades, but during the 1980s political instability gave way to a period of stagnation until the 1990s, when new researchers began comprehensive surveys and organised the available rock art information. ' - sys: id: 19eEn5GF9e0Yqk4yYmoqKg created_at: !ruby/object:DateTime 2016-07-27 07:45:12.784000000 Z updated_at: !ruby/object:DateTime 2018-05-09 16:25:10.620000000 Z content_type_id: chapter revision: 3 title: 'Themes ' title_internal: 'Angola: country, chapter 5' body: 'The rock art in Angola has a wide variety of styles and themes, depending on the region and the chronology. The oldest images are painted or engraved geometric symbols and anthropomorphic figures. More recent depictions include axes, spears and firearms. The latest period of the Angolan rock art includes complex scenes of war and hunting, and in a number of cases human figures are carried on a palanquin-like structure. Although schematic figures are widespread throughout the country, they are predominant in the south-west where most of the sites have been compared to those in the Central Africa Schematic Art zone, with parallels in Malawi and Mozambique. In the west-central area of Angola, in addition to the schematic symbols and animals, images of men holding weapons, fighting and hunting are common, including warriors holding firearms which make reference to the first contact with Europeans by the 16th century. Near the north-west coast, some of the paintings and engravings have been related to objects used in religious ceremonies – wooden statuettes or decorated pot lids. In particular, a close association has been established between rock art depictions and the so-called Cabinda pot lids, which have different carved symbols—animals, objects, human figures—acting as a shared visual language. ' - sys: id: avBmltKXBKIac040I4im4 created_at: !ruby/object:DateTime 2016-07-27 07:45:16.027000000 Z updated_at: !ruby/object:DateTime 2016-07-27 09:13:04.815000000 Z content_type_id: image revision: 2 image: sys: id: 6JWgcpb6JUq0yCegs4MsGc created_at: !ruby/object:DateTime 2016-07-27 07:46:36.335000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:36.335000000 Z title: ANGTCH0010006 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6JWgcpb6JUq0yCegs4MsGc/6f9bad737cd113899538299e444e8007/ANGTCH0010006.jpg" caption: Paintings showing geometric signs, an unidentified quadruped and a bird (?) infilled with red and white lines. Tchitundu-Hulu Mucai, Angola. 2013,2034.21209 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3744323&partId=1 - sys: id: 2I6ljlCWZyAmqm8Gq402IE created_at: !ruby/object:DateTime 2016-07-27 07:45:12.760000000 Z updated_at: !ruby/object:DateTime 2016-07-27 09:16:27.004000000 Z content_type_id: chapter revision: 2 title: " Chronology" title_internal: 'Angola: country, chapter 6' body: 'As is so often the case with rock art, the dating of images is complex due to the absence of direct correlations between rock art depictions and well contextualised archaeological remains. Some of the sites with rock art have been excavated showing dates of the 7th millennium BC, but the relationship with the rock art is unclear. In the Tchitundu-Hulu Mulume site, the excavation at the cave provided a 1st millennium BC date, and the only radiocarbon date taken from the pigments at this site provided a date of the 1st century AD, which corresponds with other dates of the same style in Central Africa. The second tool for assigning a chronology is the analysis of the subject matter represented in the rock art depictions: the presence of metal objects, for example, would imply a date of the 1st millennium AD onwards, when this material was introduced. Whereas, depictions featuring images of firearms would date from the 16th century onwards. The end of the rock art tradition has been associated with the presence of Europeans but was probably progressive as the control of the region by the Portuguese grew during the 17th and 18th centuries. ' - sys: id: 1oBOeAZi0QEmAsekMIgq88 created_at: !ruby/object:DateTime 2016-07-27 07:45:15.908000000 Z updated_at: !ruby/object:DateTime 2018-05-09 16:27:56.903000000 Z content_type_id: image revision: 3 image: sys: id: 40lIKwvi8gwo4ckmuKguYk created_at: !ruby/object:DateTime 2016-07-27 07:47:54.905000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:47:54.905000000 Z title: ANGTCH0010022` description: url: "//images.ctfassets.net/xt8ne4gbbocd/40lIKwvi8gwo4ckmuKguYk/074e930f8099bbfdf9dd872f874c3a32/ANGTCH0010022.jpg" caption: Pecked concentric circles. Tchitundu-Hulu Mulume, Angola. 2013,2034.21225 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3744347&partId=1 citations: - sys: id: 6qVsC6snf24G0ImyC6yGY8 created_at: !ruby/object:DateTime 2016-07-27 07:45:30.575000000 Z updated_at: !ruby/object:DateTime 2016-07-27 10:00:54.672000000 Z content_type_id: citation revision: 2 citation_line: "<NAME>. Desmond & <NAME>. van, 1963. *Prehistoric cultures of northeast Angola and their significance in tropical Africa*. Companhia de Diamantes de Angola, Lisboa, Servicos Culturais \n\nGutierrez, M. 1996. *L'art parietal de l'Angola*. L’Harmattan, Paris \n\nGutierrez, M. 2009. 'Rock Art and Religion: the site of Pedra do Feitiço, Angola'. *The South African Archaeological Bulletin 64 (189)* pp. 51-60\n" background_images: - sys: id: 2EhlaF5U6Qui8SueE66KUO created_at: !ruby/object:DateTime 2016-07-27 07:48:02.353000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:48:02.353000000 Z title: ANGTCH0010001 description: url: "//images.ctfassets.net/xt8ne4gbbocd/2EhlaF5U6Qui8SueE66KUO/0329cbdac83a8bc3b9bbaff953025630/ANGTCH0010001.jpg" - sys: id: 40lIKwvi8gwo4ckmuKguYk created_at: !ruby/object:DateTime 2016-07-27 07:47:54.905000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:47:54.905000000 Z title: ANGTCH0010022` description: url: "//images.ctfassets.net/xt8ne4gbbocd/40lIKwvi8gwo4ckmuKguYk/074e930f8099bbfdf9dd872f874c3a32/ANGTCH0010022.jpg" - sys: id: 6JWgcpb6JUq0yCegs4MsGc created_at: !ruby/object:DateTime 2016-07-27 07:46:36.335000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:36.335000000 Z title: ANGTCH0010006 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6JWgcpb6JUq0yCegs4MsGc/6f9bad737cd113899538299e444e8007/ANGTCH0010006.jpg" region: Southern Africa ---<file_sep>/_coll_country/sudan.md --- contentful: sys: id: 4AcIuNBVDGakKqu4OKqcUE created_at: !ruby/object:DateTime 2015-11-26 18:50:55.631000000 Z updated_at: !ruby/object:DateTime 2018-05-17 17:11:03.529000000 Z content_type_id: country revision: 9 name: Sudan slug: sudan col_url: http://www.britishmuseum.org/research/collection_online/search.aspx?people=197356&place=41071 map_progress: true intro_progress: true image_carousel: - sys: id: 2s5Rp0kCzO46AsUy6ymeIO created_at: !ruby/object:DateTime 2015-11-30 13:39:42.184000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:05:34.453000000 Z title: '2013,2034.225' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3581550&partId=1&searchText=2013,2034.225&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/2s5Rp0kCzO46AsUy6ymeIO/5ee631964812cc8481d2dbb025ad7ef7/2013_2034.225_1.jpg" - sys: id: AMf0wybjzMekgCuSAs28E created_at: !ruby/object:DateTime 2015-11-26 12:13:51.741000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:06:06.627000000 Z title: '2013,2034.272' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3586260&partId=1&searchText=2013,2034.272&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/AMf0wybjzMekgCuSAs28E/2afa178fb645276aa051e8dc597f1b1e/2013_2034.272.jpg" - sys: id: 4pB2o28EnCOk6w8m8IwciG created_at: !ruby/object:DateTime 2015-11-26 12:13:51.703000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:06:43.357000000 Z title: '2013,2034.347' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3586942&partId=1&searchText=2013,2034.347&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/4pB2o28EnCOk6w8m8IwciG/5ce1e4a59f58a180045818bdc3bc8c13/2013_2034.347.jpg" - sys: id: 2JHzf9XFUACqyq0AAaw8CQ created_at: !ruby/object:DateTime 2015-11-26 12:13:51.755000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:07:20.356000000 Z title: '2013,2034.334' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3586833&partId=1&searchText=2013,2034.334&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/2JHzf9XFUACqyq0AAaw8CQ/1070836ffd26fec60872b6b97fb72ff5/2013_2034.334.jpg" - sys: id: 1DXzN0USKMoCI4kywAKeEy created_at: !ruby/object:DateTime 2015-11-25 14:18:38.585000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:07:57.029000000 Z title: '2013,2034.6' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3577799&partId=1&searchText=2013,2034.6&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/1DXzN0USKMoCI4kywAKeEy/c1f12caa1933afa9134b18c5505d14b8/2013_2034.6.jpg" - sys: id: 70RmZtVt9Cy4Ameg0qOoCo created_at: !ruby/object:DateTime 2015-11-25 14:18:38.600000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:08:32.195000000 Z title: '2013,2034.258' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3583684&partId=1&searchText=2013,2034.258&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/70RmZtVt9Cy4Ameg0qOoCo/07832fd85c8ed2d2bbbb478c02bfddfc/2013_2034.258.jpg" featured_site: sys: id: 5T1CxEt3MIkwM42YCMEcac created_at: !ruby/object:DateTime 2015-11-25 14:12:07.582000000 Z updated_at: !ruby/object:DateTime 2015-12-07 20:52:29.073000000 Z content_type_id: featured_site revision: 4 title: Jebel Uweinat, Sudan slug: jebel-uweinat chapters: - sys: id: 2Mj1hP5TQci0sCEuAKUQ8o created_at: !ruby/object:DateTime 2015-11-25 14:19:54.772000000 Z updated_at: !ruby/object:DateTime 2015-11-25 14:19:54.772000000 Z content_type_id: chapter revision: 1 title_internal: 'Sudan: featured site, chapter 1' body: At the nexus of Sudan, Libya and Egypt, where the borders meet at a point in the Eastern Sahara, a large rocky outcrop known as Jebel Uweinat peaks at an elevation of nearly 2,000 metres. The massif consists of a large, ring-shaped granite mass in the west, with sandstone plateaus in the east divided by deep valleys. Jebel Uweinat is so isolated that, until 1923, the proliferation of rock art around it had never been documented. - sys: id: 1Xgrdv52peoaGuSSayg20g created_at: !ruby/object:DateTime 2015-11-25 14:16:00.395000000 Z updated_at: !ruby/object:DateTime 2017-01-09 17:16:10.904000000 Z content_type_id: image revision: 2 image: sys: id: 1DXzN0USKMoCI4kywAKeEy created_at: !ruby/object:DateTime 2015-11-25 14:18:38.585000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:07:57.029000000 Z title: '2013,2034.6' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3577799&partId=1&searchText=2013,2034.6&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/1DXzN0USKMoCI4kywAKeEy/c1f12caa1933afa9134b18c5505d14b8/2013_2034.6.jpg" caption: Painted cattle and human figures on rock shelter roof. <NAME>, <NAME>. 2013,2034.6 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3577799&partId=1&searchText=2013,2034.6&page=1 - sys: id: 1HdRAmiEkIGCwsagKyAWgy created_at: !ruby/object:DateTime 2015-11-25 14:20:17.081000000 Z updated_at: !ruby/object:DateTime 2015-11-25 14:20:17.081000000 Z content_type_id: chapter revision: 1 title_internal: 'Sudan: featured site, chapter 2' body: This rock art comes in the form of paintings and engravings, commonly of animals and overwhelmingly of domestic cattle – 337 painted sites out of 414 that have been counted contain depictions of cattle and cattle herds, and there are many further engravings of them. There is a disparity in the spread of each artwork technique – the engravings are predominantly at lower levels than the paintings, near the base of the mountain and valley floors, with the paintings at greater altitude. The images shown here come from Karkur Talh, the largest of these valleys, which lies mostly in Sudan. - sys: id: 1ay8a3SCfmwOgsgwoIQigW created_at: !ruby/object:DateTime 2015-11-25 14:16:50.686000000 Z updated_at: !ruby/object:DateTime 2017-01-09 17:16:25.098000000 Z content_type_id: image revision: 2 image: sys: id: 70RmZtVt9Cy4Ameg0qOoCo created_at: !ruby/object:DateTime 2015-11-25 14:18:38.600000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:08:32.195000000 Z title: '2013,2034.258' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3583684&partId=1&searchText=2013,2034.258&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/70RmZtVt9Cy4Ameg0qOoCo/07832fd85c8ed2d2bbbb478c02bfddfc/2013_2034.258.jpg" caption: White-painted cattle. <NAME>, Jebel Uweinat. 2013,2034.258 © David Coulson/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3583684&partId=1&searchText=2013,2034.258&page=1 - sys: id: 6Vn3DoC1bOo4mwYwEeQMcq created_at: !ruby/object:DateTime 2015-11-25 14:20:38.415000000 Z updated_at: !ruby/object:DateTime 2015-11-25 14:20:38.415000000 Z content_type_id: chapter revision: 1 title_internal: 'Sudan: featured site, chapter 3' body: While cattle are ubiquitous, there are also frequent depictions of humans in various styles, as well as other domesticates, including goats and dogs. The herds of cattle clearly reflect a pastoralist existence for the artists, but there are also indications of hunting taking place, through engravings of wild antelope and dog figures, as well as many engravings of camels. - sys: id: 7ptm3SlsKQMOC4WsAsGyCm created_at: !ruby/object:DateTime 2015-11-25 14:17:47.704000000 Z updated_at: !ruby/object:DateTime 2017-01-09 17:16:39.272000000 Z content_type_id: image revision: 2 image: sys: id: 32GOdHizCwYKGAqO4sQ8oW created_at: !ruby/object:DateTime 2015-11-25 14:18:38.437000000 Z updated_at: !ruby/object:DateTime 2015-11-25 14:18:38.437000000 Z title: '2013,2034.335' description: url: "//images.ctfassets.net/xt8ne4gbbocd/32GOdHizCwYKGAqO4sQ8oW/d8a9b7309191ced7fff9c6db79174520/2013_2034.335.jpg" caption: Engraved camel figure. <NAME>, Jebel Uweinat 2013,2034.335 © David Coulson/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3586831&partId=1&searchText=2013,2034.335&page=1 - sys: id: 2OEaHI22BGKWWSWyyIQu6G created_at: !ruby/object:DateTime 2015-11-25 14:20:56.425000000 Z updated_at: !ruby/object:DateTime 2015-11-25 14:20:56.425000000 Z content_type_id: chapter revision: 1 title_internal: 'Sudan: featured site, chapter 4' body: This variety, and similarities to rock art sites elsewhere in the eastern Sahara, has led to conjecture and debate regarding the date and authorship of these depictions. Were the engravings and paintings made by the same people? Does the difference in drawing styles signify authorship by different cultures and at different times? The difficulties in objective dating of rock art make these questions difficult to answer, but it seems likely that there was a long tradition of painting and engraving here, with much of the ‘pastoralist’ rock art with cattle probably made between 5,000 and 7,000 years ago, some earlier styles possibly as much as 8,500 years ago, and other images such as camels made only about 2,000 years ago or less. - sys: id: 23kCbUF0EcEiGoYkkWWOGg created_at: !ruby/object:DateTime 2015-11-25 14:18:27.297000000 Z updated_at: !ruby/object:DateTime 2017-01-09 17:16:58.457000000 Z content_type_id: image revision: 2 image: sys: id: 3YBcXyxpbq6iKIegM66KgQ created_at: !ruby/object:DateTime 2015-11-25 14:18:38.604000000 Z updated_at: !ruby/object:DateTime 2015-11-25 14:18:38.604000000 Z title: '2013,2034.342' description: url: "//images.ctfassets.net/xt8ne4gbbocd/3YBcXyxpbq6iKIegM66KgQ/eb04e0be005fb0168817ddee5d4a742e/2013_2034.342.jpg" caption: Engraved animals (cattle?) and dogs. <NAME>, Jebel Uweinat 2013,2034.342 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3586930&partId=1&images=true&people=197356&museumno=2013,2034.342&page=1 - sys: id: 6XjTJyPnFuEkqeyWg2Mku created_at: !ruby/object:DateTime 2015-11-25 14:21:14.113000000 Z updated_at: !ruby/object:DateTime 2015-11-25 14:21:14.113000000 Z content_type_id: chapter revision: 1 title_internal: 'Sudan: featured site, chapter 5' body: Other than giraffes, the lack of large wild animals depicted (e.g. elephants) may indicate the climate to have been too dry for them, as during this time the area fluctuated in aridity, eventually becoming desert. There are, however, permanent springs at Jebel Uweinat and a more temperate microclimate here may have allowed pastoralists to subsist while the surrounding area became inhospitable. Indeed, despite its present remoteness, evidence suggests millennia of successive human presence, and as recently as the early 20th century, herders of the Toubou peoples were reported to be still living in the area. The camel engravings cannot be much older than 2,000 years, because camels were unknown in Africa before that, and the recent discovery of an ancient Egyptian hieroglyphic inscription from the Early Middle Kingdom serves to confirm that Jebel Uweinat has never really been ‘undiscovered’, despite having been unknown to Western geographers prior to the 20th century. - sys: id: erHhaJBDi0Mo4WYicGUAu created_at: !ruby/object:DateTime 2015-11-25 14:19:16.492000000 Z updated_at: !ruby/object:DateTime 2017-01-09 17:17:15.357000000 Z content_type_id: image revision: 2 image: sys: id: 4TbDKiBZ2wg8GaK6GqsMsa created_at: !ruby/object:DateTime 2015-11-25 14:18:38.589000000 Z updated_at: !ruby/object:DateTime 2015-11-25 14:18:38.589000000 Z title: '2013,2034.3918' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4TbDKiBZ2wg8GaK6GqsMsa/9354c9a992a51a4e896f67ac87fb4999/2013_2034.3918.jpg" caption: Engraved giraffes. <NAME>, Jebel Uweinat 2013,2034.3918 © David Coulson/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3586999&partId=1&images=true&people=197356&museumno=2013,2034.3918&page=1 background_images: - sys: id: 2FGW2NwJ2UOi0kMEcW6cc8 created_at: !ruby/object:DateTime 2015-12-07 20:09:20.521000000 Z updated_at: !ruby/object:DateTime 2015-12-07 20:09:20.521000000 Z title: '2013,2034.258' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2FGW2NwJ2UOi0kMEcW6cc8/b719e0e85ee7ecfce140d1db6b3581d0/2013_2034.258.jpg" - sys: id: 53gAYGjCEgYaksiuGkAkwc created_at: !ruby/object:DateTime 2015-12-07 20:09:20.503000000 Z updated_at: !ruby/object:DateTime 2015-12-07 20:09:20.503000000 Z title: '2013,2034.342' description: url: "//images.ctfassets.net/xt8ne4gbbocd/53gAYGjCEgYaksiuGkAkwc/1d799717cb2b19a599be9e95706e5e05/2013_2034.342.jpg" key_facts: sys: id: 2tfSjAG6O8kG4sQkWiauoK created_at: !ruby/object:DateTime 2015-11-26 11:23:42.312000000 Z updated_at: !ruby/object:DateTime 2015-11-26 11:23:42.312000000 Z content_type_id: country_key_facts revision: 1 title_internal: 'Sudan: key facts' image_count: 163 images date_range: Mostly 6,000 BC – 30 BC and Medieval Christian main_areas: Nile valley techniques: Engravings, brush paintings main_themes: Boats, cattle, wild animals, inscriptions thematic_articles: - sys: id: 72UN6TbsDmocqeki00gS4I created_at: !ruby/object:DateTime 2015-11-26 17:35:22.951000000 Z updated_at: !ruby/object:DateTime 2015-12-07 20:47:35.130000000 Z content_type_id: thematic revision: 4 title: Chariots in the Sahara slug: chariots-in-the-sahara lead_image: sys: id: 2Ed8OkQdX2YIYAIEQwiY8W created_at: !ruby/object:DateTime 2015-11-26 17:17:39.181000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:17:39.181000000 Z title: '2013,2034.999' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2Ed8OkQdX2YIYAIEQwiY8W/9873a75ad2995b1b7a86923eca583f31/2013_2034.999.jpg" chapters: - sys: id: 3pSkk40LWUWs28e0A2ocI2 created_at: !ruby/object:DateTime 2015-11-26 17:27:59.282000000 Z updated_at: !ruby/object:DateTime 2018-05-16 16:42:36.356000000 Z content_type_id: chapter revision: 2 title_internal: 'Thematic: chariots, chapter 1' body: A number of sites from this Collection are located in the Libyan Desert, notably the Fezzan region, and include paintings of chariots in a variety of forms dating to the Horse Period, from up to 3,000 years ago. This has stimulated some interesting questions about the use of chariots in what appears to be such a seemingly inappropriate environment for a wheeled vehicle, as well as the nature of representation. Why were chariots used in the desert and why were they represented in such different ways? - sys: id: 2Hjql4WXLOsmCogY4EAWSq created_at: !ruby/object:DateTime 2015-11-26 17:18:19.534000000 Z updated_at: !ruby/object:DateTime 2018-05-16 16:43:36.197000000 Z content_type_id: image revision: 2 image: sys: id: 2Ed8OkQdX2YIYAIEQwiY8W created_at: !ruby/object:DateTime 2015-11-26 17:17:39.181000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:17:39.181000000 Z title: '2013,2034.999' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2Ed8OkQdX2YIYAIEQwiY8W/9873a75ad2995b1b7a86923eca583f31/2013_2034.999.jpg" caption: Two-wheeled chariot in profile view. Tihenagdal, Acacus Mountains, Libya. 2013,2034.999 © TARA / <NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3588528&partId=1&people=197356&museumno=2013,2034.999&page=1 - sys: id: 3TiPUtUxgAQUe0UGoQUqO0 created_at: !ruby/object:DateTime 2015-11-26 17:28:18.968000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:28:18.968000000 Z content_type_id: chapter revision: 1 title_internal: 'Thematic: chariots, chapter 2' body: The chariot has been one of the great empowering innovations of history. It likely originated in Mesopotamia about 3000 BC due to advances in metallurgy during the Bronze Age, and has served as a primary means of transport until quite recently in the historical period across Africa, Eurasia and Europe. Chariots provided rapid and efficient transport, and were ideal for the battlefield as the design provided a raised firing platform for archers . As a result the chariot became the principal war machine from the Egyptians through to the Romans; and the Chinese, who owned an army of 10,000 chariots. Indeed, our use of the word car is a derivative of the Latin word carrus, meaning ‘a chariot of war or of triumph’. - sys: id: 5ZxcAksrFSKEGacE2iwQuk created_at: !ruby/object:DateTime 2015-11-26 17:19:58.050000000 Z updated_at: !ruby/object:DateTime 2018-05-16 16:44:46.340000000 Z content_type_id: image revision: 2 image: sys: id: 5neJpIDOpyUQAWC8q0mCIK created_at: !ruby/object:DateTime 2015-11-26 17:17:39.141000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:17:39.141000000 Z title: '124534' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5neJpIDOpyUQAWC8q0mCIK/d8ee0111089adb2b565b48919f21dfbe/124534.jpg" caption: Neo-Assyrian Gypsum wall panel relief showing Ashurnasirpal II hunting lions, 865BC – 860 BC. © Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=367027&partId=1&people=197356&museumno=124534&page=1 - sys: id: 2Grf0McSJ2Uq4SUaUQAMwU created_at: !ruby/object:DateTime 2015-11-26 17:28:46.851000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:28:46.851000000 Z content_type_id: chapter revision: 1 title_internal: 'Thematic: chariots, chapter 3' body: The chariot in the Sahara was probably introduced by the Garamantes, a cultural group thought to be descended from Berbers and Saharan pastoralists. There is little textual information about the Garamantes, documentation comes mainly from Greek and Roman sources. Herodotus described them as ‘a very great nation’. Recent archaeological research has shown that the Garamantes established about eight major towns as well as numerous other settlements, and were ‘brilliant farmers, resourceful engineers, and enterprising merchants’. The success of the Garamantes was based on their subterranean water-extraction system, a network of underground tunnels, allowing the Garamantian culture to flourish in an increasingly arid environment, resulting in population expansion, urbanisation, and conquest. - sys: id: 6fOKcyIgKcyMi8uC4WW6sG created_at: !ruby/object:DateTime 2015-11-26 17:20:33.572000000 Z updated_at: !ruby/object:DateTime 2018-05-16 16:45:32.605000000 Z content_type_id: image revision: 2 image: sys: id: 4DBpxlJqeAS4O0eYeCO2Ms created_at: !ruby/object:DateTime 2015-11-26 17:17:39.152000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:17:39.152000000 Z title: '2013,2034.407' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4DBpxlJqeAS4O0eYeCO2Ms/18e67077bdaa437ac82e85ba48cdb0da/2013_2034.407.jpg" caption: A so-called ‘Flying gallop’ chariot. <NAME>, Acacus Mountains, Libya. 2013,2034.407 © TARA / <NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3580186&partId=1&people=197356&museumno=2013,2034.407&page=1 - sys: id: CAQ4O5QWhaCeOQAMmgGSo created_at: !ruby/object:DateTime 2015-11-26 17:29:06.521000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:29:06.521000000 Z content_type_id: chapter revision: 1 title_internal: 'Thematic: chariots, chapter 4' body: On average there are about 500 drawings of chariots across the Sahara, from the Fezzan in Libya through the Aïr of Niger into northern Mali and then westward to the Atlantic coast; but not all were produced by the Garamantes. It is still not certain that chariots were driven along the routes where their depictions occur; remains of chariots have never been found west of the Fezzan. However, the Fezzan states were thriving trade routes and chariots are likely to have been used to transport salt, cloth, beads and metal goods in exchange for gold, ivory and slaves. The widespread occurrence of chariot imagery on Saharan rock outcrops has led to the proposition of ‘chariot routes’ linking North and West Africa. However, these vehicles were not suited for long-distance transport across desert terrain; more localised use is probable, conducted through middlemen who were aware of the trade routes through the desert landscape. Additionally, the horse at this time was a prestige animal and it is unlikely that they facilitated transport across the Saharan trade routes, with travellers rather utilising donkeys or oxen. - sys: id: 5cgk0mmvKwC0IGsCyIsewG created_at: !ruby/object:DateTime 2015-11-26 17:20:59.281000000 Z updated_at: !ruby/object:DateTime 2018-05-16 16:46:44.461000000 Z content_type_id: image revision: 2 image: sys: id: 4XYASoQz6UQggUGI8gqkgq created_at: !ruby/object:DateTime 2015-11-26 17:17:39.148000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:17:39.148000000 Z title: '2013,2034.389' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4XYASoQz6UQggUGI8gqkgq/d167c56220dfd17c399b02086fe9ebc3/2013_2034.389.jpg" caption: This two wheeled chariot is being drawn by a cow with upturned horns. Awis Valley, Acacus Mountains, Libya. 2013,2034.389 © TARA / <NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3579985&partId=1&people=197356&museumno=2013,2034.389&page=1 - sys: id: 5pKuD1vPdmcs2o8eQeumM4 created_at: !ruby/object:DateTime 2015-11-26 17:29:23.611000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:29:23.611000000 Z content_type_id: chapter revision: 1 title_internal: 'Thematic: chariots, chapter 5' body: The absence of archaeological evidence for chariots has led to the suggestion that some representations of chariots may have been the result of cultural diffusion, transmitted orally by nomadic peoples traversing the region. Artists may never have actually seen the vehicles themselves. If this is the case, chariot symbols may have acquired some special meaning above their function as modes of transport. It may also explain why some representations of chariots do not seem to conform to more conventional styles of representations and account for the different ways in which they were depicted. - sys: id: wckVt1SCpqs0IYeaAsWeS created_at: !ruby/object:DateTime 2015-11-26 17:21:42.421000000 Z updated_at: !ruby/object:DateTime 2018-05-16 16:48:40.965000000 Z content_type_id: image revision: 3 image: sys: id: 279BaN9Z4QeOYAWCMSkyeQ created_at: !ruby/object:DateTime 2015-11-26 17:17:46.288000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:17:46.288000000 Z title: '2013,2034.392' description: url: "//images.ctfassets.net/xt8ne4gbbocd/279BaN9Z4QeOYAWCMSkyeQ/7606d86492a167b9ec4b105a7eb57d74/2013_2034.392.jpg" caption: These two images (above and below) depicts chariots as if ‘flattened out’, with the horses represented back to back. Awis Valley, Acacus Mountains, Libya. 2013,2034.392 © TARA / <NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3579981&partId=1&people=197356&museumno=2013,2034.392&page=1 - sys: id: 7fKfpmISPYs04YOi8G0kAm created_at: !ruby/object:DateTime 2015-11-26 17:23:05.317000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:23:05.317000000 Z content_type_id: image revision: 1 image: sys: id: 28JPIQ4mYQCMYQmMQ0Oke8 created_at: !ruby/object:DateTime 2015-11-26 17:17:45.941000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:17:45.941000000 Z title: '2013,2034.393' description: url: "//images.ctfassets.net/xt8ne4gbbocd/28JPIQ4mYQCMYQmMQ0Oke8/665bea9aafec58dfe3487ee665b3a9ec/2013_2034.393.jpg" caption: 2013,2034.393 © TARA / <NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3579980&partId=1&people=197356&museumno=2013,2034.393&page=1 - sys: id: 3xUchEu4sECWq4mAoEYYM4 created_at: !ruby/object:DateTime 2015-11-26 17:23:33.472000000 Z updated_at: !ruby/object:DateTime 2018-05-16 17:20:52.618000000 Z content_type_id: image revision: 2 image: sys: id: 697LgKlm3SWSQOu8CqSuIO created_at: !ruby/object:DateTime 2015-11-26 17:17:45.956000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:17:45.956000000 Z title: '2013,2034.370' description: url: "//images.ctfassets.net/xt8ne4gbbocd/697LgKlm3SWSQOu8CqSuIO/c8afe8c1724289dee3c1116fd4ba9280/2013_2034.370.jpg" caption: Possible chariot feature in top left of image. Acacus Mountains, Libya. 2013,2034.370 © TARA / <NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3579291&partId=1&people=197356&museumno=2013,2034.370&page=1 - sys: id: 6bQzinrqXmYESoWqyYYyuI created_at: !ruby/object:DateTime 2015-11-26 17:24:01.069000000 Z updated_at: !ruby/object:DateTime 2018-05-16 17:21:25.227000000 Z content_type_id: image revision: 2 image: sys: id: 5RKPaYinvOW6yyCGYcIsmK created_at: !ruby/object:DateTime 2015-11-26 17:17:45.952000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:17:45.952000000 Z title: '2013,2034.371' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5RKPaYinvOW6yyCGYcIsmK/a0328f912ac8f6fe017ce99d8e673421/2013_2034.371.jpg" caption: Possible chariots with two wheels. Acacus Mountains, Fezzan District, Libya. 2013,2034.371 © TARA / <NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3579290&partId=1&people=197356&museumno=2013,2034.371&page=1 - sys: id: 5qthr4HJaEoIe2sOOqiU4K created_at: !ruby/object:DateTime 2015-11-26 17:29:40.388000000 Z updated_at: !ruby/object:DateTime 2018-05-16 17:31:17.884000000 Z content_type_id: chapter revision: 2 title_internal: 'Thematic: chariots, chapter 6' body: |- The two images may or may not depict chariots. The rectangular shapes are potentially abstracted forms of the chariot similar to the ‘flattened out’ depictions discussed previously. These potentially abstracted representations often sit alongside distinguishing figures, such as geometric bi-triangular figures, spears or lances, women wearing long dresses, and animals drawn in a fairly naturalistic style, of the Horse Period when the chariots were being used. Beside the schematic and simply depicted chariots, there is also a group which has been termed the ‘flying gallop chariots’. Their distribution includes the whole Tassili region, although there are fewer in the Acacus Mountains. They resemble the classical two-wheeled antique chariots, generally drawn by two horses, but sometimes three, or even four. The driver is usually alone, and is depicted in a typical style with a stick head. The majority are shown at full speed, with the driver holding a whip standing on a small platform, sometimes straining forward. - sys: id: 2NEHx4J06IMSceEyC4w0CA created_at: !ruby/object:DateTime 2015-11-26 17:24:30.605000000 Z updated_at: !ruby/object:DateTime 2018-05-16 17:31:46.413000000 Z content_type_id: image revision: 2 image: sys: id: 74j3IOLwLS8IocMCACY2W created_at: !ruby/object:DateTime 2015-11-26 17:17:45.949000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:17:45.949000000 Z title: '2013,2034.523' description: url: "//images.ctfassets.net/xt8ne4gbbocd/74j3IOLwLS8IocMCACY2W/5495e8c245e10db13caf5cb0f36905c4/2013_2034.523.jpg" caption: "'Flying gallop’ chariot, <NAME>, Acacus Mountains, Fezzan District, Libya. 2013,2034.523 © TARA / <NAME>" col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3583068&partId=1&people=197356&museumno=2013,2034.523&page=1 - sys: id: 1YKtISfrKAQ6M4mMawIOYK created_at: !ruby/object:DateTime 2015-11-26 17:30:08.834000000 Z updated_at: !ruby/object:DateTime 2018-05-16 17:33:37.308000000 Z content_type_id: chapter revision: 2 title_internal: 'Thematic: chariots, chapter 7' body: |- In a similar manner to the schematic chariots, the 'Flying Gallop' depictions display the entire platform and both wheels of the chariot. In addition, more than one horse is depicted as a single horse in profile with numerous legs indicating multiple horses; an artistic technique first seen during the Upper Palaeolithic in Europe. Interestingly, in the Libyan rock art of the Acacus Mountains it seemed that animals could be conceived of in profile and in movement, but chariots were conceived of differently, and are represented in plain view, seen from above or in three-quarters perspective. Why are chariots depicted in a variety of ways, and what can we say about the nature of representation in relation to chariots? It is clear that chariots are able to be depicted in profile view, yet there are variations that digress from this perspective. In relation to the few examples we have come across so far in the Acacus Mountains in south-western Libya, one observation we might make is that the ways in which chariots have been represented may be indicative of the ways in which they have been observed by the artists representing them; as a rule from above. The rock shelters in the Acacus are often some height above the now dried up wadis, and so the ways in which they conceived of representing the chariot itself , whether as a flying gallop chariot, a chariot drawn by a bovid or as an abstraction, may have become a particular representational convention. The ways in which animals were represented conformed also to a convention, one that had a longer tradition, but chariots were an innovation and may have been represented as they were observed; from higher up in the rockshelters; thus chariots were conceived of as a whole and from an aerial perspective. The ways in which environments affect our perceptions of dimension, space and colour are now well-established, initially through cross-cultural anthropological studies in the 1960s, and becoming better understood through more recent research concerning the brain. Of course, this is speculation, and further research would be needed to consider all the possibilities. But for now, we can start to see some intriguing lines of enquiry and research areas that these images have stimulated. - sys: id: 4nHApyWfWowgG0qASeKEwk created_at: !ruby/object:DateTime 2015-11-26 17:25:19.180000000 Z updated_at: !ruby/object:DateTime 2018-05-16 17:34:17.369000000 Z content_type_id: image revision: 2 image: sys: id: 4Mn54dTjEQ80ssSOK0q0Mq created_at: !ruby/object:DateTime 2015-11-26 17:17:39.129000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:17:39.129000000 Z title: '135568' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4Mn54dTjEQ80ssSOK0q0Mq/c1bca8c151b882c16adaf7bc449e1850/135568.jpg" caption: Model of chariot, Middle Bronze Age – Early Bronze Age, 2000BC, Eastern Anatolia Region. 1971,0406.1 © Trustees of the British Museum. The design of this chariot is very similar to the representation in Fig. 4. col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=369521&partId=1&people=197356&museumno=135568&page=1 - sys: id: 5dtoX8DJv2UkguMM24uWwK created_at: !ruby/object:DateTime 2015-11-26 17:26:17.455000000 Z updated_at: !ruby/object:DateTime 2018-05-16 17:34:59.909000000 Z content_type_id: image revision: 2 image: sys: id: 7zQLgo270Am82CG0Qa6gaE created_at: !ruby/object:DateTime 2015-11-26 17:17:45.956000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:17:45.956000000 Z title: '894,1030.1' description: url: "//images.ctfassets.net/xt8ne4gbbocd/7zQLgo270Am82CG0Qa6gaE/80aa63978217874eaaa0960a6e0847d6/894_1030.1.jpg" caption: Bronze model of a two-horse racing chariot. Roman, 1st century – 2nd century, Latium, Tiber River. 1894,1030.1 © Trustees of the British Museum. col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=399770&partId=1&people=197356&museumno=1894,1030.1&page=1 - sys: id: 74fcVRriowwOQeWua2uMMY created_at: !ruby/object:DateTime 2015-11-26 17:30:27.301000000 Z updated_at: !ruby/object:DateTime 2018-05-16 17:35:36.578000000 Z content_type_id: chapter revision: 2 title_internal: 'Thematic: chariots, chapter 8' body: Vast trading networks across the Sahara Desert not only facilitated the spread of goods, but the routes served as a conduit for cultural diffusion through the spread of knowledge, ideas and technologies. Chariots were both functional and symbolic. As a mode of transport, as a weapon of war, as a means of trade and exchange and as a symbol of power, the chariot has been a cultural artefact for 4,000 years. Its temporal and spatial reach is evident not only in the rock art, but through the British Museum collections, which reveal comparisons between 2D rock art and 3D artefacts. Similarities and adjacencies occur not only in the structure and design of the chariots themselves but in their symbolic and pragmatic nature. - sys: id: 266zWxwbfC86gaKyG8myCU created_at: !ruby/object:DateTime 2015-11-26 17:26:53.266000000 Z updated_at: !ruby/object:DateTime 2018-05-16 17:43:56.525000000 Z content_type_id: image revision: 2 image: sys: id: 4rwQF960rueIOACosUMwoa created_at: !ruby/object:DateTime 2015-11-26 17:17:39.145000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:17:39.145000000 Z title: EA 37982 description: url: "//images.ctfassets.net/xt8ne4gbbocd/4rwQF960rueIOACosUMwoa/b5b41cda0efd36989292d004f039bace/EA_37982.jpg" caption: Fragment of a limestone tomb-painting representing the assessment of crops, c. 1350BC, Tomb of Nebamun, Thebes, Egypt. British Museum EA37982 ©Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=117388&partId=1&people=197356&museumno=37982&page=1 - sys: id: 2mTEgMGc5iiM00MOE4WSqU created_at: !ruby/object:DateTime 2015-11-26 17:27:28.284000000 Z updated_at: !ruby/object:DateTime 2018-05-16 17:44:28.029000000 Z content_type_id: image revision: 2 image: sys: id: 70cjifYtVeeqIOoOCouaGS created_at: !ruby/object:DateTime 2015-11-26 17:17:46.009000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:17:46.009000000 Z title: '1867,0101.870' description: url: "//images.ctfassets.net/xt8ne4gbbocd/70cjifYtVeeqIOoOCouaGS/066bc072069ab814687828a61e1ff1aa/1867_0101.870.jpg" caption: Gold coin of Diocletian, obverse side showing chariot. British Museum 1867,0101.870 ©Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=1189587&partId=1&people=197356&museumno=1867,0101.870&page=1 - sys: id: 5Z6SQu2oLuG40IIWEqKgWE created_at: !ruby/object:DateTime 2015-11-26 17:30:47.583000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:30:47.583000000 Z content_type_id: chapter revision: 1 title_internal: 'Thematic: chariots, chapter 9' body: A hoard of 100,000 Roman coins from the Diocletian period (not the above) were unearthed near Misurata, Libya, probably used to pay both regular Roman and local troops. Such finds demonstrate the symbolic power of the chariot and the diffusion of the imagery. citations: - sys: id: vVxzecw1jwam6aCcEA8cY created_at: !ruby/object:DateTime 2015-11-26 17:31:32.248000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:31:32.248000000 Z content_type_id: citation revision: 1 citation_line: <NAME>. ‘Kingdom of the Sands', in *Current Archaeology*, Vol. 57 No 2, March/April 2004 background_images: - sys: id: 3Cv9FvodyoQIQS2UaCo4KU created_at: !ruby/object:DateTime 2015-12-07 18:43:47.568000000 Z updated_at: !ruby/object:DateTime 2015-12-07 18:43:47.568000000 Z title: '01495388 001' description: url: "//images.ctfassets.net/xt8ne4gbbocd/3Cv9FvodyoQIQS2UaCo4KU/f243937c551a4a12f07c1063d13edaaa/01495388_001.jpg" - sys: id: 2yTKrZUOY00UsmcQ8sC0w4 created_at: !ruby/object:DateTime 2015-12-07 18:44:42.716000000 Z updated_at: !ruby/object:DateTime 2015-12-07 18:44:42.716000000 Z title: '01495139 001' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2yTKrZUOY00UsmcQ8sC0w4/8e527c421d837b3993026107d0a0acbb/01495139_001.jpg" - sys: id: 6h9anIEQRGmu8ASywMeqwc created_at: !ruby/object:DateTime 2015-11-25 17:07:20.920000000 Z updated_at: !ruby/object:DateTime 2015-12-07 20:49:54.244000000 Z content_type_id: thematic revision: 4 title: Geometric motifs and cattle brands slug: geometric-motifs lead_image: sys: id: 5yD7fOuAdU4cemkewCqCMO created_at: !ruby/object:DateTime 2015-11-25 16:56:44.778000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:56:44.778000000 Z title: '2013,2034.12976' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5yD7fOuAdU4cemkewCqCMO/4d203afb0318bee69decb23327864c79/2013_2034.12976.jpg" chapters: - sys: id: 5plObOxqdq6MuC0k4YkCQ8 created_at: !ruby/object:DateTime 2015-11-25 17:02:35.234000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:05:34.964000000 Z content_type_id: chapter revision: 3 title_internal: 'Geometric motifs: thematic, chapter 1' body: |- The rock art of eastern Africa is characterised by a wide range of non-figurative images, broadly defined as geometric. Occurring in a number of different patterns or designs, they are thought to have been in existence in this region for thousands of years, although often it is difficult to attribute the art to particular cultural groups. Geometric rock art is difficult to interpret, and designs have been variously associated with sympathetic magic, symbols of climate or fertility and altered states of consciousness (Coulson and Campbell, 2010:220). However, in some cases the motifs painted or engraved on the rock face resemble the same designs used for branding livestock and are intimately related to people’s lives and world views in this region. First observed in Kenya in the 1970s with the work of Gramly (1975) at <NAME> and Lynch and Robbins (1977) at Namoratung’a, some geometric motifs seen in the rock art of the region were observed to have had their counterparts on the hides of cattle of local communities. Although cattle branding is known to be practised by several Kenyan groups, Gramly concluded that “drawing cattle brands on the walls of rock shelters appears to be confined to the regions formerly inhabited by the Maa-speaking pastoralists or presently occupied by them”&dagger;(Gramly, 1977:117). - sys: id: 71cjHu2xrOC8O6IwSmMSS2 created_at: !ruby/object:DateTime 2015-11-25 16:57:39.559000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:06:07.592000000 Z content_type_id: image revision: 2 image: sys: id: 5yD7fOuAdU4cemkewCqCMO created_at: !ruby/object:DateTime 2015-11-25 16:56:44.778000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:56:44.778000000 Z title: '2013,2034.12976' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5yD7fOuAdU4cemkewCqCMO/4d203afb0318bee69decb23327864c79/2013_2034.12976.jpg" caption: White symbolic designs possibly representing Maa clans and livestock brands, Laikipia, Kenya. 2013,2034.12976 © TARA/<NAME>son col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3693276&partId=1&searchText=2013,2034.12976&page=1 - sys: id: 36QhSWVHKgOeMQmSMcGeWs created_at: !ruby/object:DateTime 2015-11-25 17:03:05.920000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:03:05.920000000 Z content_type_id: chapter revision: 1 title: title_internal: 'Geometric motifs: thematic, chapter 2' body: In the case of Lukenya Hill, the rock shelters on whose walls these geometric symbols occur are associated with meat-feasting ceremonies. Meat-feasting shelters exist from northern Tanzania through Kenya to Lake Turkana, and are places where Maa-speaking initiated men, who are not permitted to eat meat in their homes, gather to kill and feast on animals, predominantly cattle. During or after feasting, symbols of the animals that had been eaten were painted on the shelter ceiling in white or less often red. Maa speakers brand their cattle and camels with symbols that signify the lineage of their owners, but may also indicate if an animal has been treated for a particular disease. Different symbols may be used for male and female animals. - sys: id: 4t76LZy5zaSMGM4cUAsYOq created_at: !ruby/object:DateTime 2015-11-25 16:58:35.447000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:07:35.181000000 Z content_type_id: image revision: 2 image: sys: id: 1lBqQePHxK2Iw8wW8S8Ygw created_at: !ruby/object:DateTime 2015-11-25 16:56:44.764000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:56:44.764000000 Z title: '2013,2034.12846' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1lBqQePHxK2Iw8wW8S8Ygw/68fffb37b845614214e96ce78879c0b0/2013_2034.12846.jpg" caption: View of the long rock shelter below the waterfall showing white abstract Maasai paintings made probably quite recently during meat feasting ceremonies, Enkinyoi, Kenya. 2013,2034.12846 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3694558&partId=1&searchText=2013,2034.12846&page=1 - sys: id: 3HGWtlhoS424kQCMo6soOe created_at: !ruby/object:DateTime 2015-11-25 17:03:28.158000000 Z updated_at: !ruby/object:DateTime 2016-05-19 07:35:38.155000000 Z content_type_id: chapter revision: 2 title_internal: 'Geometric motifs: thematic, chapter 3' body: The sites of Namoratung’a near Lake Turkana in northern Kenya showed a similar visible relationship. The southernmost site is well known for its 167 megalithic stones marking male burials on which are engraved hundreds of geometric motifs. Some of these motifs bear a striking resemblance to the brand marks that the Turkana mark on their cattle, camels, donkeys and other livestock in the area, although local people claim no authorship for the funerary engravings (Russell, 2013:4). - sys: id: kgoyTkeS0oQIoaOaaWwwm created_at: !ruby/object:DateTime 2015-11-25 16:59:05.484000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:08:12.169000000 Z content_type_id: image revision: 2 image: sys: id: 19lqDiCw7UOomiMmYagQmq created_at: !ruby/object:DateTime 2015-11-25 16:56:44.756000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:56:44.756000000 Z title: '2013,2034.13006' description: url: "//images.ctfassets.net/xt8ne4gbbocd/19lqDiCw7UOomiMmYagQmq/6f54d106aaec53ed9a055dc7bf3ac014/2013_2034.13006.jpg" caption: Ndorobo man with bow and quiver of arrows kneels at a rock shelter adorned with white symbolic paintings suggesting meat-feasting rituals. Laikipia, Kenya. 2013,2034.13006 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3700172&partId=1&searchText=2013,2034.13006&page=1 - sys: id: 2JZ8EjHqi4U8kWae8oEOEw created_at: !ruby/object:DateTime 2015-11-25 17:03:56.190000000 Z updated_at: !ruby/object:DateTime 2016-05-19 07:35:15.319000000 Z content_type_id: chapter revision: 2 title_internal: 'Geometric motifs: thematic, chapter 4' body: Recent research (Russell, 2013) has shown that at Namoratung’a the branding of animals signifies a sense of belonging rather than a mark of ownership as we understand it in a modern farming context; all livestock, cattle, camel, goats, sheep and donkeys are branded according to species and sex (Russell, 2013:7). Ethnographic accounts document that clan membership can only be determined by observing someone with their livestock (Russell, 2013:9). The symbol itself is not as important as the act of placing it on the animal’s skin, and local people have confirmed that they never mark rock with brand marks. Thus, the geometric motifs on the grave markers may have been borrowed by local Turkana to serve as identity markers, but in a different context. In the Horn of Africa, some geometric rock art is located in the open landscape and on graves. It has been suggested that these too are brand or clan marks, possibly made by camel keeping pastoralists to mark achievement, territory or ownership (Russell, 2013:18). Some nomadic pastoralists, further afield, such as the Tuareg, place their clan marks along the routes they travel, carved onto salt blocks, trees and wells (Mohamed, 1990; Landais, 2001). - sys: id: 3sW37nPBleC8WSwA8SEEQM created_at: !ruby/object:DateTime 2015-11-25 16:59:47.649000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:59:47.649000000 Z content_type_id: image revision: 1 image: sys: id: 5yUlpG85GMuW2IiMeYCgyy created_at: !ruby/object:DateTime 2015-11-25 16:56:44.766000000 Z updated_at: !ruby/object:DateTime 2015-11-25 16:56:44.766000000 Z title: '2013,2034.13451' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5yUlpG85GMuW2IiMeYCgyy/a234f96f9931ec3fdddcf1ab54a33cd9/2013_2034.13451.jpg" caption: Borana cattle brands. Namoratung’a, Kenya. 2013,2034.13451. © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3660359&partId=1&searchText=2013,2034.13451&page=1 - sys: id: 6zBkbWkTaEoMAugoiuAwuK created_at: !ruby/object:DateTime 2015-11-25 17:04:38.446000000 Z updated_at: !ruby/object:DateTime 2016-05-19 07:34:17.646000000 Z content_type_id: chapter revision: 3 title_internal: 'Geometric motifs: thematic, chapter 5' body: "However, not all pastoralist geometric motifs can be associated with meat-feasting or livestock branding; they may have wider symbolism or be symbolic of something else (Russell, 2013:17). For example, informants from the Samburu people reported that while some of the painted motifs found at Samburu meat-feasting shelters were of cattle brands, others represented female headdresses or were made to mark an initiation, and in some Masai shelters there are also clear representations of warriors’ shields. In Uganda, a ceremonial rock in Karamoja, shows a dung painting consisting of large circles bisected by a cross which is said to represent cattle enclosures (Robbins, 1972). Geometric symbols, painted in fat and red ochre, on large phallic-shaped fertility stones on the Mesakin and Korongo Hills in south Sudan indicate the sex of the child to whom prayers are offered (Bell, 1936). A circle bisected by a line or circles bisected by two crosses represent boys. Girls are represented by a cross (drawn diagonally) or a slanting line (like a forward slash)(Russell, 2013: 17).\n\nAlthough pastoralist geometric motifs are widespread in the rock art of eastern Africa, attempting to find the meaning behind geometric designs is problematic. The examples discussed here demonstrate that motifs can have multiple authors, even in the same location, and that identical symbols can be the products of very different behaviours. \n" citations: - sys: id: 2oNK384LbeCqEuSIWWSGwc created_at: !ruby/object:DateTime 2015-11-25 17:01:10.748000000 Z updated_at: !ruby/object:DateTime 2016-05-19 07:33:26.748000000 Z content_type_id: citation revision: 3 citation_line: |- <NAME>. 1936. ‘Nuba fertility stones’, in *Sudan Notes and Records* 19(2), pp.313–314. Gramly R 1975. ‘Meat-feasting sites and cattle brands: Patterns of rock-shelter utilization in East Africa’ in *Azania*, 10, pp.107–121. <NAME>. 2001. ‘The marking of livestock in traditional pastoral societies’, *Scientific and Technical Review of the Office International des Epizooties* (Paris), 20 (2), pp.463–479. <NAME>. and <NAME>. 1977. ‘Animal brands and the interpretation of rock art in East Africa’ in *Current Anthropology *18, pp.538–539. Robbins LH (1972) Archaeology in the Turkana district, Kenya. Science 176(4033): 359–366 <NAME>. 2013. ‘Through the skin: exploring pastoralist marks and their meanings to understand parts of East African rock art’, in *Journal of Social Archaeology* 13:1, pp.3-30 &dagger; The term Maa relates to a group of closely related Eastern Nilotic languages, which historically dominated the east African hinterland; and today is spoken by around a million people. background_images: - sys: id: 1TDQd4TutiKwIAE8mOkYEU created_at: !ruby/object:DateTime 2015-12-07 19:16:42.825000000 Z updated_at: !ruby/object:DateTime 2015-12-07 19:16:42.825000000 Z title: KENLOK0030053 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1TDQd4TutiKwIAE8mOkYEU/718ff84615930ddafb1f1fdc67b5e479/KENLOK0030053.JPG" - sys: id: 2SCvEkDjAcIewkiu6iSGC4 created_at: !ruby/object:DateTime 2015-12-07 19:16:42.845000000 Z updated_at: !ruby/object:DateTime 2015-12-07 19:16:42.845000000 Z title: KENKAJ0030008 description: url: "//images.ctfassets.net/xt8ne4gbbocd/2SCvEkDjAcIewkiu6iSGC4/b2e2e928e5d9a6a25aca5c99058dfd76/KENKAJ0030008.jpg" country_introduction: sys: id: 4fITEJHibm4iy8ykmE2s0G created_at: !ruby/object:DateTime 2015-11-26 12:22:39.465000000 Z updated_at: !ruby/object:DateTime 2015-12-07 13:42:14.925000000 Z content_type_id: country_information revision: 2 title: 'Sudan: country introduction' chapters: - sys: id: 1sqHdOmWbeyY42OCS0Sc4u created_at: !ruby/object:DateTime 2015-11-26 12:18:28.564000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:18:28.564000000 Z content_type_id: chapter revision: 1 title: Introduction title_internal: 'Sudan: country, chapter 1' body: 'Sudan''s known rock art mainly consists of paintings and engravings on exposed rock surfaces and rock shelters, largely of animals, human figures and ancient river boats. Most of the published rock art is found in disparate geographical areas in the northern section of the country: around the Nile valley and close to the country''s north-western and north-eastern borders. Images include wild fauna such as antelope, domestic animals like camels, and depictions of boats, which along with inscriptions and religious imagery can attempt to date these images.' - sys: id: 1993CZTJXsyeWaOscywWs4 created_at: !ruby/object:DateTime 2015-11-26 12:14:29.575000000 Z updated_at: !ruby/object:DateTime 2017-01-09 17:12:37.390000000 Z content_type_id: image revision: 2 image: sys: id: 4rPFCqitX2sUOAGUEAqui4 created_at: !ruby/object:DateTime 2015-11-26 12:13:55.093000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:13:55.093000000 Z title: '2013,2034.225' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4rPFCqitX2sUOAGUEAqui4/d0abf71d8e72774026c082d7ae16d71c/2013_2034.225.jpg" caption: Painted cattle. <NAME>, <NAME>, Sudan. 2013,2034.225 © TARA/<NAME> col_link: http://bit.ly/2iwfHwV - sys: id: 2qQoPRbg6Q0aMQsc2WWicu created_at: !ruby/object:DateTime 2015-11-26 12:18:56.395000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:18:56.395000000 Z content_type_id: chapter revision: 1 title: Geography title_internal: 'Sudan: country, chapter 2' body: Sudan covers nearly 2,000,000 km² and is geographically diverse, dominated in the north by the desert of the southern Sahara and divided by the River Nile, which flows north from the capital city of Khartoum at the confluence of the Blue and White Niles and is joined by the Atbara River in the east. East of the Nile is the arid Nubian Desert, which is part of the larger Sahara, flanked at the north east by the Red Sea Hills and at the south by clay plains. To the south and west of the country are semi-arid zones with seasonal watercourses, with the west dominated by the Jebel Marrah volcanic massif, and the Nuba mountain range near the southern border. - sys: id: 4pTDZNCHuo8Wi22GSsSSMK created_at: !ruby/object:DateTime 2015-11-26 12:19:26.835000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:19:26.835000000 Z content_type_id: chapter revision: 1 title: Research history title_internal: 'Sudan: country, chapter 3' body: Historically, rock art research in Sudan has either been incorporated into larger investigations of the area’s rich archaeological history, or, as in the Nubian Nile valley, the result of archaeological salvage projects, aimed at documenting and conserving archaeological sites and artefacts in advance of engineered flooding events, such as the construction of the Aswan High dam in the 1960s and the Merowe dam in the early 2000s. This has resulted in significant rock art and rock gong discoveries, such as that noted near the Second Cataract (Žába, 1967) and more recently around the Fourth. Rock art remains vulnerable to damming initiatives – that at Sabu is currently under threat by the Kajbar Dam proposal at the Third Cataract. There is great scope for further research. - sys: id: 4O1OTdhzb2UIQYeuuickg6 created_at: !ruby/object:DateTime 2015-11-26 12:19:49.980000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:20:08.533000000 Z content_type_id: chapter revision: 2 title: Rock art types title_internal: 'Sudan: country, chapter 4' body: |- The rock art of Sudan is varied across both time periods and geographical regions. Numerous pecked depictions of domestic cattle can be found in the Red Sea Hills (Pluskota, 2006) as well as depictions of both domestic and wild animals closer to the River Nile, such as those found at Jebel Gorgod in a mountainous area near Sesebi (Schiff Giorgini, 1972). Engravings, like those around the Second, Third, and Fourth Cataracts (areas of rocky rapids) are varied in subject matter and in date, ranging from Neolithic engravings of wild and domestic fauna to those with Medieval Christian imagery, for example around the Dal Cataract (Mills, 1965). These are mixed with others from about 4,000 BC onwards which may be contemporary with the Predynastic cultures and Pharaonic periods of ancient Egypt and in northern Sudan, Nubian Kerma culture (known to the ancient Egyptians as the Kingdom of Kush). These include depictions of Nile river boats and later hieroglyphic inscriptions. The peripatetic nature of these traceable signatures highlights the need to look beyond modern boundaries when considering ancient rock art traditions of Africa. For millennia prior to the creation of the current Egypt/Sudan border, the highway of the river allowed movement between Egypt and Nubia, the people of the region leaving their marks on a narrow area of fertile land that fostered riverine animals like crocodiles, which are occasionally depicted in the rock engravings. From the 4th millennium BC, following several temperate millennia, savannah animals like giraffe lost their habitat in the increasingly arid environments to east and west, but remain reflected in the rock engravings of what is now desert. The range in styles and dates for Sudanese rock art emphasises its nature, not as a particular artistic style, but as personal and cultural manipulations of a specific medium. A number of stone percussive instruments known as rock gongs, which produce a sonorous tone when struck and are often apparently associated with cattle engravings, have stimulated discussion about the uses of rock art sites as multisensory ritual venues. - sys: id: 4T61G6jdTqmkMKWiEmIcEe created_at: !ruby/object:DateTime 2015-11-26 12:15:01.481000000 Z updated_at: !ruby/object:DateTime 2017-01-09 17:13:14.413000000 Z content_type_id: image revision: 2 image: sys: id: AMf0wybjzMekgCuSAs28E created_at: !ruby/object:DateTime 2015-11-26 12:13:51.741000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:06:06.627000000 Z title: '2013,2034.272' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3586260&partId=1&searchText=2013,2034.272&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/AMf0wybjzMekgCuSAs28E/2afa178fb645276aa051e8dc597f1b1e/2013_2034.272.jpg" caption: Engraved cattle, giraffe and ostrich. <NAME>, Jebel Uweinat. 2013,2034.272 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3586260&partId=1 - sys: id: 1KCSPDy6Dyqm2g6OkEeGMy created_at: !ruby/object:DateTime 2015-11-26 12:20:29.697000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:20:29.697000000 Z content_type_id: chapter revision: 1 title: Chronology title_internal: 'Sudan: country, chapter 5' body: The understanding of much of Sudanese prehistory as it relates to rock art remains subject to debate. Some of the best-preserved and most varied rock art of Sudan’s desert regions is situated only metres from the Egyptian border in the far north-west corner of the country, in a valley of Jebel Uweinat – the enormous sandstone and granite outcrop which serves as a boundary between Egypt, Sudan and Libya. Numerous paintings and engravings are found here, including images of wild animals, such as giraffe and antelope, humans, dogs and many cattle. Some of these paintings have been compared with other styles of rock art in the wider Sahara, including the later Pastoral Period (Muzzolini, 1995). Others have proposed that a different set of paintings in these sites may be older, with a stylistic link (although fragile) with the Round Head Period (Van Noten,1978). However, the scholarly community recognises the inherent difficulty of formulating conclusions of direct links with wider rock art practices. In areas around the Nile, where there are similar animal engravings, rock art is also from a wide range of time periods. - sys: id: 5E1CsZXmy4g0484oGIG2W6 created_at: !ruby/object:DateTime 2015-11-26 12:15:30.625000000 Z updated_at: !ruby/object:DateTime 2017-01-09 17:13:29.546000000 Z content_type_id: image revision: 2 image: sys: id: 4pB2o28EnCOk6w8m8IwciG created_at: !ruby/object:DateTime 2015-11-26 12:13:51.703000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:06:43.357000000 Z title: '2013,2034.347' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3586942&partId=1&searchText=2013,2034.347&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/4pB2o28EnCOk6w8m8IwciG/5ce1e4a59f58a180045818bdc3bc8c13/2013_2034.347.jpg" caption: Engraved ostriches, dogs and antelope. <NAME>, Jebel Uweinat. 2013,2034.347 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3586942&partId=1 - sys: id: 3xX43VnxhuGoG0KKMca2iG created_at: !ruby/object:DateTime 2015-11-26 12:20:54.588000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:20:54.588000000 Z content_type_id: chapter revision: 1 title: title_internal: 'Sudan: country, chapter 6' body: 'Ascribing dates to rock art like that at Jebel Uweinat is also uncertain and is more difficult than dating images such as the depictions of Nile river boats or later Christian cross engravings like those found near the Third Cataract, where similar motifs are replicated on contemporary pottery and corroborated elsewhere in the archaeological record. Occasionally rock art may be found in a dateable stratigraphic context- a giraffe engraving at Gala Abu Ahmed in Wadi Howar, an ancient Nile tributary, was recently dated to before 1,200-1,300 BC in this way (Jesse, 2005). In general, other clues are necessary, for example known domestication dates: wild animal images are often superseded with depictions of animals like horses and camels. These were only widely known in northeast Africa from the second and first millennia BC respectively and are therefore unlikely to be older. However, this is not an exact science: examination of the superimpositions and levels of patination on some Nile valley cattle engravings show that they were made over thousands of years up to the not too distant past. Faced with such challenges, classifying rock art by design style, while problematic, can prove useful in envisioning chronology.' - sys: id: 26BMChmzneksWYm4uQeK6u created_at: !ruby/object:DateTime 2015-11-26 12:16:01.977000000 Z updated_at: !ruby/object:DateTime 2017-01-09 17:13:48.660000000 Z content_type_id: image revision: 2 image: sys: id: 2JHzf9XFUACqyq0AAaw8CQ created_at: !ruby/object:DateTime 2015-11-26 12:13:51.755000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:07:20.356000000 Z title: '2013,2034.334' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3586833&partId=1&searchText=2013,2034.334&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/2JHzf9XFUACqyq0AAaw8CQ/1070836ffd26fec60872b6b97fb72ff5/2013_2034.334.jpg" caption: Engraved camels and human figures. <NAME>, Jebel Uweinat. 2013,2034.334 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3586833&partId=1 citations: - sys: id: 6LV3FmRkCkCOm8UgKQ2e26 created_at: !ruby/object:DateTime 2015-11-26 12:17:53.755000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:17:53.755000000 Z content_type_id: citation revision: 1 citation_line: |- <NAME>. 2005. *Rock Art in Lower Wadi Howar, northwest Sudan*. Sahara vol.16, pp. 27-38 <NAME>. 1965. *The Reconnaissance Survey from Gemai to Dal: A Preliminary Report for 1963- 1964*. Kush 13, pp. 1-12 <NAME>. 1995. *Les images rupestres du Sahara*. — Toulouse (author’s ed.), p. 447 <NAME>. 2006. *Kirwan Memorial Lecture: Bir Nurayet- the Rock Art Gallery of the Red Sea Hills*. Sudan & Nubia, Bulletin No. 10, pp. 2-7 <NAME>. 1972. *SOLEB, II: Les Nécropoles*. — Firenze: Sansoni <NAME>. 1978. *The Rock Paintings of Jebel Uweinat*. — Graz, Akademischeverlag <NAME>. 1967. *The Third Czechoslovak Expedition to Nubia in the Frame of the Safeguarding of the Nubian Monuments Project: Preliminary Report*. Fouilles en Nubie (1961-1963). Le Caire: Organisme general des impr. Gouvernementales, pp. 217-224 For further information about archaeology in Sudan, visit [sudarchs.org.uk](http://www.sudarchrs.org.uk/) background_images: - sys: id: 3YBcXyxpbq6iKIegM66KgQ created_at: !ruby/object:DateTime 2015-11-25 14:18:38.604000000 Z updated_at: !ruby/object:DateTime 2015-11-25 14:18:38.604000000 Z title: '2013,2034.342' description: url: "//images.ctfassets.net/xt8ne4gbbocd/3YBcXyxpbq6iKIegM66KgQ/eb04e0be005fb0168817ddee5d4a742e/2013_2034.342.jpg" - sys: id: 5TArT9HA2IAYOwG2IGeUUa created_at: !ruby/object:DateTime 2015-11-30 13:39:22.540000000 Z updated_at: !ruby/object:DateTime 2015-11-30 13:39:22.540000000 Z title: 2013,2034.334 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/5TArT9HA2IAYOwG2IGeUUa/1e99a0c3bb9d05cfe9fc050f6c022c4d/2013_2034.334_1.jpg" - sys: id: 2s5Rp0kCzO46AsUy6ymeIO created_at: !ruby/object:DateTime 2015-11-30 13:39:42.184000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:05:34.453000000 Z title: '2013,2034.225' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3581550&partId=1&searchText=2013,2034.225&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/2s5Rp0kCzO46AsUy6ymeIO/5ee631964812cc8481d2dbb025ad7ef7/2013_2034.225_1.jpg" region: Northern / Saharan Africa ---<file_sep>/_coll_country/morocco/oukaimeden.md --- breadcrumbs: - label: Countries url: "../../" - label: Morocco url: "../" layout: featured_site contentful: sys: id: 3ljdBZ1Fra2Kokks0oYiwW created_at: !ruby/object:DateTime 2015-11-25 15:15:17.431000000 Z updated_at: !ruby/object:DateTime 2015-12-08 14:39:26.150000000 Z content_type_id: featured_site revision: 5 title: Oukaïmeden, Morocco slug: oukaimeden chapters: - sys: id: 5ggUMhTP3y0uOGcMkYkEI created_at: !ruby/object:DateTime 2015-11-25 15:16:09.455000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:16:09.455000000 Z content_type_id: chapter revision: 1 title_internal: 'Morocco: featured site, chapter 1' body: |- Oukaïmeden is an alpine-like valley set 2,630 metres above sea level at the core of Morocco’s High Atlas. Records from the 16th century onwards refer to its seasonal profit as summer pasturage by herders coming from villages settled at mid-altitude. It is a well-known place due to the existence of a ski resort, and a well-frequented tourist destination for people coming from Marrakech during the summer. It is also home to one of the most impressive collections of rock art engravings in Morocco, with about 250 rock art sites and one thousand depictions scattered throughout the valley. Oukaïmeden rock art has been thoroughly studied by Malhome (1959, 1961) and Rodrigue (1999), and along with the Yagour plateau and Jbel Rat constitute the core of High Atlas rock art. - sys: id: 5rhQdcEWMo0ewS4Sq4OWcu created_at: !ruby/object:DateTime 2015-11-25 15:11:07.744000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:11:07.744000000 Z content_type_id: image revision: 1 image: sys: id: 5A7q4PnbI4sYmQsi2u4yYg created_at: !ruby/object:DateTime 2015-11-25 15:10:29.077000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:10:29.077000000 Z title: '2013,2034.5863' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5A7q4PnbI4sYmQsi2u4yYg/95ab9db2de0532159c59d4bbe3e12316/2013_2034.5863.jpg" caption: General view of Oukaimeden valley. 2013,2034.5863 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3613833&partId=1&images=true&people=197356&museumno=2013,2034.5863&page=1 - sys: id: 5VOOpZKsb6eY2MMYacY6G4 created_at: !ruby/object:DateTime 2015-11-25 15:11:50.001000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:11:50.001000000 Z content_type_id: image revision: 1 image: sys: id: 1h9eCgWFYce8eqiq2KSGkU created_at: !ruby/object:DateTime 2015-11-25 15:10:29.053000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:03:01.253000000 Z title: '2013,2034.5894' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3614035&partId=1&searchText=2013,2034.5894&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/1h9eCgWFYce8eqiq2KSGkU/830a45b1b9107528469498e3dc8c12d5/2013_2034.5894.jpg" caption: Engraved anthropomorph surrounded by a dagger and a rectangular shield. 2013,2034.5894 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3614035&partId=1&museumno=2013%2c2034.5894&page=1 - sys: id: 6uSaQ0ylC88yMwE4sKCkcq created_at: !ruby/object:DateTime 2015-11-25 15:16:30.214000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:16:30.214000000 Z content_type_id: chapter revision: 1 title_internal: 'Morocco: featured site, chapter 2' body: High Atlas rock art is remarkably different not only from the rest of Moroccan rock art, but also from most other depictions documented throughout the Sahara. Although some of the engravings correspond to cattle depictions similar to those of nearby regions, there are other images known only in this region. One particular type comprises detailed, large human figures represented frontally, surrounded by weapons and other symbols. Another common kind of depiction is circular shapes with inner designs, which most probably represent shields. Weapons are also very common, usually depicted in isolation, but not held by warriors as is common in most of the North African images. Together with these themes, Oukaïmeden is characterised by a significant number of elephant representations (something surprising considering its altitude!) and a huge number of complex, geometric symbols whose interpretation remains obscure. - sys: id: 4uVJ5RvCgUiCuEEsKAogs2 created_at: !ruby/object:DateTime 2015-11-25 15:12:18.882000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:12:18.882000000 Z content_type_id: image revision: 1 image: sys: id: 3OAdh6uCrCIgCeuQ2E0koa created_at: !ruby/object:DateTime 2015-11-25 15:10:29.049000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:03:43.993000000 Z title: '2013,2034.5874' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3613873&partId=1&searchText=2013,2034.5874&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/3OAdh6uCrCIgCeuQ2E0koa/a9fe9a0740e535707c227440bac46571/2013_2034.5874.jpg" caption: Circular engravings (shields?). 2013,2034.5874 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3613873&partId=1&museumno=2013%2c2034.5874&page=1 - sys: id: 2rFEuu8dXSEmUYccCEwUAE created_at: !ruby/object:DateTime 2015-11-25 15:12:51.006000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:12:51.006000000 Z content_type_id: image revision: 1 image: sys: id: 2joH7nmXU42sE00g0GUgMq created_at: !ruby/object:DateTime 2015-11-25 15:10:29.068000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:10:29.068000000 Z title: '2013,2034.5907' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2joH7nmXU42sE00g0GUgMq/36076d52020d185a340141311398c879/2013_2034.5907.jpg" caption: Engraved Bronze Age halberds (two-handed pole weapons). 2013,2034.5907 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3614147&partId=1&museumno=2013%2c2034.5907+&page=1 - sys: id: 51fcUCW4Skk64u24W2yEam created_at: !ruby/object:DateTime 2015-11-25 15:16:49.016000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:16:49.016000000 Z content_type_id: chapter revision: 1 title_internal: 'Morocco: featured site, chapter 3' body: Chronologically speaking, it seems Oukaïmeden engravings started to appear during the mid-3rd millennium BC, when the Sahara desert became increasingly drier and summer grazing became more and more important. The earliest depictions consisted mainly of animals, especially cattle, which was the species that benefited the most from green pastures. As time passed, pressure on this resource grew and tensions arose among the communities that used the valley. From the 2nd millennium BC onwards, animal depictions were replaced by images of weapons and warriors, showing a different, more violent way of reclaiming rights over pastures. That situation continued during the long Libyan-Berber period that started around the mid-1st millennium BC and lasted until the Muslim conquest of the area, around the 7th century AD. The arrival of Islam does not imply the immediate disappearance of rock art engravings, but their number decreased significantly and they progressively lost their significance, becoming incidental in Oukaïmeden history. - sys: id: 1x3JfrZOaUEKmcAmkosm02 created_at: !ruby/object:DateTime 2015-11-25 15:13:24.362000000 Z updated_at: !ruby/object:DateTime 2017-01-06 15:38:01.412000000 Z content_type_id: image revision: 3 image: sys: id: 2nGxKesCSgWOeqSqa2eoAc created_at: !ruby/object:DateTime 2015-11-25 15:10:29.081000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:10:29.081000000 Z title: '2013,2034.5916' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2nGxKesCSgWOeqSqa2eoAc/6bd751f25420e92c5655a1af86e277de/2013_2034.5916.jpg" caption: Pecked bull on a prominent place within the valley. 2013,2034.5916 © <NAME>/TARA col_link: http://bit.ly/2jbIt5Q - sys: id: 7DEhcGYGoogSOGqOMmImam created_at: !ruby/object:DateTime 2015-11-25 15:17:08.360000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:17:08.360000000 Z content_type_id: chapter revision: 1 title_internal: 'Morocco: featured site, chapter 4' body: 'Unlike most of the rock art sites in North Africa, Oukaïmeden was not inhabited the whole year: the heavy snow that falls during the winter prevented occupation during the winter season. But that same snow made the valley a strategic resource for the villages placed in the surrounding, lower areas. During summer, when pastures became drier in the area around Marrakech, herders would take their sheep and cattle to Oukaïmeden for grazing, much in the way as it is still done today.' - sys: id: 1PdfGxdelmo8gkSyeu4kWK created_at: !ruby/object:DateTime 2015-11-25 15:14:00.276000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:14:00.276000000 Z content_type_id: image revision: 1 image: sys: id: RXRm1UgosSw248YEayEgC created_at: !ruby/object:DateTime 2015-11-25 15:10:29.031000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:10:29.031000000 Z title: '2013,2034.5879' description: url: "//images.ctfassets.net/xt8ne4gbbocd/RXRm1UgosSw248YEayEgC/32ef250086422ca87ff06855c563174d/2013_2034.5879.jpg" caption: Elephants’ Frieze. Several elephants and a rhinoceros or warthog are depicted facing right, where two human figures are represented. 2013,2034.5879 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3613935&partId=1&images=true&people=197356&museumno=2013,2034.5879&page=1 - sys: id: 28aOey79CAaGems6OOqW4C created_at: !ruby/object:DateTime 2015-11-25 15:17:25.702000000 Z updated_at: !ruby/object:DateTime 2017-01-06 15:38:58.399000000 Z content_type_id: chapter revision: 2 title_internal: 'Morocco: featured site, chapter 5' body: |- Although Oukaïmeden rock art is distributed throughout the valley, there are some sites with scenes that stand above the rest due to their complexity and significance. One of them is the so-called Elephants’ Frieze, a horizontal rock face where four elephants, a feline, a rhinoceros or warthog and two human figures facing the animals were depicted. Two later, vertical Libyan-Berber inscriptions were added to the panel. The scene is placed near a shelter, facing a stream which constitutes one of the main access routes to the valley grazing areas. The relevance of Oukaïmeden rock art is renowned, and the whole area has been protected since 1951 by the Moroccan government, while the National Centre of Rock Art Heritage in Marrakech has carried on several research projects in the area. However, the interest in the site doesn’t mean its preservation is assured: the growing incidence of tourism, the extraction of stones for building purposes in nearby Marrakech and vandalism are threats that have still to be dealt with. The fragile environment of Oukaïmeden valley adds an extra concern about the preservation of one of the most complete and better-preserved rock sites in Morocco. citations: - sys: id: 5qcDvyXGlUeO0OYGECIQYG created_at: !ruby/object:DateTime 2015-11-25 15:14:50.132000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:14:50.132000000 Z content_type_id: citation revision: 1 citation_line: |- <NAME>. 1959. *Corpus des gravures rupestres du Grand Atlas*, vol. 1. Marrakech, Publications du Service des Antiquités du Maroc 13 Malhomme, J. 1961. *Corpus des gravures rupestres du Grand Atlas*, vol. 2. Marrakech, Publications du Service des Antiquités du Maroc 14 Rodrigue, A. 1999. *L'art rupestre du Haut Atlas Marocain*. Paris, L'Harmattan Simoneau, A. 1977. *Catalogue des sites rupestres du Sud-Marocain*. Rabat, Ministere d'Etat charge des Affaires Culturelles background_images: - sys: id: 1FXFD6ckcAWESOOCMGo4gE created_at: !ruby/object:DateTime 2015-12-07 20:09:20.487000000 Z updated_at: !ruby/object:DateTime 2015-12-07 20:09:20.487000000 Z title: '2013,2034.5874' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1FXFD6ckcAWESOOCMGo4gE/03c7c921ee08e8d8d359eddc273fc2e5/2013_2034.5874.jpg" - sys: id: 1fKpdeWDQu46gMIW8i4gki created_at: !ruby/object:DateTime 2015-12-07 20:09:33.601000000 Z updated_at: !ruby/object:DateTime 2015-12-07 20:09:33.601000000 Z title: '2013,2034.5879' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1fKpdeWDQu46gMIW8i4gki/efd0d1ecaeb976c4d94c4244a8066f4b/2013_2034.5879.jpg" ---<file_sep>/_coll_thematic/contact-rock-art-south-africa.md --- contentful: sys: id: 2Rh3XLBCreIy6ms4cKYKIQ created_at: !ruby/object:DateTime 2017-08-13 13:52:18.110000000 Z updated_at: !ruby/object:DateTime 2017-08-13 13:55:09.227000000 Z content_type_id: thematic revision: 2 title: Contact Rock Art in South Africa slug: contact-rock-art-south-africa lead_image: sys: id: 6GqC6D7ckgwSoCCKEQqiEm created_at: !ruby/object:DateTime 2016-09-12 15:11:37.019000000 Z updated_at: !ruby/object:DateTime 2018-09-19 16:32:02.304000000 Z title: SOASWC0110006 description: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3734234&partId=1&searchText=+West+Coast+District+Municipality%2c+South+Africa&page=2 url: "//images.ctfassets.net/xt8ne4gbbocd/6GqC6D7ckgwSoCCKEQqiEm/0ff3dcb37da4a9a4c5ef6275563cdfdd/SOASWC0110006.jpg" chapters: - sys: id: 4cLakkCQWQUUYiceIaW6AG created_at: !ruby/object:DateTime 2017-07-24 11:26:46.253000000 Z updated_at: !ruby/object:DateTime 2017-07-24 11:26:46.253000000 Z content_type_id: chapter revision: 1 title: Introduction title_internal: 'Contact Art: thematic, chapter 1' body: "The impact of colonisation in South Africa as a result of Dutch and English settlement from 1652 onwards has been well-documented - with devastating consequences socially, economically and culturally for many indigenous populations. \nOne of those impacts was the demise of rock art as a cultural practice by many San&#124;Bushmen, with the last rock art being made around 100 years ago. Nevertheless, rock art has provided some interesting glimpses into Colonial events, experiences and encounters from an indigenous perspective. Depictions of ships, horse-drawn wagons, guns and people wearing European clothing are not simply observational records in stone, but tell of history and heritage, memory and identity. This type of rock art, one that depicts European objects and people, is termed '*contact art*'.\n" - sys: id: 3rcFEUcVbqgqQ0mYUmgYYu created_at: !ruby/object:DateTime 2017-07-24 11:39:12.810000000 Z updated_at: !ruby/object:DateTime 2017-07-24 11:39:12.810000000 Z content_type_id: chapter revision: 1 title: History of European contact title_internal: 'Contact Art: thematic, chapter 2' body: Throughout the 15th century, Portuguese mariners navigated the western coast of Africa exploiting the lucrative trade possibilities on the continent. In 1487, Bartholomeu Dias’s expedition of two 50-ton caravels (small, fast Portuguese sailing ships of the 15th–17th centuries) anchored in Mossel Bay on the Southern Cape coast because of a storm, later sailing along the coast to Algoa Bay (east of the Cape of Good Hope) before returning to Lisbon. Ten years later, in 1497 another Portuguese expedition led by <NAME> sailed along the eastern coastline to modern day Mombasa before crossing the Indian Ocean to India (Thompson, 2014:31) - sys: id: 32Q6z3T9aU6WAUkuaI4Ikm created_at: !ruby/object:DateTime 2017-07-24 11:52:30.862000000 Z updated_at: !ruby/object:DateTime 2017-07-24 11:52:30.862000000 Z content_type_id: image revision: 1 image: sys: id: 2qghLSE632AsMMC22MskiE created_at: !ruby/object:DateTime 2017-07-24 11:51:09.713000000 Z updated_at: !ruby/object:DateTime 2017-07-24 11:51:09.713000000 Z title: Portuguese Carracks off a Rocky Coast description: url: "//images.ctfassets.net/xt8ne4gbbocd/2qghLSE632AsMMC22MskiE/e6b80c4c43d212e78e81b4f185921093/Portuguese_Carracks_off_a_Rocky_Coast.jpg" caption: 16th century painting by Flemish painter <NAME> (c.1480-1524) showing Portuguese ships leaving a port c.1540 (© National Maritime Museum) col_link: http://collections.rmg.co.uk/collections/objects/12197.html - sys: id: 3C150sXEbCMQ8QMcYKui4C created_at: !ruby/object:DateTime 2017-07-24 11:55:02.770000000 Z updated_at: !ruby/object:DateTime 2017-07-24 11:55:02.770000000 Z content_type_id: chapter revision: 1 title_internal: 'Contact Art: thematic, chapter 3' body: On 25 March 1647 the Dutch vessel, the *<NAME>*, was wrecked in a storm in Table Bay. Sixty crewman and a junior merchant named Janszen remained in the Cape for a year waiting for another vessel to collect the crew and rescued cargo to return to Holland. During the waiting period Janszen and his crew grew vegetables, bartered fresh meat from the Khoi and fished. Upon his return to Holland in 1649, Janszen produced a report for the Dutch East India Company on the feasibility of the Cape as a refreshment station. Janszen recommended it for its strategic location, the fertility of the land, the abundance of fish and most importantly, the lack of animosity towards strangers of the indigenous people (Adjibolosoo, 2001:141) Three years later, in 1652, <NAME> and 80 employees of the Dutch East India Company arrived as commander of the Cape with the aim of building a fort and supplying the Dutch fleets with fruit, vegetables and meat (Thompson, 2014:32). Van Riebeek established what is now Cape Town and is seen by many Afrikaaners as the founding father of their nation. - sys: id: 1ob9WoGxQIKok6gWwiAkEO created_at: !ruby/object:DateTime 2017-07-24 16:22:58.502000000 Z updated_at: !ruby/object:DateTime 2019-02-12 02:37:18.248000000 Z content_type_id: image revision: 2 image: sys: id: 6GsT2CqeHus8GqO2Uiq4IU created_at: !ruby/object:DateTime 2017-07-24 16:22:35.709000000 Z updated_at: !ruby/object:DateTime 2017-07-24 16:22:35.709000000 Z title: <NAME> - <NAME> se aankoms aan die Kaap description: url: "//images.ctfassets.net/xt8ne4gbbocd/6GsT2CqeHus8GqO2Uiq4IU/236c58e1ce8f1821960a33c9946d86e5/Charles_Bell_-_Jan_van_Riebeeck_se_aankoms_aan_die_Kaap.jpg" caption: A painting of the arrival of <NAME> in Table Bay in April 1652, by <NAME> (1813-1882). col_link: https://commons.wikimedia.org/wiki/File:Charles_Bell_-_Jan_van_Riebeeck_se_aankoms_aan_die_Kaap.jpg - sys: id: 6TiCFpLBHGUYCuOaOWoeYC created_at: !ruby/object:DateTime 2017-07-24 16:24:49.190000000 Z updated_at: !ruby/object:DateTime 2017-07-24 16:24:49.190000000 Z content_type_id: chapter revision: 1 title_internal: 'Contact Art: thematic, chapter 4' body: 'However, the expansion of the Dutch East India Company to the north and east of the Cape region resulted in the marginalisation of local populations. By 1740, less than a hundred years after the Dutch arrived, the traditional hunter-gatherer-fisher way of life in the Cape had all but disappeared either by the active dispossession of land, sustained political interference or enforced labour. For the indigenous populations, their “ultimate position as a servile and landless class inevitably led to the beginnings of the extinction of local indigenous culture” (Yates *et al*.1993:59). This contact between indigenous populations and European colonists was expressed early in the contact period and most vividly in rock art imagery. ' - sys: id: 4nHgrO0wmQkaUGguQKeC2I created_at: !ruby/object:DateTime 2017-08-07 23:08:33.429000000 Z updated_at: !ruby/object:DateTime 2017-08-07 23:08:33.429000000 Z content_type_id: chapter revision: 1 title: Contact Rock Art title_internal: 'Contact Art: thematic, chapter 5' body: "*Porterville* \n\n150km north-east of Cape Town in the Skurweberg Mountains, near Porterville,there is a representation of a three-masted sailing ship painted in red ochre called the ‘*Porterville Galleon*’. \n" - sys: id: 1O1Wk9Grbie4EiikoiyySE created_at: !ruby/object:DateTime 2017-08-07 23:11:59.954000000 Z updated_at: !ruby/object:DateTime 2017-08-07 23:11:59.954000000 Z content_type_id: image revision: 1 image: sys: id: 6GqC6D7ckgwSoCCKEQqiEm created_at: !ruby/object:DateTime 2016-09-12 15:11:37.019000000 Z updated_at: !ruby/object:DateTime 2018-09-19 16:32:02.304000000 Z title: SOASWC0110006 description: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3734234&partId=1&searchText=+West+Coast+District+Municipality%2c+South+Africa&page=2 url: "//images.ctfassets.net/xt8ne4gbbocd/6GqC6D7ckgwSoCCKEQqiEm/0ff3dcb37da4a9a4c5ef6275563cdfdd/SOASWC0110006.jpg" caption: "'Porterville Galleon’, South Africa. 2013,2034.19495 © TARA/<NAME>" col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3730142 - sys: id: 3tat1UEvxSwg6swC0OmWs2 created_at: !ruby/object:DateTime 2017-08-07 23:15:03.471000000 Z updated_at: !ruby/object:DateTime 2017-08-07 23:15:03.471000000 Z content_type_id: chapter revision: 1 title_internal: 'Contact Art: thematic, chapter 6' body: The detailed depiction of the vessel suggests that the artist was visually familiar with European ships. However, while three of the mast flags are pointing in the same direction, the flag on the mizzenmast (far right in the image) flies in the opposite direction, suggesting the artist was less conversant with the technology of sailing ships. In 2016, British Museum curators requested that the image of the Porterville Galleon was assessed by experts at the National Maritime Museum, who identified a cross on the shoreline (on the left of the image) and the ship to the right, including a bow, short bowsprit crossed with a spritsail yard, and three masts with Dutch flags. The combination of these features suggests the ship dates to the mid-seventeenth century date, coinciding with sinking of the *Nieuwe Haerlem* and the founding of Cape Town (Giblin and Spring, 2016:69). - sys: id: qkyiaZ7KjmACgou0suywM created_at: !ruby/object:DateTime 2017-08-07 23:20:27.981000000 Z updated_at: !ruby/object:DateTime 2017-08-07 23:20:27.981000000 Z content_type_id: chapter revision: 1 title_internal: 'Contact Art: thematic, chapter 7' body: "*Attakwaskloof* \n\nIn an east-facing sandstone overhang just north of Mossel Bay on the Southern Cape coast, the black charcoal outline of a sailing ship is drawn in a deep and broad crevice. Reddish-orange paint was applied to the rock surface first and may have served as a background or canvas on which the ship was then painted. The ship is superimposed on numerous fine line red paintings of human figures and animals as well as a series of 13 red handprints and black dots (Leggatt and Rust, 2004: 5). Although the site is more than 30km from the coast, the details of the ship visible above the water line are portrayed in clear detail. The depiction of the sailing ship corresponds with what we know of sailing ships rounding the Cape of Good Hope from the end of the 16th century. \n\nThe tricolour design of the flag on the mainmast suggests that the ship represents a Dutch vessel (Leggatt and Rust, 2004: 6). Prior to 1595 the only sailing ships known to have visited Mossel Bay were Portuguese vessels, which did not fly tricolour flags. Moreover, they attempted to avoid the southern African coast after a conflict with Khoe herders in Table Bay in 1510. The first Dutch sailing ships under the command of Cornelis de Houtman anchored in Mossel Bay on 4th August 1595, spending a week in the harbour bartering iron for cattle with the local populations (Leggatt and Rust, 2004:6).\n" - sys: id: 5jp2LySdcAseIEcsy08Ssw created_at: !ruby/object:DateTime 2017-08-13 13:20:40.339000000 Z updated_at: !ruby/object:DateTime 2019-02-12 02:39:54.322000000 Z content_type_id: image revision: 2 image: sys: id: 4oNe9JTftSCaOcw2YMicQG created_at: !ruby/object:DateTime 2017-08-07 23:23:15.928000000 Z updated_at: !ruby/object:DateTime 2017-08-07 23:23:15.928000000 Z title: <NAME> (II) - Calm - Dutch Ships Coming to Anchor - WGA24523 description: url: "//images.ctfassets.net/xt8ne4gbbocd/4oNe9JTftSCaOcw2YMicQG/2466f3251bb8f15097853570e62c8de3/Willem_van_de_Velde__II__-_Calm_-_Dutch_Ships_Coming_to_Anchor_-_WGA24523.jpg" caption: 'Late 16th century Dutch ships are depicted in this painting entitled ‘Calm: Dutch Ships Coming to Anchor’ by <NAME> (1633-1707)' col_link: https://commons.wikimedia.org/wiki/File:Willem_van_de_Velde_(II)_-_Calm_-_Dutch_Ships_Coming_to_Anchor_-_WGA24523.jpg - sys: id: 3ZSiZ5Zly8YeAcWKOs0M6k created_at: !ruby/object:DateTime 2017-08-13 13:24:03.300000000 Z updated_at: !ruby/object:DateTime 2017-08-13 13:24:03.300000000 Z content_type_id: chapter revision: 1 title_internal: 'Contact Art: thematic, chapter 8' body: "It is difficult to know exactly who the artists were of this so-called ‘contact art’, but the images of ships are likely to have been made by Khoe pastoralists and San&#124;Bushmen hunter-gatherers who were the indigenous populations when Dutch ships started landing around the southern coastline of South Africa.\n\n*Swartruggens*\n\nLater colonial period rock art can be found in a cluster of sites in the Swartruggens Hills, on the eastern margins of the Cederburg Mountains. Increasingly, European farmers started using the Swartruggens for grazing, and by 1728 some colonists were present in the region. The relative isolation of the area provided a refuge for escaped slaves, discontented employees of the Dutch East India Company and the remaining populations of the Khoisan communities (Hall and Mazel, 2005:127). \ \n\nThe rock art at Swartruggens comprises a limited but repeated set of motifs. These include men in European clothing, notably wearing wide-brimmed hats and boots, and women wearing bell-shaped crinoline dresses, cinched in at the waist. Many of the dresses are patterned with vertical and horizontal stripes. The shape and style of these dresses are reminiscent of those that dominated western female fashion between 1830-1860, and the grid pattern was a popular pattern during this time (Hall and Mazel, 2005:132). Some men are depicted smoking pipes and firing guns. \n" - sys: id: 6w7bPvqDzG4mmwKSkC2ua4 created_at: !ruby/object:DateTime 2017-08-13 13:27:37.213000000 Z updated_at: !ruby/object:DateTime 2017-08-13 13:27:37.213000000 Z content_type_id: image revision: 1 image: sys: id: 6OFVBr3mUgqcwCi4oC0u6m created_at: !ruby/object:DateTime 2017-08-13 13:27:10.583000000 Z updated_at: !ruby/object:DateTime 2017-08-13 13:27:10.583000000 Z title: '2013,2034.19509' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6OFVBr3mUgqcwCi4oC0u6m/5243bf9b8450bfab9fb3a454c2f78ca0/AN1613150762_l.jpg" caption: Women wearing European-style patterned dresses enclosed within a circle of finger dots. 2013,2034.19509 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3734258 - sys: id: 1hLrFnRQlm6eEgeG2IMIcg created_at: !ruby/object:DateTime 2017-08-13 13:29:22.353000000 Z updated_at: !ruby/object:DateTime 2017-08-13 13:31:09.148000000 Z content_type_id: chapter revision: 2 title_internal: 'Contact Art: thematic, chapter 9' body: Horses and mules are prevalent, often depicted feeding at troughs, running free and harnessed pulling wagons (Hall and Mazel, 2005:131). Of the 340 images at the site of Stompiesfontein, 165 are images of horses with 33 depictions of wagons - more than half the total number of images. Wagons are generally depicted in profile being pulled by team of 4, 6 or 8 horses (Hall and Mazel, 2005:134). The drivers of the wagons are clearly identified, wearing large brimmed hats holding long whips. In all cases the artist has depicted the interior of the wagon clearly showing the transportation of both men and women and in some cases children. Alongside the wagons are men driving packhorses or mules with others riding on horseback. A repeated feature in the wagon panels is the depiction of women who are always positioned above the wagons and encircled by finger dots (Hall and Mazel, 2005:135). The use of horse-drawn transport has been dated to around the early 19th century and coincides with the development of better road systems from Cape Town into the southern and eastern Cape regions (Hall and Mazel, 2005:136) However, until 1848, with the opening of Michell’s Pass, the area around Swartruggens was not easily accessible by horse-drawn wagons, which make a probable date of later than 1850 for the paintings (Hall and Mazel, 2005:137). - sys: id: 6Zo0yGAQ3mY8wqw8U60W2s created_at: !ruby/object:DateTime 2017-08-13 13:33:31.366000000 Z updated_at: !ruby/object:DateTime 2017-08-13 13:33:31.366000000 Z content_type_id: image revision: 1 image: sys: id: 4kZxlR0vCEkWaQIAQ8Coi0 created_at: !ruby/object:DateTime 2017-08-13 13:33:04.444000000 Z updated_at: !ruby/object:DateTime 2017-08-13 13:33:04.444000000 Z title: '2013,2034.19504 ' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4kZxlR0vCEkWaQIAQ8Coi0/2d7584a0294a352b591550629a9e4fbb/2013_2034.19504_.jpg" caption: Painted rock art panel at Swartruggens showing horse-drawn wagons, and figures in European-style clothing with guns. 2013,2034.19504 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3730134 - sys: id: 4v55jtTmQEoe2sCauwUisQ created_at: !ruby/object:DateTime 2017-08-13 13:35:21.270000000 Z updated_at: !ruby/object:DateTime 2017-08-13 13:35:21.270000000 Z content_type_id: chapter revision: 1 title_internal: 'Contact Art: thematic, chapter 10' body: | Many of the wagons depicted at Swatruggens are of a type known as the Spring Wagon or Spring Wagonette. Of South African design, these wagons were manufactured in large numbers in the last three decades of the 19th century in response to the demand for transport to the diamond mines in the north of the country (Hall and Mazel, 2005:138). As such, the wagons seen in the Swartruggens rock art are likely to have been painted from the 1870s onwards but before 1885 when the railroad reached the diamond region of Kimberley in the north. The contact period rock art at Swartruggens then seems to depict a certain event during the late 19th century when people were moving northwards seeking wealth and fortune. The production and reception of these images “stemmed from local, social, political and economic conditions of the farm labourers, squatters, drovers and shepherds - whom we assume were among the artists” (Hall and Mazel, 2005:141). - sys: id: 4vGr1ql4RGaKSy0SMWieS2 created_at: !ruby/object:DateTime 2017-08-13 13:38:13.733000000 Z updated_at: !ruby/object:DateTime 2017-08-13 13:38:13.733000000 Z content_type_id: chapter revision: 1 title: Artists and Subjects title_internal: 'Contact Art: thematic, chapter 11' body: "The identity of the artists and their relationships with the figures depicted is an interesting yet complex one. Do the images simply portray experiences of contact with Europeans or were the artists framing themselves within these tableaux? It is likely that wagons are the property of the Europeans and that the majority, if not all, of the passengers depicted are European. \n\nA common posture for figures painted outside of the context of wagons is a characteristic hands-on-hips posture, which has been identified as an European stance. Interestingly, this is a universal convention employed by contact period artists around the world in their depiction of both male and female European colonists (Hall and Mazel, 2005:142). This convention may possibly just be an observation of cultural differences, but as Hall and Mazel have suggested, “it potentially makes a wry comment about a posture of arrogance and people in the possession of idle hands“ (Hall and Mazel, 12005:142). In the rock art of the Swartruggens there does not appear to be any intentionality on the part of the artists to insert themselves into the scenes, “the people, events and episodes depicted are of the Europeans’ world and the art seems to be all about ‘outsiders’” (Hall and Mazel, 2005:143).\n" - sys: id: 4HFYx1dTdm2GEQI4Q6WwqC created_at: !ruby/object:DateTime 2017-08-13 13:39:57.014000000 Z updated_at: !ruby/object:DateTime 2017-08-13 13:39:57.014000000 Z content_type_id: image revision: 1 image: sys: id: iW6ebYDzHycokicK8kWSW created_at: !ruby/object:DateTime 2017-08-13 13:39:33.635000000 Z updated_at: !ruby/object:DateTime 2017-08-13 13:39:33.635000000 Z title: '2013,2034.19517' description: url: "//images.ctfassets.net/xt8ne4gbbocd/iW6ebYDzHycokicK8kWSW/291f7200ac8bd87ddf903921b3077f09/2013_2034.19517.jpg" caption: Detail of rock art panel showing figures withhands on hips posture. Close up of 2013,2034.19517 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3734249 - sys: id: 1IpPlvLRE42IYkcmayCUGq created_at: !ruby/object:DateTime 2017-08-13 13:41:20.696000000 Z updated_at: !ruby/object:DateTime 2017-08-13 13:41:20.696000000 Z content_type_id: chapter revision: 1 title_internal: 'Contact Art: thematic, chapter 12' body: However, this does not apply to other examples of contact rock art. Recent research has shown that some depictions in the Maloti-Drakensberg reveal a cultural admixture of both European and indigenous elements. In the 19th century, groups comprising San-, Khoe- and Bantu-speaking peoples came together to form a new cultural identity. These short-lived but culturally mixed groups reflected the social, economic and political milieu of 19th century South Africa, raiding their European neighbours for cattle and horses, exchanging them for corn, tobacco and dogs (Challis, 2012:265). As well as being ethnically diverse, they shared certain customs and belief systems. In this “creolised” (Challis, 2012:80) rock art depictions show figures on horseback, armed with guns, bows, spears, and knobkerries, wearing feathered headgear , wide-brimmed hats, tasselled armbands and skin capes (Challis, 2012:277) - sys: id: 7cu4xgoZhe48gOqI4iM2YS created_at: !ruby/object:DateTime 2017-08-13 13:45:28.447000000 Z updated_at: !ruby/object:DateTime 2017-08-13 13:45:28.447000000 Z content_type_id: image revision: 1 image: sys: id: 4CQrxTBqow4SimQQGc62yI created_at: !ruby/object:DateTime 2017-08-13 13:44:50.009000000 Z updated_at: !ruby/object:DateTime 2017-08-13 13:44:50.009000000 Z title: 'Horse and rider from the most northerly Drakensberg horse site in the Giant’s castle area. Note spears. (Challis, Retribe-4) ' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4CQrxTBqow4SimQQGc62yI/b4721fbe40e1a9556698d622456fe4a8/Horse_and_rider_from_the_most_northerly_Drakensberg_horse_site_in_the_Giant___s_castle_area._Note_spears.__Challis__Retribe-.png" caption: Horse and rider from the most northerly Drakensberg horse site in the Giant’s castle area. Note spears. (Challis 2012, Retribe:4) col_link: https://www.researchgate.net/publication/254311445_Creolisation_on_the_Nineteenth-century_Frontiers_of_Southern_Africa_A_Case_Study_of_the_AmaTola_%27Bushmen%27_in_the_Maloti-Drakensberg - sys: id: 6DhPevH8J222e6GEEkqU2A created_at: !ruby/object:DateTime 2017-08-13 13:47:17.176000000 Z updated_at: !ruby/object:DateTime 2017-08-13 13:47:17.176000000 Z content_type_id: chapter revision: 1 title_internal: 'Contact Art: thematic, chapter 13' body: Moreover, as well as the adjacencies of European and local material culture, rock art depictions show that traditional belief systems were incorporated into these tableaux. Some images depict figures engaged in dancing a variation of the Trance Dance, a traditional San medicine dance whereby shamans would enter altered states of consciousness and are represented transforming into symbolic animals such as the eland. Contact rock art amalgamates this with elements of Nguni (a local and indigenous cultural group of South Africa) culture and shamans transform instead into baboons, a symbolic animal for the Nguni that is associated with ideas of protection (Challis, 2014:249). - sys: id: 6eZhwxCwyQoUQkuWyQsooi created_at: !ruby/object:DateTime 2017-08-13 13:48:10.406000000 Z updated_at: !ruby/object:DateTime 2017-08-13 13:48:10.406000000 Z content_type_id: image revision: 1 image: sys: id: 5bo9lWxyO4YiiySIKuUIOs created_at: !ruby/object:DateTime 2017-08-13 13:48:22.538000000 Z updated_at: !ruby/object:DateTime 2017-08-13 13:48:22.538000000 Z title: Figure-8-A-Horse-and-Rider-Galloping-Behind-an-Outsize-Baboon-Traced-by-the-author-in description: url: "//images.ctfassets.net/xt8ne4gbbocd/5bo9lWxyO4YiiySIKuUIOs/a5a8066cbd9f5d39576012015e610049/Figure-8-A-Horse-and-Rider-Galloping-Behind-an-Outsize-Baboon-Traced-by-the-author-in.png" caption: Mount Fletcher region of the north Eastern Cape Province. (Challis, 2012:279) col_link: https://www.researchgate.net/publication/254311445_Creolisation_on_the_Nineteenth-century_Frontiers_of_Southern_Africa_A_Case_Study_of_the_AmaTola_%27Bushmen%27_in_the_Maloti-Drakensberg - sys: id: 227ir2Bipm8mmc2YKSMWkO created_at: !ruby/object:DateTime 2017-08-13 13:49:19.393000000 Z updated_at: !ruby/object:DateTime 2017-08-13 13:49:19.393000000 Z content_type_id: chapter revision: 1 title: Summary title_internal: 'Contact Art: thematic, chapter 14' body: Not simply a visual record of encounters and experiences, contact rock art is as complex socially, politically and culturally as the period in which it was created. Depiction of European encounters sit within a framework of local rock art traditions and belief systems as well as colonial history. citations: - sys: id: 7z28m7agdUckmmAUeEsoao created_at: !ruby/object:DateTime 2017-08-13 13:50:20.817000000 Z updated_at: !ruby/object:DateTime 2017-08-13 13:50:20.817000000 Z content_type_id: citation revision: 1 citation_line: "Adjibolosoo, <NAME>. (2001) Portraits of Human Behavior and Performance: The Human Factor in Action. Oxford and Maryland: University of America Press.\n\n<NAME>. (2012) ‘Creolisation on the Nineteenth-century Frontiers of Southern Africa: A Case Study of the AmaTola1 ‘Bushmen’ in the Maloti- Drakensberg’, in Journal of Southern African Studies, Volume 38, Number 2, pp:265-280.\n\nChallis, S. (2014) ‘Binding beliefs: the creolisation process in a ‘Bushman’ raider group in nineteenth-century southern Africa’, in The courage of |&#124;Kabbo and a century of Specimens of Bushman folklore. <NAME> and <NAME> (eds). Cape Town, UCT Press. 246-264. \n\n<NAME>. and <NAME>. (2005) ‘The Private Performance of Events: Colonial Period Rock Art from the Swartruggens’, in Kronos, No. 31, pp. 124-151.\n\n<NAME>. and <NAME>. (2004) An unusual rock painting of a ship found in the Attakwaskloof, in Digging Stick, Vol.21 (2), pp:5-8.\n\n<NAME>. (2014) A History of South Africa. New Haven and London: Yale University Press.\n\n<NAME>., <NAME>., and \ <NAME>. (1993) ‘Colonial Era Paintings in the Rock Art of the South-Western Cape: Some Preliminary Observations’, in Goodwin Series, Vol. 7, pp. 59-70.\n" background_images: - sys: id: 6QHTRqNGXmWic6K2cQU8EA created_at: !ruby/object:DateTime 2016-09-13 13:03:52.426000000 Z updated_at: !ruby/object:DateTime 2016-09-13 13:03:52.426000000 Z title: SOASWC0110006 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6QHTRqNGXmWic6K2cQU8EA/3d924964d904e34e6711c6224a7429e6/SOASWC0110006.jpg" - sys: id: 6OFVBr3mUgqcwCi4oC0u6m created_at: !ruby/object:DateTime 2017-08-13 13:27:10.583000000 Z updated_at: !ruby/object:DateTime 2017-08-13 13:27:10.583000000 Z title: '2013,2034.19509' description: url: "//images.ctfassets.net/<KEY>613150762_l.jpg" ---<file_sep>/_coll_thematic/chariots-in-the-sahara.md --- contentful: sys: id: 72UN6TbsDmocqeki00gS4I created_at: !ruby/object:DateTime 2015-11-26 17:35:22.951000000 Z updated_at: !ruby/object:DateTime 2015-12-07 20:47:35.130000000 Z content_type_id: thematic revision: 4 title: Chariots in the Sahara slug: chariots-in-the-sahara lead_image: sys: id: 2Ed8OkQdX2YIYAIEQwiY8W created_at: !ruby/object:DateTime 2015-11-26 17:17:39.181000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:17:39.181000000 Z title: '2013,2034.999' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2Ed8OkQdX2YIYAIEQwiY8W/9873a75ad2995b1b7a86923eca583f31/2013_2034.999.jpg" chapters: - sys: id: 3pSkk40LWUWs28e0A2ocI2 created_at: !ruby/object:DateTime 2015-11-26 17:27:59.282000000 Z updated_at: !ruby/object:DateTime 2018-05-16 16:42:36.356000000 Z content_type_id: chapter revision: 2 title_internal: 'Thematic: chariots, chapter 1' body: A number of sites from this Collection are located in the Libyan Desert, notably the Fezzan region, and include paintings of chariots in a variety of forms dating to the Horse Period, from up to 3,000 years ago. This has stimulated some interesting questions about the use of chariots in what appears to be such a seemingly inappropriate environment for a wheeled vehicle, as well as the nature of representation. Why were chariots used in the desert and why were they represented in such different ways? - sys: id: 2Hjql4WXLOsmCogY4EAWSq created_at: !ruby/object:DateTime 2015-11-26 17:18:19.534000000 Z updated_at: !ruby/object:DateTime 2018-05-16 16:43:36.197000000 Z content_type_id: image revision: 2 image: sys: id: 2Ed8OkQdX2YIYAIEQwiY8W created_at: !ruby/object:DateTime 2015-11-26 17:17:39.181000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:17:39.181000000 Z title: '2013,2034.999' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2Ed8OkQdX2YIYAIEQwiY8W/9873a75ad2995b1b7a86923eca583f31/2013_2034.999.jpg" caption: Two-wheeled chariot in profile view. Tihenagdal, Acacus Mountains, Libya. 2013,2034.999 © TARA / <NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3588528&partId=1&people=197356&museumno=2013,2034.999&page=1 - sys: id: 3TiPUtUxgAQUe0UGoQUqO0 created_at: !ruby/object:DateTime 2015-11-26 17:28:18.968000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:28:18.968000000 Z content_type_id: chapter revision: 1 title_internal: 'Thematic: chariots, chapter 2' body: The chariot has been one of the great empowering innovations of history. It likely originated in Mesopotamia about 3000 BC due to advances in metallurgy during the Bronze Age, and has served as a primary means of transport until quite recently in the historical period across Africa, Eurasia and Europe. Chariots provided rapid and efficient transport, and were ideal for the battlefield as the design provided a raised firing platform for archers . As a result the chariot became the principal war machine from the Egyptians through to the Romans; and the Chinese, who owned an army of 10,000 chariots. Indeed, our use of the word car is a derivative of the Latin word carrus, meaning ‘a chariot of war or of triumph’. - sys: id: 5ZxcAksrFSKEGacE2iwQuk created_at: !ruby/object:DateTime 2015-11-26 17:19:58.050000000 Z updated_at: !ruby/object:DateTime 2018-05-16 16:44:46.340000000 Z content_type_id: image revision: 2 image: sys: id: 5neJpIDOpyUQAWC8q0mCIK created_at: !ruby/object:DateTime 2015-11-26 17:17:39.141000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:17:39.141000000 Z title: '124534' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5neJpIDOpyUQAWC8q0mCIK/d8ee0111089adb2b565b48919f21dfbe/124534.jpg" caption: Neo-Assyrian Gypsum wall panel relief showing Ashurnasirpal II hunting lions, 865BC – 860 BC. © Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=367027&partId=1&people=197356&museumno=124534&page=1 - sys: id: 2Grf0McSJ2Uq4SUaUQAMwU created_at: !ruby/object:DateTime 2015-11-26 17:28:46.851000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:28:46.851000000 Z content_type_id: chapter revision: 1 title_internal: 'Thematic: chariots, chapter 3' body: The chariot in the Sahara was probably introduced by the Garamantes, a cultural group thought to be descended from Berbers and Saharan pastoralists. There is little textual information about the Garamantes, documentation comes mainly from Greek and Roman sources. Herodotus described them as ‘a very great nation’. Recent archaeological research has shown that the Garamantes established about eight major towns as well as numerous other settlements, and were ‘brilliant farmers, resourceful engineers, and enterprising merchants’. The success of the Garamantes was based on their subterranean water-extraction system, a network of underground tunnels, allowing the Garamantian culture to flourish in an increasingly arid environment, resulting in population expansion, urbanisation, and conquest. - sys: id: 6fOKcyIgKcyMi8uC4WW6sG created_at: !ruby/object:DateTime 2015-11-26 17:20:33.572000000 Z updated_at: !ruby/object:DateTime 2018-05-16 16:45:32.605000000 Z content_type_id: image revision: 2 image: sys: id: 4DBpxlJqeAS4O0eYeCO2Ms created_at: !ruby/object:DateTime 2015-11-26 17:17:39.152000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:17:39.152000000 Z title: '2013,2034.407' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4DBpxlJqeAS4O0eYeCO2Ms/18e67077bdaa437ac82e85ba48cdb0da/2013_2034.407.jpg" caption: A so-called ‘Flying gallop’ chariot. <NAME>, Acacus Mountains, Libya. 2013,2034.407 © TARA / <NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3580186&partId=1&people=197356&museumno=2013,2034.407&page=1 - sys: id: CAQ4O5QWhaCeOQAMmgGSo created_at: !ruby/object:DateTime 2015-11-26 17:29:06.521000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:29:06.521000000 Z content_type_id: chapter revision: 1 title_internal: 'Thematic: chariots, chapter 4' body: On average there are about 500 drawings of chariots across the Sahara, from the Fezzan in Libya through the Aïr of Niger into northern Mali and then westward to the Atlantic coast; but not all were produced by the Garamantes. It is still not certain that chariots were driven along the routes where their depictions occur; remains of chariots have never been found west of the Fezzan. However, the Fezzan states were thriving trade routes and chariots are likely to have been used to transport salt, cloth, beads and metal goods in exchange for gold, ivory and slaves. The widespread occurrence of chariot imagery on Saharan rock outcrops has led to the proposition of ‘chariot routes’ linking North and West Africa. However, these vehicles were not suited for long-distance transport across desert terrain; more localised use is probable, conducted through middlemen who were aware of the trade routes through the desert landscape. Additionally, the horse at this time was a prestige animal and it is unlikely that they facilitated transport across the Saharan trade routes, with travellers rather utilising donkeys or oxen. - sys: id: 5cgk0mmvKwC0IGsCyIsewG created_at: !ruby/object:DateTime 2015-11-26 17:20:59.281000000 Z updated_at: !ruby/object:DateTime 2018-05-16 16:46:44.461000000 Z content_type_id: image revision: 2 image: sys: id: 4XYASoQz6UQggUGI8gqkgq created_at: !ruby/object:DateTime 2015-11-26 17:17:39.148000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:17:39.148000000 Z title: '2013,2034.389' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4XYASoQz6UQggUGI8gqkgq/d167c56220dfd17c399b02086fe9ebc3/2013_2034.389.jpg" caption: This two wheeled chariot is being drawn by a cow with upturned horns. Awis Valley, Acacus Mountains, Libya. 2013,2034.389 © TARA / <NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3579985&partId=1&people=197356&museumno=2013,2034.389&page=1 - sys: id: 5pKuD1vPdmcs2o8eQeumM4 created_at: !ruby/object:DateTime 2015-11-26 17:29:23.611000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:29:23.611000000 Z content_type_id: chapter revision: 1 title_internal: 'Thematic: chariots, chapter 5' body: The absence of archaeological evidence for chariots has led to the suggestion that some representations of chariots may have been the result of cultural diffusion, transmitted orally by nomadic peoples traversing the region. Artists may never have actually seen the vehicles themselves. If this is the case, chariot symbols may have acquired some special meaning above their function as modes of transport. It may also explain why some representations of chariots do not seem to conform to more conventional styles of representations and account for the different ways in which they were depicted. - sys: id: wckVt1SCpqs0IYeaAsWeS created_at: !ruby/object:DateTime 2015-11-26 17:21:42.421000000 Z updated_at: !ruby/object:DateTime 2018-05-16 16:48:40.965000000 Z content_type_id: image revision: 3 image: sys: id: 279BaN9Z4QeOYAWCMSkyeQ created_at: !ruby/object:DateTime 2015-11-26 17:17:46.288000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:17:46.288000000 Z title: '2013,2034.392' description: url: "//images.ctfassets.net/xt8ne4gbbocd/279BaN9Z4QeOYAWCMSkyeQ/7606d86492a167b9ec4b105a7eb57d74/2013_2034.392.jpg" caption: These two images (above and below) depicts chariots as if ‘flattened out’, with the horses represented back to back. Awis Valley, Acacus Mountains, Libya. 2013,2034.392 © TARA / <NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3579981&partId=1&people=197356&museumno=2013,2034.392&page=1 - sys: id: 7fKfpmISPYs04YOi8G0kAm created_at: !ruby/object:DateTime 2015-11-26 17:23:05.317000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:23:05.317000000 Z content_type_id: image revision: 1 image: sys: id: 28JPIQ4mYQCMYQmMQ0Oke8 created_at: !ruby/object:DateTime 2015-11-26 17:17:45.941000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:17:45.941000000 Z title: '2013,2034.393' description: url: "//images.ctfassets.net/xt8ne4gbbocd/28JPIQ4mYQCMYQmMQ0Oke8/665bea9aafec58dfe3487ee665b3a9ec/2013_2034.393.jpg" caption: 2013,2034.393 © TARA / <NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3579980&partId=1&people=197356&museumno=2013,2034.393&page=1 - sys: id: 3xUchEu4sECWq4mAoEYYM4 created_at: !ruby/object:DateTime 2015-11-26 17:23:33.472000000 Z updated_at: !ruby/object:DateTime 2018-05-16 17:20:52.618000000 Z content_type_id: image revision: 2 image: sys: id: 697LgKlm3SWSQOu8CqSuIO created_at: !ruby/object:DateTime 2015-11-26 17:17:45.956000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:17:45.956000000 Z title: '2013,2034.370' description: url: "//images.ctfassets.net/xt8ne4gbbocd/697LgKlm3SWSQOu8CqSuIO/c8afe8c1724289dee3c1116fd4ba9280/2013_2034.370.jpg" caption: Possible chariot feature in top left of image. Acacus Mountains, Libya. 2013,2034.370 © TARA / <NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3579291&partId=1&people=197356&museumno=2013,2034.370&page=1 - sys: id: 6bQzinrqXmYESoWqyYYyuI created_at: !ruby/object:DateTime 2015-11-26 17:24:01.069000000 Z updated_at: !ruby/object:DateTime 2018-05-16 17:21:25.227000000 Z content_type_id: image revision: 2 image: sys: id: 5RKPaYinvOW6yyCGYcIsmK created_at: !ruby/object:DateTime 2015-11-26 17:17:45.952000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:17:45.952000000 Z title: '2013,2034.371' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5RKPaYinvOW6yyCGYcIsmK/a0328f912ac8f6fe017ce99d8e673421/2013_2034.371.jpg" caption: Possible chariots with two wheels. Acacus Mountains, Fezzan District, Libya. 2013,2034.371 © TARA / <NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3579290&partId=1&people=197356&museumno=2013,2034.371&page=1 - sys: id: 5qthr4HJaEoIe2sOOqiU4K created_at: !ruby/object:DateTime 2015-11-26 17:29:40.388000000 Z updated_at: !ruby/object:DateTime 2018-05-16 17:31:17.884000000 Z content_type_id: chapter revision: 2 title_internal: 'Thematic: chariots, chapter 6' body: |- The two images may or may not depict chariots. The rectangular shapes are potentially abstracted forms of the chariot similar to the ‘flattened out’ depictions discussed previously. These potentially abstracted representations often sit alongside distinguishing figures, such as geometric bi-triangular figures, spears or lances, women wearing long dresses, and animals drawn in a fairly naturalistic style, of the Horse Period when the chariots were being used. Beside the schematic and simply depicted chariots, there is also a group which has been termed the ‘flying gallop chariots’. Their distribution includes the whole Tassili region, although there are fewer in the Acacus Mountains. They resemble the classical two-wheeled antique chariots, generally drawn by two horses, but sometimes three, or even four. The driver is usually alone, and is depicted in a typical style with a stick head. The majority are shown at full speed, with the driver holding a whip standing on a small platform, sometimes straining forward. - sys: id: 2NEHx4J06IMSceEyC4w0CA created_at: !ruby/object:DateTime 2015-11-26 17:24:30.605000000 Z updated_at: !ruby/object:DateTime 2018-05-16 17:31:46.413000000 Z content_type_id: image revision: 2 image: sys: id: 74j3IOLwLS8IocMCACY2W created_at: !ruby/object:DateTime 2015-11-26 17:17:45.949000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:17:45.949000000 Z title: '2013,2034.523' description: url: "//images.ctfassets.net/xt8ne4gbbocd/74j3IOLwLS8IocMCACY2W/5495e8c245e10db13caf5cb0f36905c4/2013_2034.523.jpg" caption: "'Flying gallop’ chariot, <NAME>, Acacus Mountains, Fezzan District, Libya. 2013,2034.523 © TARA / <NAME>" col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3583068&partId=1&people=197356&museumno=2013,2034.523&page=1 - sys: id: 1YKtISfrKAQ6M4mMawIOYK created_at: !ruby/object:DateTime 2015-11-26 17:30:08.834000000 Z updated_at: !ruby/object:DateTime 2018-05-16 17:33:37.308000000 Z content_type_id: chapter revision: 2 title_internal: 'Thematic: chariots, chapter 7' body: |- In a similar manner to the schematic chariots, the 'Flying Gallop' depictions display the entire platform and both wheels of the chariot. In addition, more than one horse is depicted as a single horse in profile with numerous legs indicating multiple horses; an artistic technique first seen during the Upper Palaeolithic in Europe. Interestingly, in the Libyan rock art of the Acacus Mountains it seemed that animals could be conceived of in profile and in movement, but chariots were conceived of differently, and are represented in plain view, seen from above or in three-quarters perspective. Why are chariots depicted in a variety of ways, and what can we say about the nature of representation in relation to chariots? It is clear that chariots are able to be depicted in profile view, yet there are variations that digress from this perspective. In relation to the few examples we have come across so far in the Acacus Mountains in south-western Libya, one observation we might make is that the ways in which chariots have been represented may be indicative of the ways in which they have been observed by the artists representing them; as a rule from above. The rock shelters in the Acacus are often some height above the now dried up wadis, and so the ways in which they conceived of representing the chariot itself , whether as a flying gallop chariot, a chariot drawn by a bovid or as an abstraction, may have become a particular representational convention. The ways in which animals were represented conformed also to a convention, one that had a longer tradition, but chariots were an innovation and may have been represented as they were observed; from higher up in the rockshelters; thus chariots were conceived of as a whole and from an aerial perspective. The ways in which environments affect our perceptions of dimension, space and colour are now well-established, initially through cross-cultural anthropological studies in the 1960s, and becoming better understood through more recent research concerning the brain. Of course, this is speculation, and further research would be needed to consider all the possibilities. But for now, we can start to see some intriguing lines of enquiry and research areas that these images have stimulated. - sys: id: 4nHApyWfWowgG0qASeKEwk created_at: !ruby/object:DateTime 2015-11-26 17:25:19.180000000 Z updated_at: !ruby/object:DateTime 2018-05-16 17:34:17.369000000 Z content_type_id: image revision: 2 image: sys: id: 4Mn54dTjEQ80ssSOK0q0Mq created_at: !ruby/object:DateTime 2015-11-26 17:17:39.129000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:17:39.129000000 Z title: '135568' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4Mn54dTjEQ80ssSOK0q0Mq/c1bca8c151b882c16adaf7bc449e1850/135568.jpg" caption: Model of chariot, Middle Bronze Age – Early Bronze Age, 2000BC, Eastern Anatolia Region. 1971,0406.1 © Trustees of the British Museum. The design of this chariot is very similar to the representation in Fig. 4. col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=369521&partId=1&people=197356&museumno=135568&page=1 - sys: id: 5dtoX8DJv2UkguMM24uWwK created_at: !ruby/object:DateTime 2015-11-26 17:26:17.455000000 Z updated_at: !ruby/object:DateTime 2018-05-16 17:34:59.909000000 Z content_type_id: image revision: 2 image: sys: id: 7zQLgo270Am82CG0Qa6gaE created_at: !ruby/object:DateTime 2015-11-26 17:17:45.956000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:17:45.956000000 Z title: '894,1030.1' description: url: "//images.ctfassets.net/xt8ne4gbbocd/7zQLgo270Am82CG0Qa6gaE/80aa63978217874eaaa0960a6e0847d6/894_1030.1.jpg" caption: Bronze model of a two-horse racing chariot. Roman, 1st century – 2nd century, Latium, Tiber River. 1894,1030.1 © Trustees of the British Museum. col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=399770&partId=1&people=197356&museumno=1894,1030.1&page=1 - sys: id: 74fcVRriowwOQeWua2uMMY created_at: !ruby/object:DateTime 2015-11-26 17:30:27.301000000 Z updated_at: !ruby/object:DateTime 2018-05-16 17:35:36.578000000 Z content_type_id: chapter revision: 2 title_internal: 'Thematic: chariots, chapter 8' body: Vast trading networks across the Sahara Desert not only facilitated the spread of goods, but the routes served as a conduit for cultural diffusion through the spread of knowledge, ideas and technologies. Chariots were both functional and symbolic. As a mode of transport, as a weapon of war, as a means of trade and exchange and as a symbol of power, the chariot has been a cultural artefact for 4,000 years. Its temporal and spatial reach is evident not only in the rock art, but through the British Museum collections, which reveal comparisons between 2D rock art and 3D artefacts. Similarities and adjacencies occur not only in the structure and design of the chariots themselves but in their symbolic and pragmatic nature. - sys: id: 266zWxwbfC86gaKyG8myCU created_at: !ruby/object:DateTime 2015-11-26 17:26:53.266000000 Z updated_at: !ruby/object:DateTime 2018-05-16 17:43:56.525000000 Z content_type_id: image revision: 2 image: sys: id: 4rwQF960rueIOACosUMwoa created_at: !ruby/object:DateTime 2015-11-26 17:17:39.145000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:17:39.145000000 Z title: EA 37982 description: url: "//images.ctfassets.net/xt8ne4gbbocd/4rwQF960rueIOACosUMwoa/b5b41cda0efd36989292d004f039bace/EA_37982.jpg" caption: Fragment of a limestone tomb-painting representing the assessment of crops, c. 1350BC, Tomb of Nebamun, Thebes, Egypt. British Museum EA37982 ©Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=117388&partId=1&people=197356&museumno=37982&page=1 - sys: id: 2mTEgMGc5iiM00MOE4WSqU created_at: !ruby/object:DateTime 2015-11-26 17:27:28.284000000 Z updated_at: !ruby/object:DateTime 2018-05-16 17:44:28.029000000 Z content_type_id: image revision: 2 image: sys: id: 70cjifYtVeeqIOoOCouaGS created_at: !ruby/object:DateTime 2015-11-26 17:17:46.009000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:17:46.009000000 Z title: '1867,0101.870' description: url: "//images.ctfassets.net/xt8ne4gbbocd/70cjifYtVeeqIOoOCouaGS/066bc072069ab814687828a61e1ff1aa/1867_0101.870.jpg" caption: Gold coin of Diocletian, obverse side showing chariot. British Museum 1867,0101.870 ©Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=1189587&partId=1&people=197356&museumno=1867,0101.870&page=1 - sys: id: 5Z6SQu2oLuG40IIWEqKgWE created_at: !ruby/object:DateTime 2015-11-26 17:30:47.583000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:30:47.583000000 Z content_type_id: chapter revision: 1 title_internal: 'Thematic: chariots, chapter 9' body: A hoard of 100,000 Roman coins from the Diocletian period (not the above) were unearthed near Misurata, Libya, probably used to pay both regular Roman and local troops. Such finds demonstrate the symbolic power of the chariot and the diffusion of the imagery. citations: - sys: id: vVxzecw1jwam6aCcEA8cY created_at: !ruby/object:DateTime 2015-11-26 17:31:32.248000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:31:32.248000000 Z content_type_id: citation revision: 1 citation_line: <NAME>. ‘Kingdom of the Sands', in *Current Archaeology*, Vol. 57 No 2, March/April 2004 background_images: - sys: id: 3Cv9FvodyoQIQS2UaCo4KU created_at: !ruby/object:DateTime 2015-12-07 18:43:47.568000000 Z updated_at: !ruby/object:DateTime 2015-12-07 18:43:47.568000000 Z title: '01495388 001' description: url: "//images.ctfassets.net/xt8ne4gbbocd/3Cv9FvodyoQIQS2UaCo4KU/f243937c551a4a12f07c1063d13edaaa/01495388_001.jpg" - sys: id: 2yTKrZUOY00UsmcQ8sC0w4 created_at: !ruby/object:DateTime 2015-12-07 18:44:42.716000000 Z updated_at: !ruby/object:DateTime 2015-12-07 18:44:42.716000000 Z title: '01495139 001' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2yTKrZUOY00UsmcQ8sC0w4/8e527c421d837b3993026107d0a0acbb/01495139_001.jpg" ---<file_sep>/_coll_country/niger.md --- contentful: sys: id: 3GPYEG1KyQ4icW4yy46Y0G created_at: !ruby/object:DateTime 2015-11-26 18:53:05.784000000 Z updated_at: !ruby/object:DateTime 2018-05-17 16:52:26.695000000 Z content_type_id: country revision: 10 name: Niger slug: niger col_url: http://www.britishmuseum.org/research/collection_online/search.aspx?people=197356&place=13131 map_progress: true intro_progress: true image_carousel: - sys: id: 2lW3L3iwz60ekeWsYKgOYC created_at: !ruby/object:DateTime 2015-11-26 10:54:26.852000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:53:07.945000000 Z title: '2013,2034.9786' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3637692 url: "//images.ctfassets.net/xt8ne4gbbocd/2lW3L3iwz60ekeWsYKgOYC/c303352ed0b0976a3f1508ea30b8a41d/2013_2034.9786.jpg" - sys: id: 6yxgQFojbUcOUSwyaWwEMC created_at: !ruby/object:DateTime 2015-11-26 10:54:27.057000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:54:03.540000000 Z title: '2013,2034.8891' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3637764&partId=1&searchText=2013,2034.8891&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/6yxgQFojbUcOUSwyaWwEMC/5547eadfdf388937a8c708c145c2dba6/2013_2034.8891.jpg" featured_site: sys: id: 3iEbGKCOjuqgaMOGUQiQuS created_at: !ruby/object:DateTime 2015-11-25 15:50:42.860000000 Z updated_at: !ruby/object:DateTime 2015-12-07 20:52:09.605000000 Z content_type_id: featured_site revision: 4 title: Dabous, Niger slug: dabous chapters: - sys: id: 5j5MjrxkwgewSk0EAgqMkS created_at: !ruby/object:DateTime 2015-11-25 15:44:58.105000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:44:58.105000000 Z content_type_id: chapter revision: 1 title_internal: 'Niger: featured site, chapter 1' body: Dabous is located in north-eastern Niger, where the Ténéré desert meets the slopes of the Aïr Mountains. The area has been part of the trans-Saharan caravan trade route traversed by the Tuareg for over two millennia, but archaeological evidence shows much older occupation in the region dating back 8,000 years. More recently, it has become known to a wider global audience for its exceptional rock art. - sys: id: 5Tp7co5fdCUIi68CyKGm8o created_at: !ruby/object:DateTime 2015-11-25 15:38:46.775000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:38:46.775000000 Z content_type_id: image revision: 1 image: sys: id: 56TaQ0UFBK8sEE4GWaQOcw created_at: !ruby/object:DateTime 2015-11-25 15:37:38.020000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:37:38.020000000 Z title: '2013,2034.10543' description: url: "//images.ctfassets.net/xt8ne4gbbocd/56TaQ0UFBK8sEE4GWaQOcw/d8465329314fcafe9814b92028e90927/2013_2034.10543.jpg" caption: Dabous giraffe. Western Aïr Mountains, Niger. 2013,2034.10543 © David Coulson/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3637915&partId=1&searchText=2013,2034.9967&people=197356&place=13131&museumno=2013,2034.10543&page=1 - sys: id: 59s9c4KH8skCgKkQMaWymw created_at: !ruby/object:DateTime 2015-11-25 15:45:19.771000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:45:19.771000000 Z content_type_id: chapter revision: 1 title_internal: 'Niger: featured site, chapter 2' body: |- Recorded in 1987 by French archaeologist <NAME>, two remarkable life-size engravings of giraffe have generated much interest due to the size, realism and technique of the depictions. The two giraffe, thought to be one large male in front of a smaller female, were engraved on the weathered surface of a sandstone outcrop. The larger giraffe measures 5.4 m from top to toe and combines several techniques of production, including scraping, smoothing and deep engraving of the outlines. Each giraffe has an incised line emanating from its mouth or nose, meandering down to a small human figure. This motif is not unusual in Saharan rock art, but its meaning remains a mystery. Interpretations have suggested the line may indicate that giraffe were hunted or even domesticated, or may reflect a religious, mythical or cultural association. It has also been suggested that the lines and human figures were later additions. - sys: id: 5ZK8nNmuzKa66KOEqquoqI created_at: !ruby/object:DateTime 2015-11-25 15:39:28.089000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:39:28.089000000 Z content_type_id: image revision: 1 image: sys: id: 6Y2u961dcWISC2E2CK62KS created_at: !ruby/object:DateTime 2015-11-25 15:37:55.237000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:37:55.237000000 Z title: '2013,2034.10570' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6Y2u961dcWISC2E2CK62KS/64bef06da41a71f32cf8601c426d1608/2013_2034.10570.jpg" caption: Dabous giraffe. Western Aïr Mountains, Niger. 2013,2034.10570 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3637906&partId=1&searchText=2013,2034.10570&people=197356&place=13131&museumno=2013,2034.10570&page=1 - sys: id: ZKn6IIxaoeiw68c444iAM created_at: !ruby/object:DateTime 2015-11-25 15:40:08.118000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:40:08.118000000 Z content_type_id: image revision: 1 image: sys: id: n2nHWRqjXE0qkaEqCWK6Y created_at: !ruby/object:DateTime 2015-11-25 15:37:38.049000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:37:38.049000000 Z title: '2013,2034.10555' description: url: "//images.ctfassets.net/xt8ne4gbbocd/n2nHWRqjXE0qkaEqCWK6Y/7a3d94b2a4f3d792a0f9de60647d3d59/2013_2034.10555.jpg" caption: Dabous giraffe at night. Western Aïr Mountains, Niger. 2013,2034.10555 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3637914&partId=1&searchText=2013,2034.10570&people=197356&place=13131&museumno=2013,2034.10555&page=1 - sys: id: 1oNgYDPKxuquY6U6gsKY62 created_at: !ruby/object:DateTime 2015-11-25 15:45:53.655000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:45:53.655000000 Z content_type_id: chapter revision: 1 title_internal: 'Niger: featured site, chapter 3' body: |- The engravings cannot be seen from ground level; they are only visible by climbing onto the boulder. They are thought to date from between 6,000 and 8,000 years ago – a period known as the Neolithic Subpluvial, when environmental conditions were much wetter and the Sahara was a vast savannah stretching for thousands of miles, able to sustain large mammals such as giraffe. The soft sandstone is likely to have been incised using a harder material such as flint; there are chisels of petrified wood in the surrounding desert sands which would have acted as good tools for abrading and polishing outlines. It is easy to imagine people in the past sitting on the rocky outcrop watching these long-necked, graceful animals and immortalising them in stone for future generations. We can only speculate as to why the giraffe was selected for this special treatment. Any number of physical, behavioural, environmental or symbolic factors may have contributed to its significance. - sys: id: 3Xlo7BIZzy2umQ2Ac6M2QI created_at: !ruby/object:DateTime 2015-11-25 15:40:37.408000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:40:37.408000000 Z content_type_id: image revision: 1 image: sys: id: 4yEY9exQaswSA6k6Gu02c6 created_at: !ruby/object:DateTime 2015-11-25 15:38:02.784000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:38:02.784000000 Z title: '2013,2034.10751' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4yEY9exQaswSA6k6Gu02c6/307728aa6d1880f11af9dc45d7e7d830/2013_2034.10751.jpg" caption: Further engravings at the site. Dabous, Western Aïr Mountains, Niger. 2013,2034.10751 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3637901&partId=1&searchText=2013,2034.10570&people=197356&place=13131&museumno=2013,2034.10751&page=1 - sys: id: 2tsfZzpTFWoYacAQioAyQ0 created_at: !ruby/object:DateTime 2015-11-25 15:46:12.778000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:46:12.778000000 Z content_type_id: chapter revision: 1 title_internal: 'Niger: featured site, chapter 4' body: |- While the giraffe have taken centre stage at this site because of their size and the skill of the execution, a systematic study of the area has identified 828 further engravings, including 704 zoomorphs (animal forms), 61 anthropomorphs (human forms), and 17 inscriptions of Tifinâgh script. The animals identified include: bovines (cattle ) (46%), ostrich (16%), antelope and gazelle (16%), giraffe (16%), and finally 12 dromedaries (camels), 11 canids (dog-like mammals), 6 rhinoceros, 3 equids (horses or donkeys), 2 monkeys, 2 elephants, and 1 lion. Who might the artists have been? It is often the case in rock art research that artists are lost to us in time and we have little or no archaeological evidence that can offer insights into the populations that occupied these sites, sometimes only for a short time. However, in 2001 a site called Gobero was discovered that provides a glimpse of life in this region at the time that the Dabous engravings were produced. - sys: id: gku8mXGHUA06KW8YGgU64 created_at: !ruby/object:DateTime 2015-11-25 15:41:06.708000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:41:06.708000000 Z content_type_id: image revision: 1 image: sys: id: 5Lzyd3mFTUII2MEkgQ0ki2 created_at: !ruby/object:DateTime 2015-11-25 15:37:38.045000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:37:38.045000000 Z title: Gobero description: url: "//images.ctfassets.net/xt8ne4gbbocd/5Lzyd3mFTUII2MEkgQ0ki2/61cb38b7b4e4d62e911bb971cad67c7f/Gobero.jpg" caption: 'Aerial view of Gobero archaeological site in Niger, from the Holocene Period. Source: Sereno et al. 2008, (via Wikimedia Commons)' col_link: https://commons.wikimedia.org/wiki/File%3AGobero.jpg - sys: id: dSvovYGs3C6YsimmmIEeA created_at: !ruby/object:DateTime 2015-11-25 15:46:46.760000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:46:46.760000000 Z content_type_id: chapter revision: 1 title_internal: 'Niger: featured site, chapter 5' body: Gobero is located at the western tip of the Ténéré desert in Niger, approximately 150 km south-east of the Aïr Mountains. Situated on the edge of a paleaolake and dating from the early Holocene (7,700–6,200 years ago), it is the earliest recorded cemetery in the western Sahara and consists of around 200 burials. Skeletal evidence shows both male and females to be tall in stature, approaching two metres. Some of the burials included items of jewellery, including a young girl wearing a bracelet made from the tusk of a hippo, and a man buried with the shell of a turtle. - sys: id: 2bxmGW0ideQSs4esWCUCka created_at: !ruby/object:DateTime 2015-11-25 15:41:32.700000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:41:32.700000000 Z content_type_id: image revision: 1 image: sys: id: 24rwZWG7UA02KCgcKeaOQS created_at: !ruby/object:DateTime 2015-11-25 15:37:47.721000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:37:47.721000000 Z title: '2013,2034.10635' description: url: "//images.ctfassets.net/xt8ne4gbbocd/24rwZWG7UA02KCgcKeaOQS/762b9a27c73609c09017102e0f4cb3f4/2013_2034.10635.jpg" caption: Close up of head and neck of large giraffe. Dabous, Western Aïr Mountains, Niger. 2013,2034.10635 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3637902&partId=1&people=197356&place=13131&museumno=2013,2034.10635&page=1 - sys: id: 58NIyuAAcwEMy8WCsoIEwO created_at: !ruby/object:DateTime 2015-11-25 15:47:13.849000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:47:13.849000000 Z content_type_id: chapter revision: 1 title_internal: 'Niger: featured site, chapter 6' body: This cultural group were largely sedentary; their subsistence economy was based on fishing (Nile perch, catfish, soft-shell turtles) and hunting (hippos, bovids, small carnivores and crocodiles). Microlithis, bone harpoon points and hooks, as well as ceramics with dotted wavy-line and zig-zag impressed motif were found in burials, refuse areas and around the lake. A hiatus in the occupation of the area (6,200–5,200 years ago) occurred during a harsh arid interval, forcing the occupants to relocate. The Gobero population may not be the artists responsible for Dabous, but archaeological evidence can help formulate a picture of the environmental, social and material culture at the time of the engravings. - sys: id: 4M6x7TPSB2g20UC6ck0ism created_at: !ruby/object:DateTime 2015-11-25 15:41:59.887000000 Z updated_at: !ruby/object:DateTime 2017-01-09 17:08:32.539000000 Z content_type_id: image revision: 2 image: sys: id: 6HNDioOx44CMaGCccQQE2G created_at: !ruby/object:DateTime 2015-11-25 15:37:38.095000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:37:38.095000000 Z title: '2013,2034.10608' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6HNDioOx44CMaGCccQQE2G/9c2d264396e34b6900229a7142f38d8e/2013_2034.10608.jpg" caption: Taking a cast of the Dabous giraffe. Western Aïr Mountains, Niger. 2013,2034.10608 © <NAME>/TARA col_link: http://bit.ly/2j0rzed - sys: id: 1jPJvNv7dcciOCCiiUugQq created_at: !ruby/object:DateTime 2015-11-25 15:47:33.801000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:47:33.801000000 Z content_type_id: chapter revision: 1 title_internal: 'Niger: featured site, chapter 7' body: Unfortunately, the engravings have been subject to deterioration as a result of human intervention such as trampling, graffiti and fragments being stolen. As a result, the decision was made to preserve them by making a mould of the carvings in order to make a cast in a resistant material. Permission was granted by both the government of Niger and UNESCO and in 1999 the moulding process took place. The first cast of the mould, made in aluminium, stands at the airport of Agadez in the small desert town near the site of Dabous – an enduring symbol of the rich rock art heritage of the country. - sys: id: 2MlmKLhdHq6SQyiU0IyIww created_at: !ruby/object:DateTime 2015-11-25 15:48:27.320000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:48:27.320000000 Z content_type_id: chapter revision: 1 title_internal: 'Niger: featured site, chapter 8' body: In 2000, the giraffe engravings at Dabous were declared one of the 100 Most Endangered Sites by the [World Monuments Watch](https://www.wmf.org/). Today, a small group of Tuareg live in the area, acting as permanent guides and custodians of the site. citations: - sys: id: 5IQzdbUWHemE6WCkUUeQwi created_at: !ruby/object:DateTime 2015-11-25 15:43:52.331000000 Z updated_at: !ruby/object:DateTime 2015-12-08 18:25:23.674000000 Z content_type_id: citation revision: 3 citation_line: |+ <NAME>. ‘Réflexions sur l'identité des guerriers représentés dans les gravures de l'Adrar des Iforas et de l'Aïr’ in *Sahara*, 10, pp.31-54 <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., et al. 2008. ‘Lakeside Cemeteries in the Sahara: 5000 Years of Holocene Population and Environmental Change’. PLoS ONE, 3(8): pp.1-22 ‘The Giraffe Carvings of the Tenere Desert’: [http://www.bradshawfoundation.com/giraffe/](http://www.bradshawfoundation.com/giraffe/) background_images: - sys: id: 58CpIve4WQo8wq4ooU0SoC created_at: !ruby/object:DateTime 2015-12-07 20:33:25.148000000 Z updated_at: !ruby/object:DateTime 2015-12-07 20:33:25.148000000 Z title: NIGEAM0060015 description: url: "//images.ctfassets.net/xt8ne4gbbocd/58CpIve4WQo8wq4ooU0SoC/bdaac15fdb14d3baf1a2f2ffa2a00e80/NIGEAM0060015_jpeg.jpg" - sys: id: 4yEY9exQaswSA6k6Gu02c6 created_at: !ruby/object:DateTime 2015-11-25 15:38:02.784000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:38:02.784000000 Z title: '2013,2034.10751' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4yEY9exQaswSA6k6Gu02c6/307728aa6d1880f11af9dc45d7e7d830/2013_2034.10751.jpg" key_facts: sys: id: 3GPdGGuBuU4oiKwq6GGsqk created_at: !ruby/object:DateTime 2015-11-26 10:50:06.558000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:50:06.558000000 Z content_type_id: country_key_facts revision: 1 title_internal: 'Niger: key facts' image_count: 2,439 images date_range: Mostly 10,000BC – AD 100 main_areas: Aïr Mountains, Djado Plateau techniques: Engravings, fine line paintings main_themes: Wild animals, cattle, Barbary sheep, ostrich, horses, giraffe (Dabous) thematic_articles: - sys: id: bl0Xb7b67YkI4CMCwGwgy created_at: !ruby/object:DateTime 2015-11-27 11:40:20.548000000 Z updated_at: !ruby/object:DateTime 2019-02-12 02:25:05.303000000 Z content_type_id: thematic revision: 8 title: The art of the warrior slug: the-art-of-the-warrior lead_image: sys: id: 69ZiYmRsreOiIUUEiCuMS6 created_at: !ruby/object:DateTime 2015-11-25 17:20:27.484000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:20:27.484000000 Z title: '2013,2034.9707' description: url: "//images.ctfassets.net/xt8ne4gbbocd/69ZiYmRsreOiIUUEiCuMS6/3b4c3bdee6c66bce875eef8014e5fe93/2013_2034.9707.jpg" chapters: - sys: id: 2YeH0ki7Pq08iGWoyeI2SY created_at: !ruby/object:DateTime 2015-11-27 12:04:20.772000000 Z updated_at: !ruby/object:DateTime 2015-12-11 11:29:10.545000000 Z content_type_id: chapter revision: 2 title_internal: 'Warrior: thematic, chapter 1' body: | Historically, much of the rock art from across northern Africa has been classified according to a particular style or ‘school’ of depictions. One such category of images, known as the Libyan Warrior School or Libyan Warrior style is found predominantly in Niger. Typically, this style “…commonly depicts human figures, mainly armed warriors; women are very rare. The style is fairly crude and the technique unsophisticated, almost invariably a rather careless pecking. The figures, almost always presented frontally with their heads quite circular, with added lobes, or mushroom-shaped, are shown according to a symmetrical schema. Various garment decorations and feathers in the hair are common, and the warrior often holds one or two throwing-spears – the bow is almost lacking – and frequently also holds by the leading rein a typical horse; foreshortened with large hindquarters” (Muzzolini, 2001:614) Termed *Libyan Warriors* by French ethnographer <NAME>, these representations have been associated with Garamantes’ raids, possibly 2,500 years ago. Thought to be descended from Berbers and Saharan pastoralists who settled in central Libya from around 1500 BC, the Garamantes developed a thriving urban centre, with flourishing trade networks from Libya to Niger. In contrast, <NAME>, a military man who led two big expeditions to the Sahara in the 1920s, proposed that these figures represent Tuareg; a people reputedly of Berber descent who live a nomadic pastoralist lifestyle. They have their own script known as Tifinagh, which is thought to have Libyan roots and which is engraved onto rocks alongside other rock art depictions. - sys: id: 3TQXxJGkAgOkCuQeq4eEEs created_at: !ruby/object:DateTime 2015-11-25 17:21:56.426000000 Z updated_at: !ruby/object:DateTime 2018-05-15 14:09:37.769000000 Z content_type_id: image revision: 2 image: sys: id: 2HdsFc1kI0ogGEmGWi82Ci created_at: !ruby/object:DateTime 2015-11-25 17:20:56.981000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:20:56.981000000 Z title: '2013,2034.11148' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2HdsFc1kI0ogGEmGWi82Ci/5c85cb71338ff7ecd923c26339a73ef5/2013_2034.11148.jpg" caption: "‘Typical’ Libyan Warrior style figure with horse. Indakatte, Western Aïr Mountains, Niger. 2013,2034.11148 © TARA/<NAME>" col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3649143&partId=1&searchText=2013,2034.11148&page=1 - sys: id: IENFM2XWMKmW02sWeYkaI created_at: !ruby/object:DateTime 2015-11-27 12:05:01.774000000 Z updated_at: !ruby/object:DateTime 2015-12-11 11:30:21.015000000 Z content_type_id: chapter revision: 2 title_internal: 'Warrior: thematic, chapter 2' body: | Libyan Warrior figures are almost exclusively located in the Aïr Mountains of Niger although can also be found in the Adrar des Iforas, north-east Mali extending into Algeria. Defining the Libyan Warrior Period chronologically is a challenge and dates are fairly fluid; the earliest dates suggested start from 5,200 years ago; it certainly coincides with the Horse period between 3,000-2,000 years ago but has also been proposed to continue throughout the Camel Period, from 2,000 years ago to present. From the sample of images we have as part of this collection it is clear that not all figures designated as falling under the umbrella term of Libyan Warrior style all share the same characteristics; there are similarities, differences and adjacencies even between what we may term a ‘typical’ representation. Of course, if these images span a period of 5,000 years then this may account for the variability in the depictions. - sys: id: 1vwQrEx1gA2USS0uSUEO8u created_at: !ruby/object:DateTime 2015-11-25 17:22:32.328000000 Z updated_at: !ruby/object:DateTime 2018-05-15 14:10:06.087000000 Z content_type_id: image revision: 2 image: sys: id: 69ZiYmRsreOiIUUEiCuMS6 created_at: !ruby/object:DateTime 2015-11-25 17:20:27.484000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:20:27.484000000 Z title: '2013,2034.9707' description: url: "//images.ctfassets.net/xt8ne4gbbocd/69ZiYmRsreOiIUUEiCuMS6/3b4c3bdee6c66bce875eef8014e5fe93/2013_2034.9707.jpg" caption: "‘Typical’ Libyan Warrior style figure with antelope. Iwellene, Northern Aïr Mountains, Niger. 2013,2034.9707 © TARA/<NAME>" col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3649767&partId=1&searchText=2013,2034.9707&page=1 - sys: id: 13aC6FIWtQAauy2SYC6CQu created_at: !ruby/object:DateTime 2015-11-27 12:05:26.289000000 Z updated_at: !ruby/object:DateTime 2015-11-27 12:05:26.289000000 Z content_type_id: chapter revision: 1 title_internal: 'Warrior: thematic, chapter 3' body: However, for the majority of figures their posture is remarkably similar even though objects of material culture and the types of garments they wear may show more diversity. The overriding feature is that figures are positioned frontally with arms bent and raised, often displaying splayed fingers. In some cases figures hold weapons and shields, but some do not. Some wear obviously elaborate headdresses, but in others the features look more coiffure-like. Selected garments are decorated with geometric patterns, others are plain; not all wear items of personal ornamentation. Certainly, not all figures are associated with horses, as typically characterised. Moreover, rather than all being described as unsophisticated or careless, many are executed showing great technique and skill. So how do we start to make sense of this contradiction between consistency and variation? - sys: id: 4thny4IiHKW66c2sGySMqE created_at: !ruby/object:DateTime 2015-11-25 17:28:05.405000000 Z updated_at: !ruby/object:DateTime 2018-05-15 14:15:37.257000000 Z content_type_id: image revision: 3 image: sys: id: 4Mq2eZY2bKogMqoCmu6gmW created_at: !ruby/object:DateTime 2015-11-25 17:20:40.548000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:20:40.548000000 Z title: '2013,2034.11167' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4Mq2eZY2bKogMqoCmu6gmW/9916aa4ecde51858768639f010a0442e/2013_2034.11167.jpg" caption: Infissak, Western Aïr Mountains, Niger. 2013,2034.11167 © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3648925&partId=1&searchText=2013,2034.11167&page=1 - sys: id: 1D7OVEK1eouQAsg6e6esS4 created_at: !ruby/object:DateTime 2015-11-27 12:05:50.702000000 Z updated_at: !ruby/object:DateTime 2015-12-11 11:36:43.690000000 Z content_type_id: chapter revision: 3 title_internal: 'Warrior: thematic, chapter 4' body: A criticism of Saharan rock art research, in comparison to that which has focused on other parts of Africa, is an under-theorisation of how the art links to past ethnic, archaeological or other identities (Smith,2013:156). This is tricky when dealing with past societies which were potentially nomadic, and where their archaeological remains are scarce. However, recent anthropological research may inform our thinking in this area. A member of the Wodaabe cultural group (nomadic cattle-herders and traders in the Sahel) on seeing a photograph of a Libyan-Warrior engraving and noting the dress and earrings told photographer <NAME> that it represents a woman performing a traditional greeting dance with arms outstretched and about to clap (Coulson and Campbell,2001:210). - sys: id: 6GvLgKrVXaSIQaAMECeE2m created_at: !ruby/object:DateTime 2015-11-25 17:31:34.914000000 Z updated_at: !ruby/object:DateTime 2018-05-15 14:15:11.171000000 Z content_type_id: image revision: 2 image: sys: id: 18c47Fe9jeoIi4CouE8Eya created_at: !ruby/object:DateTime 2015-11-25 17:20:10.453000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:20:10.453000000 Z title: '2013,2034.11133' description: url: "//images.ctfassets.net/xt8ne4gbbocd/18c47Fe9jeoIi4CouE8Eya/189da8bf1c84d7f95b532cf59780fe82/2013_2034.11133.jpg" caption: Two Libyan Warrior style figures, Western Aïr Mountains, Niger. 2013,2034.11133 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3649155&partId=1&searchText=2013,2034.11133&page=1 - sys: id: 4wQK9fpysE0GEaGYOEocws created_at: !ruby/object:DateTime 2015-11-27 12:06:27.167000000 Z updated_at: !ruby/object:DateTime 2018-05-15 14:17:33.313000000 Z content_type_id: chapter revision: 3 title_internal: 'Warrior: thematic, chapter 5' body: "Such a comment suggests that local ethnographies might assist in an understanding of more recent rock art, that not all figures described as Libyan-Warrior may necessarily be the same, and indeed that women may not be as rare as previously documented. In fact, the Wodaabe have been noted to resemble figures in other Saharan rock art contexts (see article on Hairdressing in the Acacus).\n\nIf we accept that some of these representations share affinities with the Wodaabe then thinking about this category of images from an ethnographic perspective may prove productive. Moreover, the British Museum’s existing ethnographic collections are simultaneously a useful resource by which we can potentially add more meaning to the rock art images.\n\nThe Wodaabe belong to the Fulani people, numbering 20 million and currently living across eighteen countries. The Wodaabe comprise 2-3% of the Fulani cultural group, still live as true nomads and are considered to have the most traditional culture of all the Fulani (Bovin,2001:13).\t\n" - sys: id: 2oNDIVZY2cY6y2ACUykYiW created_at: !ruby/object:DateTime 2015-11-25 17:31:55.456000000 Z updated_at: !ruby/object:DateTime 2018-05-15 14:26:02.339000000 Z content_type_id: image revision: 2 image: sys: id: 2klydX5Lbm6sGIUO8cCuow created_at: !ruby/object:DateTime 2015-11-25 17:20:40.581000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:20:40.581000000 Z title: Wodaabe description: url: "//images.ctfassets.net/xt8ne4gbbocd/2klydX5Lbm6sGIUO8cCuow/af221201c757ffe51e741300ffaefcba/Wodaabe.jpg" caption: Wodaabe men preparing for Gerewol ceremony ©<NAME>, Wikimedia Commons col_link: https://commons.wikimedia.org/wiki/File:Flickr_-_Dan_Lundberg_-_1997_%5E274-33_Gerewol_contestants.jpg - sys: id: 3SOhBsJLQACesg4wogaksm created_at: !ruby/object:DateTime 2015-11-27 12:07:09.983000000 Z updated_at: !ruby/object:DateTime 2015-11-27 12:07:09.983000000 Z content_type_id: chapter revision: 1 title_internal: 'Warrior: thematic, chapter 6' body: "The Wodaabe have become particularly well-known in the West through visual anthropology, because of their emphasis on cultivating male personal beauty and adornment. Men invest enormous amounts of time in personal artistic expression; much more so than women. Anthropologists have documented the constant checking of Wodaabe men in their mirrors; a Wodaabe man will not even go out among the cows in the morning until he has checked and tidied himself. They spend hours every day on their appearance and have been described as styling themselves like “living paintings” and “living statues” (Bovin, 2001:72). Symmetry plays a particularly significant part in Wodaabe culture and is reflected in all their artistic expressions. Symmetry stands for culture, asymmetry stands for nature. Culture is order and nature is disorder (Bovin,2001:17). Everyday Wodaabe life is imbued with artistic expression, whereby “every individual is an active creator, decorator and performer (Bovin, 2001:15).\n\nSo, how might we see Wodaabe cultural traits reflected in the Libyan-Warrior figures?\n\nPlumage is often depicted on these Warrior figures and for the most part is assumed to simply be part of the warrior regalia. The ostrich feather, a phallic symbol in Wodaabe culture, is an important element in male adornment and is carefully placed in the axis of symmetry in the middle of a man’s turban, worn during dancing ceremonies (Bovin, 2001:41). Music and dancing are typical of Fulani traditions, characterized by group singing and accompanied by clapping, stomping and bells. The feathers in the British Museum’s collections are known to be dance ornaments, worn during particular ceremonies. \n" - sys: id: 4AsNsHJ1n2USWMU68cIUko created_at: !ruby/object:DateTime 2015-11-27 11:46:03.474000000 Z updated_at: !ruby/object:DateTime 2018-05-15 14:30:37.659000000 Z content_type_id: image revision: 4 image: sys: id: 6QT0CdFAgoISmsuUk6u4OW created_at: !ruby/object:DateTime 2015-11-27 11:54:37.045000000 Z updated_at: !ruby/object:DateTime 2015-11-27 11:54:37.045000000 Z title: Af2005,04.6 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6QT0CdFAgoISmsuUk6u4OW/02489b2a4374bdb0a92ad9684f6120f4/Af2005_04.6_1.jpg" caption: Wodaabe dancing feather from the British Museum collections. Af2005,04.6 © Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=1585897&partId=1&searchText=Af2005%2c04.6&view=list&page=1 - sys: id: 5z7EqYMmFaI0Eom6AAgu6i created_at: !ruby/object:DateTime 2015-11-27 11:57:19.817000000 Z updated_at: !ruby/object:DateTime 2018-05-15 14:28:41.984000000 Z content_type_id: image revision: 2 image: sys: id: 10pBS62m3eugyAkY8iQYGs created_at: !ruby/object:DateTime 2015-11-25 17:20:48.548000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:20:48.548000000 Z title: '2013,2034.9037' description: url: "//images.ctfassets.net/xt8ne4gbbocd/10pBS62m3eugyAkY8iQYGs/b54aab41922ff6690ca59533afddeb84/2013_2034.9037.jpg" caption: Libyan Warrior figure showing symmetrical plumage from Eastern Aïr Mountains, Niger. 2013,2034.9037 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3636108&partId=1&searchText=2013,2034.9037&page=1 - sys: id: 1UmQD1rR0IISqKmGe4UWYs created_at: !ruby/object:DateTime 2015-11-27 11:47:12.062000000 Z updated_at: !ruby/object:DateTime 2018-05-15 14:28:08.133000000 Z content_type_id: image revision: 3 image: sys: id: 5oL3JD0PbaEMMyu4mA0oGw created_at: !ruby/object:DateTime 2015-11-27 11:54:37.053000000 Z updated_at: !ruby/object:DateTime 2015-11-27 11:54:37.053000000 Z title: Af2005,04.20 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/5oL3JD0PbaEMMyu4mA0oGw/72bb636538c36d21c62fef5628556238/Af2005_04.20_1.jpg" caption: Wodaabe dancing feather from the British Museum collections. Af2005,04.20 © Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=1585792&partId=1&searchText=Af2005%2c04.20&view=list&page=1 - sys: id: 45NYo7UU5ymOCYiqEYyQQO created_at: !ruby/object:DateTime 2015-11-27 12:07:34.816000000 Z updated_at: !ruby/object:DateTime 2015-11-27 12:07:34.816000000 Z content_type_id: chapter revision: 1 title_internal: 'Warrior: thematic, chapter 7' body: One of the recurring features of the Warrior engravings is the round discs that seem to be suspended from a figure’s arm or shoulder. Historically, these have been interpreted as shields, which one might expect a warrior to be carrying and in part this may be the case. - sys: id: 55JXs6mmfCoM6keQuwSeKA created_at: !ruby/object:DateTime 2015-11-27 11:59:13.850000000 Z updated_at: !ruby/object:DateTime 2018-05-15 14:31:16.112000000 Z content_type_id: image revision: 2 image: sys: id: 3s0PrjlXlS2QwMKMk0giog created_at: !ruby/object:DateTime 2015-11-25 17:20:56.985000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:20:56.985000000 Z title: '2013,2034.9554' description: url: "//images.ctfassets.net/xt8ne4gbbocd/3s0PrjlXlS2QwMKMk0giog/bef0019b59e2abe3ba3e29a4377eedd0/2013_2034.9554.jpg" caption: Warrior style figure holding ‘shields’. Eastern Aïr Mountains, Niger. 2013,2034.9554 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3639988&partId=1&searchText=2013,2034.9554&page=1 - sys: id: 2UL4zsEuwgekwI0ugSOSok created_at: !ruby/object:DateTime 2015-11-27 11:59:49.961000000 Z updated_at: !ruby/object:DateTime 2018-05-15 14:31:41.776000000 Z content_type_id: image revision: 2 image: sys: id: 3XjtbP2JywoCw8Qm0O8iKo created_at: !ruby/object:DateTime 2015-11-25 17:20:48.555000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:20:48.555000000 Z title: '2013,2034.9600' description: url: "//images.ctfassets.net/xt8ne4gbbocd/3XjtbP2JywoCw8Qm0O8iKo/fc0ccf0eb00a563da9a60276c87bbc11/2013_2034.9600.jpg" caption: Warrior style figure holding ‘shields’. Eastern Aïr Mountains, Niger. 2013,2034.9600 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3639940&partId=1&searchText=2013,2034.9600&page=1 - sys: id: 64MCgMHx60M8e0GSCaM2qm created_at: !ruby/object:DateTime 2015-11-27 12:07:53.749000000 Z updated_at: !ruby/object:DateTime 2015-11-27 12:07:53.749000000 Z content_type_id: chapter revision: 1 title_internal: 'Warrior: thematic, chapter 8' body: However, others may represent shoulder bags or flat baskets which are used as vessel covers or food trays; both of which are vital items in a nomadic lifestyle. Alternatively, they may represent calabashes. Wodaabe women measure their worldly wealth in calabashes and can acquire many in a lifetime, mostly ornamental to be displayed only on certain ceremonial occasions. If some of these depictions are not necessarily men or warriors then what have been considered shields may in fact represent some other important item of material culture. - sys: id: 78Ks1B0PPUA8YIm0ugMkQK created_at: !ruby/object:DateTime 2015-11-27 12:00:47.553000000 Z updated_at: !ruby/object:DateTime 2018-05-15 14:33:27.671000000 Z content_type_id: image revision: 2 image: sys: id: 5SDdxljduwuQggsuWcYUCA created_at: !ruby/object:DateTime 2015-11-25 17:20:48.583000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:20:48.583000000 Z title: Af,B47.19 description: url: "//images.ctfassets.net/xt8ne4gbbocd/5SDdxljduwuQggsuWcYUCA/eeb48a1ec8550bb4e1622317e5b7cea0/Af_B47.19.jpg" caption: Photograph of three Fulani male children 'dressed up for a ceremonial dance'. They are carrying shoulder-bags and holding sticks, and the male at right has flat basket impaled on stick. Rural setting. Af,B47.19 © Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=1410664&partId=1&searchText=Af,B47.19&page=1 - sys: id: 5nvXXoq4Baa0IwOmMSiUkI created_at: !ruby/object:DateTime 2015-11-27 12:08:13.833000000 Z updated_at: !ruby/object:DateTime 2015-11-27 12:08:13.833000000 Z content_type_id: chapter revision: 1 title_internal: 'Warrior: thematic, chapter 9' body: Engraved figures are often depicted with geometric patterning across their torso which may reflect traditional garments. This armless Wodaabe vest is decorated with abstract geometric combinations; patterns similar to those found on amulets, bags, containers and other artefacts as well as rock art. - sys: id: 1Huul8DwMcACSECuGoASE2 created_at: !ruby/object:DateTime 2015-11-27 12:01:35.826000000 Z updated_at: !ruby/object:DateTime 2018-05-15 14:35:18.268000000 Z content_type_id: image revision: 2 image: sys: id: 1PmWIHnxq0cAESkGiiWCkK created_at: !ruby/object:DateTime 2015-11-25 17:20:48.554000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:20:48.554000000 Z title: '7,2023.1' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1PmWIHnxq0cAESkGiiWCkK/51912ac1b7bffafe18fbbbb48a253fe9/7_2023.1.jpg" caption: Wodaabe vest, Niger. 2007,2023.1 ©Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3372277&partId=1&searchText=2007%2c2023.1&view=list&page=1 - sys: id: GT1E1E6FMc04CaQQUEuG6 created_at: !ruby/object:DateTime 2015-11-27 12:02:14.003000000 Z updated_at: !ruby/object:DateTime 2018-05-15 14:37:15.633000000 Z content_type_id: image revision: 2 image: sys: id: lz2F9O4kSWoi2g68csckA created_at: !ruby/object:DateTime 2015-11-25 17:20:48.580000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:20:48.580000000 Z title: '2013,2034.9016' description: url: "//images.ctfassets.net/xt8ne4gbbocd/lz2F9O4kSWoi2g68csckA/97f7a9fbec98c4af224273fbd3f7e9a5/2013_2034.9016.jpg" caption: Eastern Aïr Mountains, Niger. 2013,2034.9016 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3636134&partId=1&searchText=2013%2c2034.9016&&page=1 - sys: id: MH7tazL1u0ocyy6ysc8ci created_at: !ruby/object:DateTime 2015-11-27 12:08:38.359000000 Z updated_at: !ruby/object:DateTime 2015-11-27 12:08:38.359000000 Z content_type_id: chapter revision: 1 title_internal: 'Warrior: thematic, chapter 10' body: |- There is also a consensus within Wodaabe society about beauty and ugliness; what makes something beautiful or indeed ugly generally is agreed upon, there is a commonality of taste. This may account for the paradox of why there is individuality within a corpus of images that inherently are comparable (Bovin,2001:16). As nomads, Wodaabe do not identify themselves by place or territory as such, but a Wodaabe’s body is a repository of culture to mark them out against nature. Culture is not seen as an unessential indulgence but as an imperative necessity, it is part of one’s survival and existence in an inhospitable environment. We may speculate that rock art images may be seen as a way of stamping culture on nature; markers of socialised space. - sys: id: 5f7LkndYMoCiE0C6cYI642 created_at: !ruby/object:DateTime 2015-11-27 12:02:44.521000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:04:54.162000000 Z content_type_id: image revision: 4 image: sys: id: 4S1bl6LKUEKg0mMiQMoS2i created_at: !ruby/object:DateTime 2015-11-25 17:20:33.489000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:20:33.489000000 Z title: Gerewol description: url: "//images.ctfassets.net/xt8ne4gbbocd/4S1bl6LKUEKg0mMiQMoS2i/77678da7ac7b9573cfdfdcc9222b4187/Gerewol.jpg" caption: Wodaabe participants in the Gerewol beauty contest. ©<NAME> via Wikimedia Commons col_link: https://commons.wikimedia.org/wiki/File:1997_274-5_Gerewol.jpg - sys: id: 2s5eLxURwgEKUGYiCc62MM created_at: !ruby/object:DateTime 2015-11-27 12:03:20.752000000 Z updated_at: !ruby/object:DateTime 2018-05-15 14:40:40.756000000 Z content_type_id: image revision: 2 image: sys: id: 3as8UfaNIk22iQwu2uccsO created_at: !ruby/object:DateTime 2015-11-25 17:20:57.016000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:20:57.016000000 Z title: '2013,2034.9685' description: url: "//images.ctfassets.net/xt8ne4gbbocd/3as8UfaNIk22iQwu2uccsO/bef9cc4c65f13f394c4c6c03fa665aab/2013_2034.9685.jpg" caption: Four Warrior style figures, Eastern Aïr Mountains, Niger. 2013,2034.9685 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3644735&partId=1&searchText=2013,2034.9685&page=1 - sys: id: 4c37ixkB72GaCAkSYwGmSI created_at: !ruby/object:DateTime 2015-11-27 12:08:59.408000000 Z updated_at: !ruby/object:DateTime 2015-11-27 12:08:59.408000000 Z content_type_id: chapter revision: 1 title_internal: 'Warrior: thematic, chapter 11' body: This brief review was motivated, in part, by the underlying problems inherent in the categorisation of visual culture. Historically assigned classifications are not fixed and armed with current knowledge across a range of resources we may provide further insights into these enigmatic representations. Obviously, a much more systematic study of this category known as Libyan-Warrior figures needs to be undertaken to determine their distribution and the similarities and differences between depictions across sites. Additionally, care must be taken making connections with a cultural group whose material culture has changed over the course of the twentieth century. Nevertheless, it seems the category of Libyan-Warrior figures is an area that is ripe for more intensive investigation. citations: - sys: id: 2YpbTzVtq8og44KCIYKySK created_at: !ruby/object:DateTime 2015-11-25 17:17:36.606000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:17:36.606000000 Z content_type_id: citation revision: 1 citation_line: | <NAME>. 2001. *Nomads Who Cultivate Beauty*. Uppsala: Nordiska Afrikainstitutet <NAME> and <NAME>. 2001. *African Rock Art: Paintings and Engravings on Stone*. New York: Harry N Abrams <NAME>. 2001. ‘Saharan Africa’ In Whitley, D. (ed) *Handbook of Rock Art Research*: pp.605-636. Walnut Creek: Altamira Press <NAME>. 2013. Rock art research in Africa. In: Lane, P. & Mitchell, P. (eds) *Handbook of African Archaeology*: 145-162. Oxford: Oxford University Press. background_images: - sys: id: 4ICv2mLYykaUs2K6sI600e created_at: !ruby/object:DateTime 2015-12-07 19:16:46.680000000 Z updated_at: !ruby/object:DateTime 2015-12-07 19:16:46.680000000 Z title: NIGNAM0010007 description: url: "//images.ctfassets.net/xt8ne4gbbocd/4ICv2mLYykaUs2K6sI600e/175a170bba1f5856e70c2bb59a88e28f/NIGNAM0010007.jpg" - sys: id: 4sWbJZXtCUKKqECk24wOwi created_at: !ruby/object:DateTime 2015-12-07 19:16:46.673000000 Z updated_at: !ruby/object:DateTime 2015-12-07 19:16:46.673000000 Z title: NIGEAM0070022 description: url: "//images.ctfassets.net/xt8ne4gbbocd/4sWbJZXtCUKKqECk24wOwi/63797d84c9f0c89db25bd2f2cebaa21b/NIGEAM0070022.jpg" - sys: id: 1KwPIcPzMga0YWq8ogEyCO created_at: !ruby/object:DateTime 2015-11-26 16:25:56.681000000 Z updated_at: !ruby/object:DateTime 2015-12-07 20:49:15.151000000 Z content_type_id: thematic revision: 5 title: 'Sailors on sandy seas: camels in Saharan rock art' slug: camels-in-saharan-rock-art lead_image: sys: id: 46X3vtG1faouSYYws0Aywu created_at: !ruby/object:DateTime 2015-11-26 16:07:51.521000000 Z updated_at: !ruby/object:DateTime 2019-02-12 02:30:35.572000000 Z title: View of camel salt caravan crossing the Ténéré desert. Niger. ©David Coulson/TARA description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3652083&partId=1&searchText=2013,2034.10379&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/46X3vtG1faouSYYws0Aywu/6ff8cc3f26c918c81157746e1b2b3131/Fig._1._Camel.jpg" chapters: - sys: id: 1Q7xHD856UsISuceGegaqI created_at: !ruby/object:DateTime 2015-11-26 16:19:29.618000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:19:29.618000000 Z content_type_id: chapter revision: 1 title_internal: 'Camels: thematic, chapter 1' body: 'If we were to choose a defining image for the Sahara Desert, it would probably depict an endless sea of yellow dunes under a blue sky and, off in the distance, a line of long-legged, humped animals whose profiles have become synonymous with deserts: the one-humped camel (or dromedary). Since its domestication, the camel’s resistance to heat and its ability to survive with small amounts of water and a diet of desert vegetation have made it a key animal for inhabitants of the Sahara, deeply bound to their economy, material culture and lifestyle.' - sys: id: 4p7wUbC6FyiEYsm8ukI0ES created_at: !ruby/object:DateTime 2015-11-26 16:09:23.136000000 Z updated_at: !ruby/object:DateTime 2019-02-12 02:30:19.986000000 Z content_type_id: image revision: 3 image: sys: id: 46X3vtG1faouSYYws0Aywu created_at: !ruby/object:DateTime 2015-11-26 16:07:51.521000000 Z updated_at: !ruby/object:DateTime 2019-02-12 02:30:35.572000000 Z title: View of camel salt caravan crossing the Ténéré desert. Niger. ©David Coulson/TARA description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3652083&partId=1&searchText=2013,2034.10379&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/46X3vtG1faouSYYws0Aywu/6ff8cc3f26c918c81157746e1b2b3131/Fig._1._Camel.jpg" caption: Camel salt caravan crossing the Ténéré desert in Niger. 2013,2034.10487 ©<NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3652360&partId=1&searchText=2013,2034.10487&page=1 - sys: id: 1LsXHHPAZaIoUksC2US08G created_at: !ruby/object:DateTime 2015-11-26 16:19:46.820000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:19:46.820000000 Z content_type_id: chapter revision: 1 title_internal: 'Camels: thematic, chapter 2' body: Yet, surprising as it seems, the camel is a relative newcomer to the Sahara – at least when compared to other domestic animals such as cattle, sheep, horses and donkeys. Although the process is not yet fully known, camels were domesticated in the Arabian Peninsula around the third millennium BC, and spread from there to the Middle East, North Africa and Somalia from the 1st century AD onwards. The steps of this process from Egypt to the Atlantic Ocean have been documented through many different historical sources, from Roman texts to sculptures or coins, but it is especially relevant in Saharan rock art, where camels became so abundant that they have given their name to a whole period. The depictions of camels provide an incredible amount of information about the life, culture and economy of the Berber and other nomadic communities from the beginnings of the Christian era to the Muslim conquest in the late years of the 7th century. - sys: id: j3q9XWFlMOMSK6kG2UWiG created_at: !ruby/object:DateTime 2015-11-26 16:10:00.029000000 Z updated_at: !ruby/object:DateTime 2018-05-17 14:21:07.255000000 Z content_type_id: image revision: 2 image: sys: id: 6afrRs4VLUS4iEG0iwEoua created_at: !ruby/object:DateTime 2015-11-26 16:07:34.273000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:34.273000000 Z title: EA26664 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6afrRs4VLUS4iEG0iwEoua/e00bb3c81c6c9b44b5e224f5a8ce33a2/EA26664.jpg" caption: Roman terracotta camel with harness, 1st – 3rd century AD, Egypt. British Museum 1891,0403.31 © Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?museumno=1891,0430.31&objectId=118725&partId=1 - sys: id: NxdAnazJaUkeMuyoSOy68 created_at: !ruby/object:DateTime 2015-11-26 16:20:03.948000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:20:03.948000000 Z content_type_id: chapter revision: 1 title_internal: 'Camels: thematic, chapter 3' body: 'What is it that makes camels so suited to deserts? It is not only their ability to transform the fat stored in their hump into water and energy, or their capacity to eat thorny bushes, acacia leaves and even fish and bones. Camels are also able to avoid perspiration by manipulating their core temperature, enduring fluctuations of up to six degrees that could be fatal for other mammals. They rehydrate very quickly, and some of their physical features (nostrils, eyebrows) have adapted to increase water conservation and protect the animals from dust and sand. All these capacities make camels uniquely suited to hot climates: in temperatures of 30-40 °C, they can spend up to 15 days without water. In addition, they are large animals, able to carry loads of up to 300kg, over long journeys across harsh environments. The pads on their feet have evolved so as to prevent them from sinking into the sand. It is not surprising that dromedaries are considered the ‘ships of the desert’, transporting people, commodities and goods through the vast territories of the Sahara.' - sys: id: 2KjIpAzb9Kw4O82Yi6kg2y created_at: !ruby/object:DateTime 2015-11-26 16:10:36.039000000 Z updated_at: !ruby/object:DateTime 2018-05-17 14:39:34.523000000 Z content_type_id: image revision: 2 image: sys: id: 6iaMmNK91YOU00S4gcgi6W created_at: !ruby/object:DateTime 2015-11-26 16:07:51.477000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:51.477000000 Z title: Af1937,0105.16 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6iaMmNK91YOU00S4gcgi6W/4a850695b34c1766d1ee5a06f61f2b36/Af1937_0105.16.jpg" caption: Clay female dromedary (possibly a toy), Somalia. British Museum Af1937,0105.16 © Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?assetId=1088379&objectId=590967&partId=1 - sys: id: 12mIwQ0wG2qWasw4wKQkO0 created_at: !ruby/object:DateTime 2015-11-26 16:11:00.578000000 Z updated_at: !ruby/object:DateTime 2018-05-17 14:45:29.810000000 Z content_type_id: image revision: 2 image: sys: id: 4jTR7LKYv6IiY8wkc2CIum created_at: !ruby/object:DateTime 2015-11-26 16:07:51.505000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:51.505000000 Z title: Fig. 4. Man description: url: "//images.ctfassets.net/xt8ne4gbbocd/4jTR7LKYv6IiY8wkc2CIum/3dbaa11c18703b33840a6cda2c2517f2/Fig._4._Man.jpg" caption: Man leading a camel train through the Ennedi Plateau, Chad. 2013,2034.6134 ©<NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3636989&partId=1&searchText=2013,2034.6134&page=1 - sys: id: 6UIdhB0rYsSQikE8Yom4G6 created_at: !ruby/object:DateTime 2015-11-26 16:20:29.219000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:20:29.219000000 Z content_type_id: chapter revision: 1 title_internal: 'Camels: thematic, chapter 4' body: As mentioned previously, camels came from the Arabian Peninsula through Egypt, where bone remains have been dated to the early 1st millennium BC. However, it took hundreds of years to move into the rest of North Africa due to the River Nile, which represented a major geographical and climatic barrier for these animals. The expansion began around the beginning of the Christian era, and probably took place both along the Mediterranean Sea and through the south of the Sahara. At this stage, it appears to have been very rapid, and during the following centuries camels became a key element in the North African societies. They were used mainly for riding, but also for transporting heavy goods and even for ploughing. Their milk, hair and meat were also used, improving the range of resources available to their herders. However, it seems that the large caravans that crossed the desert searching for gold, ivory or slaves came later, when the Muslim conquest of North Africa favoured the establishment of vast trade networks with the Sahel, the semi-arid region that lies south of the Sahara. - sys: id: YLb3uCAWcKm288oak4ukS created_at: !ruby/object:DateTime 2015-11-26 16:11:46.395000000 Z updated_at: !ruby/object:DateTime 2018-05-17 14:46:15.751000000 Z content_type_id: image revision: 2 image: sys: id: 5aJ9wYpcHe6SImauCSGoM8 created_at: !ruby/object:DateTime 2015-11-26 16:06:48.336000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:06:48.336000000 Z title: '1923,0401.850' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5aJ9wYpcHe6SImauCSGoM8/74efd37612ec798fd91c2a46c65587f7/1923_0401.850.jpg" caption: Glass paste gem imitating beryl, engraved with a short, bearded man leading a camel with a pack on its hump. Roman Empire, 1st – 3rd century AD. 1923,0401.850 ©Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=434529&partId=1&museumno=1923,0401.850&page=1 - sys: id: 3uitqbkcY8s8GCcicKkcI4 created_at: !ruby/object:DateTime 2015-11-26 16:20:45.582000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:20:45.582000000 Z content_type_id: chapter revision: 1 title_internal: 'Camels: thematic, chapter 5' body: Rock art can be extremely helpful in learning about the different ways in which camels were used in the first millennium AD. Images of camels are found in both engravings and paintings in red, white or – on rare occasions – black; sometimes the colours are combined to achieve a more impressive effect. They usually appear in groups, alongside humans, cattle and, occasionally, dogs and horses. Sometimes, even palm trees and houses are included to represent the oases where the animals were watered. Several of the scenes show female camels herded or taking care of their calves, showing the importance of camel-herding and breeding for the Libyan-Berber communities. - sys: id: 5OWosKxtUASWIO6IUii0EW created_at: !ruby/object:DateTime 2015-11-26 16:12:17.552000000 Z updated_at: !ruby/object:DateTime 2018-05-17 15:11:49.775000000 Z content_type_id: image revision: 2 image: sys: id: 3mY7XFQW6QY6KekSQm6SIu created_at: !ruby/object:DateTime 2015-11-26 16:06:48.343000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:06:48.343000000 Z title: '2013,2034.383' description: url: "//images.ctfassets.net/xt8ne4gbbocd/3mY7XFQW6QY6KekSQm6SIu/85c0b70ab40ead396c695fe493081801/2013_2034.383.jpg" caption: Painted scene of a village, depicting a herd or caravan of camels guided by riders and dogs. <NAME>, Acacus Mountains, Libya. 2013,2034.383 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3579914&partId=1&museumno=2013,2034.383&page=1 - sys: id: 2Ocb7A3ig8OOkc2AAQIEmo created_at: !ruby/object:DateTime 2015-11-26 16:12:48.147000000 Z updated_at: !ruby/object:DateTime 2018-05-17 15:12:22.249000000 Z content_type_id: image revision: 2 image: sys: id: 2xR2nZml7mQAse8CgckCa created_at: !ruby/object:DateTime 2015-11-26 16:07:51.480000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:51.480000000 Z title: '2013,2034.5117' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2xR2nZml7mQAse8CgckCa/984e95b65ebdc647949d656cb08c0fc9/2013_2034.5117.jpg" caption: Engravings of a female camel with calves. <NAME>. 2013,2034.5117 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3624292&partId=1&museumno=2013,2034.5117&page=1 - sys: id: 4iTHcZ38wwSyGK8UIqY2yQ created_at: !ruby/object:DateTime 2015-11-26 16:13:13.897000000 Z updated_at: !ruby/object:DateTime 2018-05-17 15:31:09.339000000 Z content_type_id: image revision: 2 image: sys: id: 1ecCbVeHUGa2CsYoYSQ4Sm created_at: !ruby/object:DateTime 2015-11-26 16:07:34.241000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:34.241000000 Z title: Fig. 8. Painted description: url: "//images.ctfassets.net/xt8ne4gbbocd/1ecCbVeHUGa2CsYoYSQ4Sm/21b2aebd215d0691482411608ad5682f/Fig._8._Painted.jpg" caption: " Painted scene of Libyan-Berber warriors riding camels, accompanied by infantry and cavalrymen. Kozen Pass, Chad. 2013,2034.7295 © <NAME>/TARA" col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3655154&partId=1&searchText=2013,2034.7295&page=1 - sys: id: 2zqiJv33OUM2eEMIK2042i created_at: !ruby/object:DateTime 2015-11-26 16:21:08.068000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:21:08.068000000 Z content_type_id: chapter revision: 1 title_internal: 'Camels: thematic, chapter 6' body: |- That camels were used to transport goods is obvious, and depictions of long lines of animals are common, sometimes with saddles on which to place the packs and ropes to tie the animals together. However, if rock art depictions are some indication of camel use, it seems that until the Muslim conquest the main function of one-humped camels was as mounts, often linked to war. The Sahara desert contains dozens of astonishingly detailed images of warriors riding camels, armed with spears, long swords and shields, sometimes accompanied by infantry soldiers and horsemen. Although camels are not as good as horses for use as war mounts (they are too tall and make insecure platforms for shooting arrows), they were undoubtedly very useful in raids – the most common type of war activity in the desert – as well as being a symbol of prestige, wealth and authority among the desert warriors, much as they still are today. Moreover, the extraordinary detail of some of the rock art paintings has provided inestimable help in understanding how (and why) camels were ridden in the 1st millennium AD. Unlike horses, donkeys or mules, one-humped camels present a major problem for riders: where to put the saddle. Although it might be assumed that the saddle should be placed over the hump, they can, in fact, also be positioned behind or in front of the hump, depending on the activity. It seems that the first saddles were placed behind the hump, but that position was unsuitable for fighting, quite uncomfortable, and unstable. Subsequently, a new saddle was invented in North Arabia around the 5th century BC: a framework of wood that rested over the hump and provided a stable platform on which to ride and fight more effectively. The North Arabian saddle led to a revolution in the domestication of one-humped camels, allowed a faster expansion of the use of these animals, and it is probably still the most used type of saddle today. - sys: id: 6dOm7ewqmA6oaM4cK4cy8c created_at: !ruby/object:DateTime 2015-11-26 16:14:25.900000000 Z updated_at: !ruby/object:DateTime 2018-05-17 15:31:33.078000000 Z content_type_id: image revision: 2 image: sys: id: 5qXuQrcnUQKm0qCqoCkuGI created_at: !ruby/object:DateTime 2015-11-26 16:06:48.345000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:06:48.345000000 Z title: As1974,29.17 description: url: "//images.ctfassets.net/xt8ne4gbbocd/5qXuQrcnUQKm0qCqoCkuGI/2b279eff2a6f42121ab0f6519d694a92/As1974_29.17.jpg" caption: North Arabian-style saddle, with a wooden framework designed to be put around the hump. Jordan. British Museum As1974,29.17 © Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3320111&partId=1&object=23696&page=1 - sys: id: 5jE9BeKCBUEK8Igg8kCkUO created_at: !ruby/object:DateTime 2015-11-26 16:21:27.156000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:21:27.156000000 Z content_type_id: chapter revision: 1 title_internal: 'Camels: thematic, chapter 7' body: 'Although North Arabian saddles are found throughout North Africa and are often depicted in rock art paintings, at some point a new kind of saddle was designed in North Africa: one placed in front of the hump, with the weight over the shoulders of the camel. This type of shoulder saddle allows the rider to control the camel with the feet and legs, thus improving the ride. Moreover, the rider is seated in a lower position and thus needs shorter spears and swords that can be brandished more easily, making warriors more efficient. This new kind of saddle, which is still used throughout North Africa today, appears only in the western half of the Sahara and is well represented in the rock art of Algeria, Niger and Mauritania. And it is not only saddles that are recognizable in Saharan rock art: harnesses, reins, whips or blankets are identifiable in the paintings and show astonishing similarities to those still used today by desert peoples.' - sys: id: 6yZaDQMr1Sc0sWgOG6MGQ8 created_at: !ruby/object:DateTime 2015-11-26 16:14:46.560000000 Z updated_at: !ruby/object:DateTime 2018-05-17 15:33:25.754000000 Z content_type_id: image revision: 2 image: sys: id: 40zIycUaTuIG06mgyaE20K created_at: !ruby/object:DateTime 2015-11-26 16:07:51.466000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:51.466000000 Z title: Fig. 10. Painting description: url: "//images.ctfassets.net/xt8ne4gbbocd/40zIycUaTuIG06mgyaE20K/1736927ffb5e2fc71d1f1ab04310a73f/Fig._10._Painting.jpg" caption: Painting of rider on a one-humped camel. Note the North Arabian saddle on the hump, similar to the example from Jordan above. Terkei, Ennedi plateau, Chad. 2013,2034.6568 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3640623&partId=1&searchText=2013,2034.6568&page=1 - sys: id: 5jHyVlfWXugI2acowekUGg created_at: !ruby/object:DateTime 2015-11-26 16:15:13.926000000 Z updated_at: !ruby/object:DateTime 2018-05-17 15:36:07.603000000 Z content_type_id: image revision: 2 image: sys: id: 6EvwTsiMO4qoiIY4gGCgIK created_at: !ruby/object:DateTime 2015-11-26 16:07:34.249000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:34.249000000 Z title: '2013,2034.4471' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6EvwTsiMO4qoiIY4gGCgIK/1db47ae083ff605b9533898d9d9fb10d/2013_2034.4471.jpg" caption: Camel-rider using a North African saddle (in front of the hump), surrounded by warriors with spears and swords, with Libyan-Berber graffiti. <NAME>, <NAME>. 2013,2034.4471 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3602860&partId=1&museumno=2013,2034.4471&page=1 - sys: id: 57goC8PzUs6G4UqeG0AgmW created_at: !ruby/object:DateTime 2015-11-26 16:16:51.920000000 Z updated_at: !ruby/object:DateTime 2019-02-12 02:33:53.275000000 Z content_type_id: image revision: 3 image: sys: id: 5JDO7LrdKMcSEOMEG8qsS8 created_at: !ruby/object:DateTime 2015-11-26 16:07:34.250000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:34.250000000 Z title: Fig. 12. Tuaregs description: url: "//images.ctfassets.net/xt8ne4gbbocd/5JDO7LrdKMcSEOMEG8qsS8/76cbecd637724d549db8a7a101553280/Fig._12._Tuaregs.jpg" caption: Tuaregs at Cura Salee, an annual meeting of desert peoples. Note the saddles in front of the hump and the camels' harnesses, similar to the rock paintings above such as the image from Terkei. Ingal, Northern Niger. 2013,2034.10523 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3652377&partId=1&searchText=2013,2034.10523&page=1 - sys: id: 3QPr46gQP6sQWswuSA2wog created_at: !ruby/object:DateTime 2015-11-26 16:21:50.767000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:21:50.767000000 Z content_type_id: chapter revision: 1 title_internal: 'Camels: thematic, chapter 8' body: Since their introduction to the Sahara during the first centuries of the Christian era, camels have become indispensable for desert communities, providing a method of transport for people and commodities, but also for their milk, meat and hair for weaving. They allowed the improvement of wide cultural and economic networks, transforming the Sahara into a key node linking the Mediterranean Sea with Sub-Saharan Africa. A symbol of wealth and prestige, the Libyan-Berber peoples recognized camels’ importance and expressed it through paintings and engravings across the desert, leaving a wonderful document of their societies. The painted images of camel-riders crossing the desert not only have an evocative presence, they are also perfect snapshots of a history that started two thousand years ago and seems as eternal as the Sahara. - sys: id: 54fiYzKXEQw0ggSyo0mk44 created_at: !ruby/object:DateTime 2015-11-26 16:17:13.884000000 Z updated_at: !ruby/object:DateTime 2018-05-17 16:01:13.379000000 Z content_type_id: image revision: 2 image: sys: id: 3idPZkkIKAOWCiKouQ8c8i created_at: !ruby/object:DateTime 2015-11-26 16:07:34.244000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:34.244000000 Z title: Fig. 13. Camel-riders description: url: "//images.ctfassets.net/xt8ne4gbbocd/3idPZkkIKAOWCiKouQ8c8i/4527b1eebe112ef9c38da1026e7540b3/Fig._13._Camel-riders.jpg" caption: Camel-riders galloping. Butress cave, <NAME>, Chad. 2013,2034.6077 ©<NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3637992&partId=1&searchText=2013,2034.6077&page=1 - sys: id: 1ymik3z5wMUEway6omqKQy created_at: !ruby/object:DateTime 2015-11-26 16:17:32.501000000 Z updated_at: !ruby/object:DateTime 2018-05-17 16:02:41.679000000 Z content_type_id: image revision: 2 image: sys: id: 4Y85f5QkVGQiuYEaA2OSUC created_at: !ruby/object:DateTime 2015-11-26 16:07:06.194000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:06.194000000 Z title: Fig. 14. Tuareg description: url: "//images.ctfassets.net/xt8ne4gbbocd/4Y85f5QkVGQiuYEaA2OSUC/4fbca027ed170b221daefdff0ae7d754/Fig._14._Tuareg.jpg" caption: Tuareg rider galloping at the Cure Salee meeting. Ingal, northern Niger. 2013,2034.10528 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3652371&partId=1&searchText=2013,2034.10528&page=1 background_images: - sys: id: 3mhr7uvrpesmaUeI4Aiwau created_at: !ruby/object:DateTime 2015-12-07 18:13:48.396000000 Z updated_at: !ruby/object:DateTime 2015-12-07 18:13:48.396000000 Z title: CHAENP0340003 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3mhr7uvrpesmaUeI4Aiwau/65c691f09cd60bb7aa08457e18eaa624/CHAENP0340003_1_.JPG" - sys: id: BPzulf3QNqMC4Iqs4EoCG created_at: !ruby/object:DateTime 2015-12-07 18:13:31.094000000 Z updated_at: !ruby/object:DateTime 2015-12-07 18:13:31.094000000 Z title: CHAENP0340001 description: url: "//images.ctfassets.net/xt8ne4gbbocd/BPzulf3QNqMC4Iqs4EoCG/356b921099bfccf59008b69060d20d75/CHAENP0340001_1_.JPG" country_introduction: sys: id: 3dMpIo4d4cQa2OI4me2ACQ created_at: !ruby/object:DateTime 2015-11-26 11:15:52.509000000 Z updated_at: !ruby/object:DateTime 2015-12-08 14:55:14.724000000 Z content_type_id: country_information revision: 4 title: 'Niger: country introduction' chapters: - sys: id: 1edWsVTqzcciiIAUaqYoG created_at: !ruby/object:DateTime 2015-11-26 11:03:04.104000000 Z updated_at: !ruby/object:DateTime 2017-01-09 16:49:15.950000000 Z content_type_id: chapter revision: 2 title: Introduction title_internal: 'Niger: country, chapter 1' body: Niger is geographically diverse, having both the Sahel (savannah) and the Sahara (desert). The majority of the country’s rock art – made up predominantly of engravings – is located in the northern desert area, in and around the Aïr Mountains, where some of the art is thought to be several thousand years old. The Djado Plateau in the north-east is also rich in art that includes both paintings and engravings. One of the most celebrated sites of rock engraving is at a place called Dabous, to the west of the mountains. Here, two life-size giraffe were carved on the top of an outcrop, and may be up to 6,000 years old. Other notable areas for engravings are Iwellene in the northern Aïr Mountains, where some of the art is thought to be several thousand years old, as well the sites of Tanakom and Tagueit in the south-eastern Aïr Mountains, where engravings are located on the sides of two wadis (dry riverbeds). - sys: id: 1E25PiKMde8CE8MgQIukKK created_at: !ruby/object:DateTime 2015-11-26 10:55:02.416000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:55:02.416000000 Z content_type_id: image revision: 1 image: sys: id: 2FAYj7hG88aQ0Quq6Wc6gE created_at: !ruby/object:DateTime 2015-11-26 10:54:16.151000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:54:16.151000000 Z title: '2013,2034.9967' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2FAYj7hG88aQ0Quq6Wc6gE/49ae0722057f453db4bb15da9c1ee6c0/2013_2034.9967.jpg" caption: Block-pecked engraving of running hare. 2013,2034.9967 © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3637684&partId=1&page=1 - sys: id: 1WQHiGltOAqm4oAc46YAme created_at: !ruby/object:DateTime 2015-11-26 11:03:35.303000000 Z updated_at: !ruby/object:DateTime 2015-11-26 11:03:35.303000000 Z content_type_id: chapter revision: 1 title_internal: 'Niger: country, chapter 2' body: Links have been made between the rock art of Niger and that of several other countries – in particular, between the so-called Libyan Warrior art found in the Aïr Mountains and the rock engravings of the Adrar des Iforas in Mali. Stylistic similarities also exist with some of the art of the Tadrart (Acacus) and in south-east Algeria. Further associations have been made between the Early Hunter art of the Djado Plateau and art in south-west Libya and south-east Algeria. Equally, similarities have been observed with the Tazina-style engravings in south-western Algeria and south-eastern Morocco. - sys: id: 5bPNREZcAMsO8SuecSaoQy created_at: !ruby/object:DateTime 2015-11-26 10:55:34.135000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:55:34.135000000 Z content_type_id: image revision: 1 image: sys: id: 4h5Sa7Ex2M2aEa8YSGW6iU created_at: !ruby/object:DateTime 2015-11-26 10:53:55.744000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:53:55.744000000 Z title: '2013,2034.8958' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4h5Sa7Ex2M2aEa8YSGW6iU/b394694db95c753013248a8e398017d4/2013_2034.8958.jpg" caption: Looking out of a shallow cave, Djado Plateau, Niger. 2013,2034.8958 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3637696&partId=1&page=1 - sys: id: 3OeKLV88XSow8C0iOKcqIg created_at: !ruby/object:DateTime 2015-11-26 11:04:29.851000000 Z updated_at: !ruby/object:DateTime 2015-12-07 17:12:48.554000000 Z content_type_id: chapter revision: 6 title: Geography and rock art distribution title_internal: 'Niger: country, chapter 3' body: "Covering an area of 1.267 million km², this landlocked country borders seven others. Its south-western borders flank the Niger River, with Burkina Faso, Benin and Nigeria to the south; its north-eastern borders touch the borders of Algeria, Libya and Chad in the central Sahara, and Mali to the west. The climate is mainly hot and dry with much of the country covered by the Sahara desert. In the extreme south, on the edges of the Sahel, the terrain is mainly shrub savannah.\n\nUnlike other regions in northern Africa, in the absence of a generally agreed chronology, scholars have categorised the rock art of Niger regionally and stylistically, making connections where possible with rock art of other regions. The rock art of Niger can be broadly divided into the following regions: \n" - sys: id: 516un196R2QI8MKOSMA6mW created_at: !ruby/object:DateTime 2015-12-07 17:13:15.478000000 Z updated_at: !ruby/object:DateTime 2015-12-07 17:13:15.478000000 Z content_type_id: chapter revision: 1 title_internal: Sub heading 1 body: '__Aïr Mountains (northern Niger)__ ' - sys: id: 57o3riQZdC2CE4IOSgoOke created_at: !ruby/object:DateTime 2015-11-26 10:56:09.992000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:56:09.992000000 Z content_type_id: image revision: 1 image: sys: id: 6wKZcUGktaAG0IYOagAIQ4 created_at: !ruby/object:DateTime 2015-11-26 10:54:26.849000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:54:26.849000000 Z title: '2013,2034.11147' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6wKZcUGktaAG0IYOagAIQ4/9ddabc2eb10161fcb2c69cff6817741a/2013_2034.11147.jpg" caption: Libyan Warrior figure, Western Aïr Mountains, Niger. 2013,2034.11147 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3637713&partId=1&museumno=2013,2034.11147&page=1 - sys: id: 5p9XKG2DjakmUkWuq6AuIK created_at: !ruby/object:DateTime 2015-11-26 11:05:00.923000000 Z updated_at: !ruby/object:DateTime 2015-12-08 14:54:12.049000000 Z content_type_id: chapter revision: 2 title_internal: 'Niger: country, chapter 4' body: Consisting predominantly of engravings, the majority of depictions in this region fall within the so-called Libyan Warrior period or style of art, dating from 1,500–3,000 years ago, characterised by forward-facing figures with metal weapons and horses. Approximately 1,000 engravings of warriors have been recorded from the Aïr Mountains in Niger, as well as the Adrar des Iforas in bordering Mali. Based on investigations into the garments worn, accessories, headdresses and weaponry, and by studying the placement and superimposition of images, it has been proposed that there are two main stages of this Libyan Warrior rock art. The oldest is linked to a pastoral economy based on cattle-rearing, when metal had been introduced to the region and the use of the spear took over from the traditional bow. This region also hosts images of wild animals such as Barbary sheep and ostrich, as well as cattle. - sys: id: 61yqtntiEMEgWW8iAAa4Ao created_at: !ruby/object:DateTime 2015-12-08 14:54:32.334000000 Z updated_at: !ruby/object:DateTime 2015-12-08 14:54:48.031000000 Z content_type_id: chapter revision: 2 title_internal: Sub heading 2 body: __Djado Plateau__ - sys: id: Kjmi6uh5U2aGEuI0ggoEw created_at: !ruby/object:DateTime 2015-11-26 10:56:33.929000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:56:33.929000000 Z content_type_id: image revision: 1 image: sys: id: 6yxgQFojbUcOUSwyaWwEMC created_at: !ruby/object:DateTime 2015-11-26 10:54:27.057000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:54:03.540000000 Z title: '2013,2034.8891' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3637764&partId=1&searchText=2013,2034.8891&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/6yxgQFojbUcOUSwyaWwEMC/5547eadfdf388937a8c708c145c2dba6/2013_2034.8891.jpg" caption: Two outline engravings of white rhinoceros. 2013,2034.8891 © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3637764&partId=1&museumno=2013,2034.8891&page=1 - sys: id: olpDz3t6DeY0qgiiCeIq created_at: !ruby/object:DateTime 2015-11-26 11:05:22.441000000 Z updated_at: !ruby/object:DateTime 2015-11-26 11:05:22.441000000 Z content_type_id: chapter revision: 1 title_internal: 'Niger: country, chapter 5' body: Here, both paintings and engravings occur. The earliest engravings include images of wild animals such as elephants, rhinoceros, giraffe and other game, and dated to the Early Hunter or Bubalus Period; human figures are very rare. Tazina-style engravings – similar to those found in south-eastern Morocco – also occur, as well as polychrome fine-line and finger paintings that are unique to this area. - sys: id: 5F6G6OVWSI4UOWmaq0ocqS created_at: !ruby/object:DateTime 2015-11-26 10:57:18.063000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:57:18.063000000 Z content_type_id: image revision: 1 image: sys: id: 2ANvzNqFfiKkMWAAsWCWKQ created_at: !ruby/object:DateTime 2015-11-26 10:54:26.916000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:54:26.916000000 Z title: '2013,2034.8960' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2ANvzNqFfiKkMWAAsWCWKQ/724f5a5d07a365fdf3b9040aa30d916c/2013_2034.8960.jpg" caption: White cows with calves and three figures. Djado Plateau, Niger. 2013,2034.8960 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3637694&partId=1&museumno=2013,2034.8960&page=1 - sys: id: 3qTgmBHVQc48E4WUuQgkGM created_at: !ruby/object:DateTime 2015-11-26 11:05:56.545000000 Z updated_at: !ruby/object:DateTime 2015-11-26 11:05:56.545000000 Z content_type_id: chapter revision: 1 title_internal: 'Niger: country, chapter 6' body: The number of cattle depictions is small, but particular images of calves attached to a lead can be compared stylistically with images of cattle in Tassili n’Ajjer, Algeria. Moreover, <NAME> noted the resemblance between these rock art depictions and the husbandry practices of the present day Wodaabe people of Niger, who use a similar calf rope. The calf rope (a long rope comprising loops within which the heads of the calves are secured) is both practical and symbolic, ensuring the cows always return to their home camp, while also physically dividing the camp into male and female halves. It is interesting to note the close relationship between the rock art of regions that today are politically discrete. - sys: id: dGrDTSq3Xqm06eis6sUkU created_at: !ruby/object:DateTime 2015-11-26 11:06:48.293000000 Z updated_at: !ruby/object:DateTime 2015-11-26 11:06:48.293000000 Z content_type_id: chapter revision: 1 title: History of rock art discovery in Niger title_internal: 'Niger: country, chapter 7' body: Until relatively recently rock art research has been sporadic in Niger. In the 1920s Major Gen. <NAME>, a British explorer and army officer, made two great expeditions into the Sahara. He was the first person to make a serious study of the Tuareg and documented some of the rock art in the Aïr Mountains. Subsequently, French colonial officers noted some sites around 1960. However, it was French archaeologist Henri Lhote who undertook major recording programmes throughout the 1960s and 1970s to document, trace and publish several thousand engravings. Very little information is known relating the rock art to known cultural groups, either past or present. Most of the sites were not habitation sites, and were probably only occasionally visited by nomadic societies in the past, so very little (if any) archaeological evidence remains. Most of the art predates the residence of the Tuareg, who now inhabit this area and who appear to have no direct connections with the art. The Tuareg recognise old script which sometimes accompanies images as it closely resembles their own writing, *Tifinagh*; however, it is incomprehensible to them if it is more than 100 years old. - sys: id: 2dnMaAI1RyUiEgWiY8SEsS created_at: !ruby/object:DateTime 2015-11-26 10:57:51.550000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:57:51.550000000 Z content_type_id: image revision: 1 image: sys: id: 5OBSH7pvt6I6eOAc4OaqEG created_at: !ruby/object:DateTime 2015-11-26 10:54:26.945000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:54:26.945000000 Z title: '2013,2034.10009' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5OBSH7pvt6I6eOAc4OaqEG/f667bce1cf4cf3c6dbce0bb5a83383bc/2013_2034.10009.jpg" caption: Large reground and painted figure surrounded by ancient Tifinagh script. Northern Air Mountains, Niger. 2013,2034.10009 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3637714&partId=1&museumno=2013,2034.10009&page=1 - sys: id: 37Cl8z71uMqYsoeyqyOegs created_at: !ruby/object:DateTime 2015-11-26 11:07:24.753000000 Z updated_at: !ruby/object:DateTime 2015-11-26 11:07:24.753000000 Z content_type_id: chapter revision: 1 title: Chronology title_internal: 'Niger: country, chapter 8' body: 'The relative chronology for rock art in Niger can be based, as in other Saharan regions, on stylistic classifications:' - sys: id: uNjAW1yrkW6iyE0iqcsQy created_at: !ruby/object:DateTime 2015-11-26 10:58:19.111000000 Z updated_at: !ruby/object:DateTime 2017-01-09 16:51:42.139000000 Z content_type_id: image revision: 2 image: sys: id: 1vncvc4BCIG8ymWeS8c28q created_at: !ruby/object:DateTime 2015-11-26 10:54:27.168000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:54:27.168000000 Z title: '2013,2034.9910' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1vncvc4BCIG8ymWeS8c28q/ee518eb244c2193ea827c7875b30c049/2013_2034.9910.jpg" caption: Block-pecked elephant. Northern Aïr Mountains, Niger. 2013,2034.9910 © TARA/<NAME> col_link: http://bit.ly/2iVcmsb - sys: id: 31SOSm8z04CU4MouUSUSQe created_at: !ruby/object:DateTime 2015-11-26 11:07:44.432000000 Z updated_at: !ruby/object:DateTime 2017-01-09 16:53:27.619000000 Z content_type_id: chapter revision: 2 title_internal: 'Niger: country, chapter 9' body: Early Hunter or Bubalus Period rock engravings are executed with deeply incised and smoothened lines, mainly depicting big game such as elephants, rhinoceros, giraffe and other game (with rhinoceros occurring most often), and are found on the Djado Plateau, as well as the Mangueni and Tchigai plateaux in north-east Niger. In the eastern Aïr Mountains, archaeological traces of human occupation during this early wet phase are evident, dating back 9,500 years. - sys: id: 2HafBWCAcMOYykSgSywEK6 created_at: !ruby/object:DateTime 2015-11-26 10:58:42.964000000 Z updated_at: !ruby/object:DateTime 2017-01-09 16:54:59.579000000 Z content_type_id: image revision: 2 image: sys: id: 2lW3L3iwz60ekeWsYKgOYC created_at: !ruby/object:DateTime 2015-11-26 10:54:26.852000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:53:07.945000000 Z title: '2013,2034.9786' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3637692 url: "//images.ctfassets.net/xt8ne4gbbocd/2lW3L3iwz60ekeWsYKgOYC/c303352ed0b0976a3f1508ea30b8a41d/2013_2034.9786.jpg" caption: Outline and decorated cattle, some with elaborate deliberately turned-back horns. 2013,2034.9786 © TARA/<NAME> col_link: http://bit.ly/2jlwIKc - sys: id: 2lLu5BCrhuiWA0eOUSkQYo created_at: !ruby/object:DateTime 2015-11-26 11:08:13.631000000 Z updated_at: !ruby/object:DateTime 2015-11-26 11:08:13.631000000 Z content_type_id: chapter revision: 1 title_internal: 'Niger: country, chapter 10' body: Although the Bovidian Period is sparsely represented in comparison to other rock art regions, both on the Djado Plateau and the Aïr Mountains, this period can probably be dated to between 7,000 and 4,000 years ago. A few cattle are depicted in a similar fashion to the big game of the Early Hunter Period, which raises the question of whether the nomadic cattle-herding culture emerged from a hunting lifestyle, or at least rapidly succeeded it. - sys: id: 6JJPeizRe0WiQIc2yOEaIY created_at: !ruby/object:DateTime 2015-11-26 10:59:13.005000000 Z updated_at: !ruby/object:DateTime 2017-01-09 17:03:18.580000000 Z content_type_id: image revision: 2 image: sys: id: 3nBXTYYPN6ucuaImm24iuG created_at: !ruby/object:DateTime 2015-11-26 10:54:30.823000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:54:30.823000000 Z title: '2013,2034.8834' description: url: "//images.ctfassets.net/xt8ne4gbbocd/3nBXTYYPN6ucuaImm24iuG/a188d0ae5e00e8934acbf0397ce50194/2013_2034.8834.jpg" caption: Outline Tazina-style engraving of a giraffe. 2013,2034.8834 © TARA/David Coulson col_link: http://bit.ly/2i9uPQ2 - sys: id: 6lPfzlhbskGkAcU6eiEuIQ created_at: !ruby/object:DateTime 2015-11-26 11:08:30.254000000 Z updated_at: !ruby/object:DateTime 2015-11-26 11:08:30.254000000 Z content_type_id: chapter revision: 1 title_internal: 'Niger: country, chapter 11' body: Engravings in the Tazina style are found on the Djado Plateau and have been likened to those in south-eastern Morocco. While dates in Niger are not generally agreed, the Tazina period in Morocco is dated from c.5,000–2,000 BC. - sys: id: 5cO6JFSdgQgQMIK8egwYwA created_at: !ruby/object:DateTime 2015-11-26 10:59:45.306000000 Z updated_at: !ruby/object:DateTime 2017-01-09 17:04:32.984000000 Z content_type_id: image revision: 2 image: sys: id: 2wvcOF7LOQa6iEsWyQOUQi created_at: !ruby/object:DateTime 2015-11-26 10:54:26.797000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:54:26.797000000 Z title: '2013,2034.9875' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2wvcOF7LOQa6iEsWyQOUQi/ba1af764bd58d195ef002f58cca5eb51/2013_2034.9875.jpg" caption: Libyan Warrior-style figures. Northern Aïr Mountains, Niger. 2013,2034.9875 © TARA/<NAME> col_link: http://bit.ly/2i6usdB - sys: id: 5s0XmNAWWIwwQ2m8q88AWe created_at: !ruby/object:DateTime 2015-11-26 11:00:12.745000000 Z updated_at: !ruby/object:DateTime 2017-01-09 17:05:53.718000000 Z content_type_id: image revision: 2 image: sys: id: 4fSRLSsTP2MCiquKAEsmkQ created_at: !ruby/object:DateTime 2015-11-26 10:54:26.833000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:54:26.833000000 Z title: '2013,2034.9430' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4fSRLSsTP2MCiquKAEsmkQ/ad620450f16447bcbb6e734d2a4c1c0e/2013_2034.9430.jpg" caption: Two horses attached to two-wheeled chariot with charioteer. Eastern Aïr Mountains, Niger. 2013,2034.9430 © TARA/<NAME> col_link: http://bit.ly/2i6uJ07 - sys: id: 5lN8CVda2AG6QAaeyI20O8 created_at: !ruby/object:DateTime 2015-11-26 11:08:51.981000000 Z updated_at: !ruby/object:DateTime 2015-12-08 14:57:22.081000000 Z content_type_id: chapter revision: 2 title_internal: 'Niger: country, chapter 12' body: Consisting predominantly of rock engravings and found in the Aïr Mountains, the Horse Period and Libyan Warrior Period date from around 3,000–1,500 years ago. Depictions are of horses with so-called Libyan Warriors, with metal weapons or with chariots and charioteers. Human figures, which often appear with horses, were sometimes depicted with elaborate apparel; others were drawn with stylized bodies consisting of two triangles joined at the apex. Wild animals such as Barbary sheep and ostrich, as well as cattle, appear in this art. Art of the Horse Period is not widely represented in the Djado Plateau, suggesting that Berber groups did not reach the region in any great numbers – but it has been proposed that certain peculiarities of style may suggest an influence from Aïr. - sys: id: IVnNUsnIeAcAiM42imyI4 created_at: !ruby/object:DateTime 2015-11-26 11:00:38.006000000 Z updated_at: !ruby/object:DateTime 2017-01-09 17:06:56.071000000 Z content_type_id: image revision: 2 image: sys: id: 2bO7Zt5qJ6UI088i422mMe created_at: !ruby/object:DateTime 2015-11-26 10:53:55.796000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:53:55.796000000 Z title: '2013,2034.9578' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2bO7Zt5qJ6UI088i422mMe/337784cf715978325ffb7bda8179c3ce/2013_2034.9578.jpg" caption: Crudely pecked camels. Eastern Aïr Mountains, Niger. 2013,2034.9578 © TARA/<NAME> col_link: http://bit.ly/2i9tto4 - sys: id: ZjY1WlFDm8uM2oycKygUa created_at: !ruby/object:DateTime 2015-11-26 11:09:10.217000000 Z updated_at: !ruby/object:DateTime 2015-11-26 11:09:10.217000000 Z content_type_id: chapter revision: 1 title_internal: 'Niger: country, chapter 13' body: A small number of engravings from the Camel Period occur on the Djado Plateau, but as camels were introduced to the Sahara up to 2,000 years ago, the relative lack of depictions suggests that the plateau was scarcely frequented during this hyper-arid period. citations: - sys: id: 23N5waXqbei8UswAuiGa8g created_at: !ruby/object:DateTime 2015-11-26 11:02:17.186000000 Z updated_at: !ruby/object:DateTime 2015-11-26 11:02:17.186000000 Z content_type_id: citation revision: 1 citation_line: |- <NAME>. ‘Sub-zone 3: Niger’, in *Rock art of Sahara and North Africa: Thematic study*. [ICOMOS](http://www.icomos.org/en/116-english-categories/resources/publications/222-rock-art-of-sahara-and-north-africa-thematic-study). <NAME>. 2003. ‘One Hundred Years of Archaeology in Niger’, *Journal of World Prehistory*, Vol. 17, No. 2, pp. 181-234 Muzzolini, Alfred.2001. ‘Saharan Africa’, in D.S. Whitley (ed.) *Handbook of Rock Art Research*. Walnut Creek, California: AltaMira Press, pp.605-636. Striedter, <NAME>.1993. ‘Rock Art research on the Djado Plateau (Niger): a Preliminary Report n Arkana’, in *Rock Art in the Old World*. Walnut Creek, (ed. Michel Lorblanchet). New Delhi: Indira Ghandi National Centre for the Arts, pp.113-128 background_images: - sys: id: 1vncvc4BCIG8ymWeS8c28q created_at: !ruby/object:DateTime 2015-11-26 10:54:27.168000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:54:27.168000000 Z title: '2013,2034.9910' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1vncvc4BCIG8ymWeS8c28q/ee518eb244c2193ea827c7875b30c049/2013_2034.9910.jpg" - sys: id: 4EatwZfN72waIquQqWEeOs created_at: !ruby/object:DateTime 2015-11-26 17:51:43.121000000 Z updated_at: !ruby/object:DateTime 2015-11-26 17:51:43.121000000 Z title: '2013,2034.11147' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4EatwZfN72waIquQqWEeOs/d793f6266f2ff486e0e99256c2c0ca39/2013_2034.11147.jpg" - sys: id: 2wvcOF7LOQa6iEsWyQOUQi created_at: !ruby/object:DateTime 2015-11-26 10:54:26.797000000 Z updated_at: !ruby/object:DateTime 2015-11-26 10:54:26.797000000 Z title: '2013,2034.9875' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2wvcOF7LOQa6iEsWyQOUQi/ba1af764bd58d195ef002f58cca5eb51/2013_2034.9875.jpg" region: Northern / Saharan Africa ---<file_sep>/_coll_country_information/mauritania-country-introduction.md --- contentful: sys: id: 5uLhtUXIeA0kma8usA44eM created_at: !ruby/object:DateTime 2015-11-26 13:13:33.481000000 Z updated_at: !ruby/object:DateTime 2015-12-07 13:40:48.819000000 Z content_type_id: country_information revision: 2 title: 'Mauritania: country introduction' chapters: - sys: id: 7ZVEMUYkGAcAwIGQ2aYiu created_at: !ruby/object:DateTime 2015-11-26 13:03:29.927000000 Z updated_at: !ruby/object:DateTime 2015-11-26 13:03:29.927000000 Z content_type_id: chapter revision: 1 title: Introduction title_internal: 'Mauritania: country, chapter 1' body: Mauritania is one of Africa’s westernmost countries, stretching over 1,000 km inland from the Atlantic coast into the Sahara. Mauritania’s corpus of rock art is extensive and mostly appears to have been produced within the last 4,000 years. - sys: id: 6rGE0FRNFmqKCEwOOy2sEg created_at: !ruby/object:DateTime 2015-11-26 12:53:11.539000000 Z updated_at: !ruby/object:DateTime 2017-01-09 16:41:03.423000000 Z content_type_id: image revision: 2 image: sys: id: 6a9PIc2PD2GoSys6umKim created_at: !ruby/object:DateTime 2015-11-26 12:50:25.597000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:15:13.181000000 Z title: '2013,2034.12277' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3645968&partId=1&searchText=2013,2034.12277&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/6a9PIc2PD2GoSys6umKim/df4fd71d342462545f28c306a798de62/2013_2034.12277.jpg" caption: Painted horses, riders and standing human figure. <NAME> Garbi, Mauritania. 2013,2034.12277 © TARA/<NAME> col_link: http://bit.ly/2iaQquq - sys: id: 6BfTuIwDOEMoiw6AUYSiYm created_at: !ruby/object:DateTime 2015-11-26 13:04:41.054000000 Z updated_at: !ruby/object:DateTime 2017-01-09 16:41:57.874000000 Z content_type_id: chapter revision: 2 title: Geography and rock art distribution title_internal: 'Mauritania: country, chapter 2' body: |- In total Mauritania covers about 1,030,700 km², most of which forms part of the western portion of the Sahara desert. The southern part of Mauritania incorporates some of the more temperate Sahelian zone, forming part of the geographical and cultural border between Saharan and Sub-Saharan Africa. The landscape of the country is generally characterised by its flatness, but the two major neighbouring plateaux in the East-Centre of the country – the Tagant in the South and the Adrar further North – are furnished with rock shelters, boulders and other surfaces upon which can be found abundant rock art, more often engraved than painted. The principal concentrations of rock art in Mauritania are located in these two areas, as well as in the North around Bir Moghreïn (in the Mauritanian extension of the Zemmur mountains), the Hank ridge near the borders of Algeria and Mali and the Tichitt-Walata area to the east of the Tagant plateau. __Adrar__ There are about thirty known rock art sites in the Adrar region, although, as with most Mauritanian rock art, study has not been comprehensive and there may be many more as yet undocumented. Engraved rock art sites dominate along the northern edge of the massif, with some of the most significant to be found at the sites of El Beyyed and El Ghallaouiya. Rarer paintings of cattle are also to be found at El Ghallaouiya, as well as at the site of Amogjar. __Tagant__ Less well studied than Adrar, the Tagant plateau contains several painting sites showing horses and riders such as those at the sites of Agneitir Dalma and Tinchmart. The archaeologically significant area of the Tichitt-Walata ridge, a chain of escarpments known for its Neolithic settlements, is largely located within the wider Tagant region to the east of the plateau, and also features many engravings and some paintings. - sys: id: 1xRX7rqW0s4Wo0ewQCUGWu created_at: !ruby/object:DateTime 2015-11-26 13:05:22.127000000 Z updated_at: !ruby/object:DateTime 2015-11-26 13:05:22.127000000 Z content_type_id: chapter revision: 1 title: Research history title_internal: 'Mauritania: country, chapter 3' body: |- Recording and research on Mauritanian rock art has been limited in comparison with other Saharan rock art traditions, and has mainly been undertaken by French scholars, as Mauritania was formerly part of French West Africa. The first major publications cataloguing rock art sites in the country were those of Théodore Monod (1937-8), based on recordings collected on expeditions made between 1934 and 1936 and covering the entire western Saharan region. Following this, the explorers <NAME> and <NAME>uigaudeau published some paintings of the Tagant region in1939. A more comprehensive study of the paintings, engravings and inscriptions of West and North West Africa was made by <NAME> (1954), and emphasised the importance of systematically recording and studying the images in their contexts. More recently (1993), <NAME> produced a synthesis of known Mauritanian rock art in his *Préhistoire de la Mauritanie*. Many individual Mauritanian rock art sites have also been recorded and published over the decades since the 1940s, particularly in the context of associated archaeological sites, such as those at Tegdaoust and in the Tichitt-Walata region. - sys: id: 66wyHEf39KoaOmm4YA8ko created_at: !ruby/object:DateTime 2015-11-26 12:53:57.337000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:53:57.337000000 Z content_type_id: image revision: 1 image: sys: id: 4lA1J5Jly0MSImIsQ2GwUo created_at: !ruby/object:DateTime 2015-11-26 12:50:25.581000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:50:25.581000000 Z title: '2013,2034.2312' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4lA1J5Jly0MSImIsQ2GwUo/91ed83183f46bedf859da6b1fb5ffcaa/2013_2034.2312.jpg" caption: 'Painted geometric circle design, <NAME>, <NAME>, Mauritania. 2013,2034.2312 © TARA/<NAME> ' col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3618068&partId=1&searchText=2013,2034.2312&page=1 - sys: id: 3Lde3TfwY8aWu26K84weUa created_at: !ruby/object:DateTime 2015-11-26 13:05:45.305000000 Z updated_at: !ruby/object:DateTime 2015-11-26 13:05:45.305000000 Z content_type_id: chapter revision: 1 title: Themes title_internal: 'Mauritania: country, chapter 4' body: |- The range of subject matter in the rock art of Mauritania is similar to that of other Saharan countries, consisting primarily of images of domestic cattle, along with those of horses both mounted and unmounted, human figures and weaponry, wild fauna, hunting scenes, camels and Libyco-Berber/Tifinagh and Arabic script. Images of goats and sheep are extremely rare. Some general geographic tendencies in style and type can be made out, for example, deeply cut and polished naturalistic engravings of large wild animals are concentrated in the North of the country. There is an apparent North-South divide in engraving style, with images becoming more schematic further south. Rarer painting sites are clustered in certain areas such as north of Bir Moghreïn in the far north, and certain Adrar sites, with horse and rider paintings most common in the Tagant and Tichitt-Walata regions. - sys: id: AHzKqrsBricmEQwCmOYyQ created_at: !ruby/object:DateTime 2015-11-26 12:54:38.583000000 Z updated_at: !ruby/object:DateTime 2018-09-17 18:03:32.564000000 Z content_type_id: image revision: 2 image: sys: id: 5u1VecbrbOq4cCICyqiOAw created_at: !ruby/object:DateTime 2015-11-26 12:50:25.656000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:20:04.418000000 Z title: '2013,2034.12427' description: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3646352&partId=1&searchText=2013,2034.12427&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/5u1VecbrbOq4cCICyqiOAw/c4223338beae42378b3c34f8ab1b5a8e/2013_2034.12421.jpg" caption: Painted heads of antelope facing left, Guilemsi, Tadrart, Mauritania. 2013,2034.12427 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3646352&partId=1&searchText=2013,2034.12427&page=1 - sys: id: 4itpl0jzpKAqkcCa6yKqa6 created_at: !ruby/object:DateTime 2015-11-26 13:06:05.325000000 Z updated_at: !ruby/object:DateTime 2015-11-26 13:06:05.325000000 Z content_type_id: chapter revision: 1 title_internal: 'Mauritania: country, chapter 5' body: |- Mauritanian rock art consists most commonly of similar-looking scenes of cattle, hunting tableaux, or camel depictions, but there are some exceptions of interest, for example: the monumental bull engraving from Akhrejit in the Dhar Tichitt, which is nearly 5 metres long; the unusually naturalistic paintings of cattle at Amogjar and Tenses in the Adrar; and the curiously shaped painted horses at Guilemsi in the Tagant-Titchitt region. In addition, although images of chariots apparently drawn by oxen are known elsewhere in the Sahara, chariots in Saharan rock art are normally associated with horses. In Mauritania, however, there are several images of ox chariots or carts – both painted and engraved – as well as depictions of cattle apparently bearing burdens/saddles, or mounted. Moreover, Mauritania has no known depictions of chariots where the draught animal is identifiably a horse, although there are many images of horses and riders. Sometimes chariots are depicted independent of any animals drawing them, and in all there are over 200 known images of chariots in the country. - sys: id: 3MShhKY9bWiw8u6WGkek6s created_at: !ruby/object:DateTime 2015-11-26 12:55:35.339000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:55:35.339000000 Z content_type_id: image revision: 1 image: sys: id: 5LOsfjF8UEYmIUaQ00cA8i created_at: !ruby/object:DateTime 2015-11-26 12:50:25.657000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:50:25.657000000 Z title: '2013,2034.12381' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5LOsfjF8UEYmIUaQ00cA8i/2f5c949384c4cd1e5a23e4cc77a4904f/2013_2034.12381.jpg" caption: Cattle painted with different designs, Guilemsi, Tagant, Mauritania. 2013,2034.12381 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3646170&partId=1&searchText=2013,2034.12381+&page=1 - sys: id: 2mhsdlyizy886WMQkoOmmM created_at: !ruby/object:DateTime 2015-11-26 12:56:29.522000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:56:29.522000000 Z content_type_id: image revision: 1 image: sys: id: 6Cccz71bd66Es0EcmMqICa created_at: !ruby/object:DateTime 2015-11-26 12:50:25.724000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:50:25.724000000 Z title: '2013,2034.12449' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6Cccz71bd66Es0EcmMqICa/82071c6a91a03c64020c9d7ce81fc354/2013_2034.12449.jpg" caption: Cattle painted with different designs, Guilemsi, Tagant, Mauritania. 2013,2034.12449 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3647071&partId=1&searchText=2013%2c2034.12449&page=1 - sys: id: 5vzOFu8OlOEAUMGS0KYIw2 created_at: !ruby/object:DateTime 2015-11-26 13:06:27.333000000 Z updated_at: !ruby/object:DateTime 2015-11-26 13:06:27.333000000 Z content_type_id: chapter revision: 1 title: Chronology title_internal: 'Mauritania: country, chapter 6' body: 'As is the case with all Saharan rock art, sites found in Mauritania are very difficult to date, especially absolutely. Monod remarked: ‘it is impossible to propose even approximate dates: no landmark pinpoints the end of the Neolithic and the arrival of Libyan (Berber) horsemen’ (Monod, 1938, p.128). Relative chronologies of rock art styles are easier to identify than specific dates, as they may be based on visible elements such as superimpositions in paintings, and the darkness level of accrued patina in engravings. In Mauritania, researchers have generally paid particular attention to patina as well as themes and styles in order to try and place a timeframe on different rock art traditions. Even this is an inexact science – however, Monod did propose a three-phase chronology, with 1) ‘Ancient’ prehistoric rock art showing large wild fauna and cattle, 2) ‘Middle’ pre-Islamic art showing horses, camels, riders, arms and armour, hunting scenes and Libyco-Berber script and 3) ‘Modern’ Islamic-era art with modern Tifinagh and Arabic inscriptions.' - sys: id: 79JveWwduEWS0GOECouiCi created_at: !ruby/object:DateTime 2015-11-26 12:57:03.931000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:57:03.931000000 Z content_type_id: image revision: 1 image: sys: id: W4EibqP766CYAamWyqkQK created_at: !ruby/object:DateTime 2015-11-26 12:50:25.952000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:21:05.070000000 Z title: '2013,2034.12332' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3646132&partId=1&searchText=2013,2034.12332&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/W4EibqP766CYAamWyqkQK/523fee62695a3de60ff7940899dfaaf1/2013_2034.12332.jpg" caption: Engraved geometric shapes, M’Treoka, Hodh el Garbi, Mauritania. 2013,2034.12332 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3646132&partId=1&searchText=2013%2c2034.12332&page=1 - sys: id: 4AtrIwkF7OaKCEAiQ2GASg created_at: !ruby/object:DateTime 2015-11-26 13:06:44.804000000 Z updated_at: !ruby/object:DateTime 2015-11-26 13:06:44.804000000 Z content_type_id: chapter revision: 1 title_internal: 'Mauritania: country, chapter 7' body: Mauny later proposed a more nuanced chronology, based also on style and technique, along the same lines as Monod’s. Mauny’s proposed divisions include a ‘naturalist’ period from 5,000–2,000 BC, a cattle pastoralist phase from 2,500–1,000 BC, a horse period from 1,200 BC onwards, a ‘Libyco-Berber’ group from 200 BC–700 AD and a final ‘Arabo-Berber’ phase from 700 AD onwards (Mauny, 1954). While the oldest rock art, such as the paintings at Amogjar, could be more than 5,000 years old, it appears that most Mauritanian rock art probably post-dates 2,000 BC, with some, particularly that involving camels, made within the last 2,000 years. - sys: id: 4lUHWxICtWgQ0w6iy28iEI created_at: !ruby/object:DateTime 2015-11-26 13:07:10.157000000 Z updated_at: !ruby/object:DateTime 2015-11-26 13:07:10.157000000 Z content_type_id: chapter revision: 1 title_internal: 'Mauritania: country, chapter 8' body: 'Further evidence from the archaeological record and historical knowledge is helpful in ascribing dates and authorship to some of the rock art. The time period over which rock art was produced in Mauritania coincided with dramatic changes in the climate and the desertification of the Sahara, which settled at present levels of aridity following increased dry periods: around 1,500 BC in the North, and by the mid-1st Millenium AD in the South. There is some evidence for a combination of hunting and pastoral activity in the North-East prior to the desertification, with pastoralism becoming an important means of subsistence in the South after 2,000 BC.' - sys: id: 48cLDAbqdim44m0G0kAiMm created_at: !ruby/object:DateTime 2015-11-26 12:58:12.334000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:58:12.334000000 Z content_type_id: image revision: 1 image: sys: id: 6gZ1qhryX6EM26sQo4MWYQ created_at: !ruby/object:DateTime 2015-11-26 12:50:26.009000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:50:26.009000000 Z title: '2013,2034.12340' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6gZ1qhryX6EM26sQo4MWYQ/ffd1149106f1364f7e7c15130243b5cc/2013_2034.12340.jpg" caption: Crocodiles in pool below engraving site at M’Treoka with relict populations of crocodiles. Hodh el Garbi, Mauritania. 2013,2034.12340 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3646115&partId=1&searchText=2013,2034.12340&page=1 - sys: id: 2f2rsdCUH6yWQkC2y4i6aC created_at: !ruby/object:DateTime 2015-11-26 13:07:28.228000000 Z updated_at: !ruby/object:DateTime 2015-11-26 13:07:28.228000000 Z content_type_id: chapter revision: 1 title_internal: 'Mauritania: country, chapter 9' body: The first solid archaeological evidence for horses this far west is from about 600 AD. However, horses and chariots could have been introduced over a thousand years before, possibly by early Berber peoples from the North, who are thought to have made increased incursions from the 4th Millennium onwards, and with whom much of the rock art is usually associated. Chariot images can be reasonably assumed to date from the time we know chariots were in use in the Sahara – i.e. not earlier than 1,200 BC. - sys: id: 3bDBY7ve9GkIoEAeqCKe6M created_at: !ruby/object:DateTime 2015-11-26 13:07:55.785000000 Z updated_at: !ruby/object:DateTime 2015-11-26 13:07:55.785000000 Z content_type_id: chapter revision: 1 title: Interpretation title_internal: 'Mauritania: country, chapter 10' body: 'Generally, the study of Mauritanian rock art traditions has focused more on cataloguing the images and categorising them by style, technique and perceived age than investigating their potential cultural significance. The limitations in the ability to scientifically date these images, and the fact that they are not usually associated with other archaeological materials, hinders effective attempts at interpretation or ascribing authorship, beyond basic ‘Neolithic’ ‘pastoralist’, or ‘early Berber’. Even this may not be clear-cut or mutually exclusive: for example, incoming Berber peoples in the Adrar Plateau after 2,000 BC are thought to have been cattle pastoralists, as their non-Berber predecessors probably were. In addition, while the desertification process was definitive from this time on, fluctuations and regional microclimates made pastoralism viable relatively recently in some areas – in the Adrar there is still evidence of cattle rearing as late as 1,000 BC or after, and some areas of the Tagant region may have been able to support cattle as late as the 18th century. Thus subject matter alone is not necessarily indicative of date or authorship: depictions of cattle may be Berber or non-Berber, as old as the 4th millennium BC or as recent as the 1st, if not later.' - sys: id: 3j9ouDudwkk8qqEqqsOI4i created_at: !ruby/object:DateTime 2015-11-26 12:58:46.100000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:58:46.100000000 Z content_type_id: image revision: 1 image: sys: id: 4zNeoXAAesUaCGoaSic6qO created_at: !ruby/object:DateTime 2015-11-26 12:50:25.588000000 Z updated_at: !ruby/object:DateTime 2019-02-12 01:21:40.547000000 Z title: '2013,2034.12285' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3645983&partId=1&searchText=2013,2034.12285&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/4zNeoXAAesUaCGoaSic6qO/97398e8ebe5bd8be1adf57f450a72e08/2013_2034.12285.jpg" caption: Painted ‘bitriangular’ horse and rider with saddle, Guilemsi, Mauritania. 2013,2034.12285 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3645983&partId=1&searchText=2013%2c2034.12285&page=1 - sys: id: 5Rfj3BIjRugQEoOOwug8Qm created_at: !ruby/object:DateTime 2015-11-26 13:08:21.025000000 Z updated_at: !ruby/object:DateTime 2015-11-26 13:08:21.025000000 Z content_type_id: chapter revision: 1 title_internal: 'Mauritania: country, chapter 11' body: It is possible to make some more specific inferences based on style. Some of the more naturalistic cattle paintings from the Adrar have been compared in style to the Bovidian style paintings of the Tassili n’Ajjer in Libya, and some of the more geometric designs to others in Senegal and Mali. Links have also been suggested between some cattle and symbolic images and modern Fulani and Tuareg traditions and iconography. In terms of significance, changes to rock art style over time, from naturalistic to schematic, have been remarked upon as perhaps somehow reflecting environmental changes from savannah to steppe and desert. It has also been debated whether some of the geometric symbols and images of riders on horseback were the result of conflict, perhaps made by the victims of Berber invasions as catharsis or to ward off evil. - sys: id: 2NWh1MPulOkK4kQSgKuwyO created_at: !ruby/object:DateTime 2015-11-26 12:59:21.672000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:59:21.672000000 Z content_type_id: image revision: 1 image: sys: id: 6NlmQWPzJSiCWEIek2ySa8 created_at: !ruby/object:DateTime 2015-11-26 12:50:26.009000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:50:26.009000000 Z title: '2013,2034.12390' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6NlmQWPzJSiCWEIek2ySa8/f6454e19c8de0ed0ba409100bc3cd56b/2013_2034.12390.jpg" caption: Handprint, Guilemsi, Tagant, Mauritania.2013,2034.12390 © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3646185&partId=1&searchText=2013%2c2034.12390&page=1 - sys: id: 32ujQ27WmIokwSaq0g8y8E created_at: !ruby/object:DateTime 2015-11-26 13:08:35.046000000 Z updated_at: !ruby/object:DateTime 2015-11-26 13:08:35.046000000 Z content_type_id: chapter revision: 1 title_internal: 'Mauritania: country, chapter 12' body: At this point, however, such inferences are fragmentary and speculative, and it is clear that more comprehensive study of rock art in context in the region is desirable, as it potentially holds much interest for the study of the history and prehistory of Mauritania. It is also an endangered resource, due to a combination of environmental factors, such as extremes of temperature which damage and split the rocks, and human interference from looting and vandalism. citations: - sys: id: 4BBq4ePWQEC2Y2OmceCGgW created_at: !ruby/object:DateTime 2015-11-26 12:51:23.581000000 Z updated_at: !ruby/object:DateTime 2015-11-26 12:51:23.581000000 Z content_type_id: citation revision: 1 citation_line: |- <NAME>., 2010. *Mauritanian Rock Art: A New Recording*. Biblioteca Alexandrina, Alexandria <NAME>, 1954 *Gravures, peintures et inscriptions rupestres de l'Ouest africain*. Vol. 11. Institut français d'Afrique noire <NAME>., 1938. *Contributions à l’étude du Sahara Occidental. Gravures, Peintures et Inscriptions rupestres*. Publications du Comité d’études historiques et scientifiques de l’Afrique occidentale française, Paris <NAME>. 1993. *Préhistoire de la Mauritanie*. Centre Culturel Français A. de Saint Exupéry-Sépia, Nouakchott <NAME>. & <NAME>. *Dictionnaire Archéologique de la Mauritanie*. CRIAA, Université de Nouakchott ---<file_sep>/_coll_country/ethiopia/shepe.md --- breadcrumbs: - label: Countries url: "../../" - label: Ethiopia url: "../" layout: featured_site contentful: sys: id: 5I6VFY4EX6GOW2mCag08aU created_at: !ruby/object:DateTime 2015-11-25 11:54:40.762000000 Z updated_at: !ruby/object:DateTime 2015-12-07 20:52:58.329000000 Z content_type_id: featured_site revision: 5 title: Shepe, Ethiopia slug: shepe chapters: - sys: id: 4ixjUTf8kEQuQk4GMOy4W6 created_at: !ruby/object:DateTime 2015-11-25 10:41:05.845000000 Z updated_at: !ruby/object:DateTime 2017-01-11 11:21:10.230000000 Z content_type_id: chapter revision: 5 title_internal: 'Ethiopia: featured site, chapter 1' body: The site of Shepe (also known as Chabbé, Šappe or Mancheti) is located in the Sidamo Zone of Oromia, about 250 km to the south of Addis Ababa. The region is a fertile, forest-mountainous area traditionally dedicated to the cultivation of coffee. The site is in a narrow gorge carved by the Shepe River at 1300 m above sea level, full of vegetation and therefore difficult to detect. Along this gorge there are several notable engravings depicted in four panels, forming one of the most impressive – if secluded — rock art sites in the Horn of Africa. The site was discovered in 1965 by Fitaorari Selechi Defabatchaw, governor of the Dilla district where the site is located, and was published by <NAME> two years later. Since that, the importance of Shepe has been widely recognized and some other sites with similar engravings have been documented in the surrounding area. This group (known generically as the Shepe-Galma group) constitutes one of the main areas of Ethiopian rock art, the other being the Laga Oda-Sourré group in the Harar region. images_and_captions: - sys: id: 5EG7K0Z26cUMISeKsAww4s created_at: !ruby/object:DateTime 2015-11-25 10:47:14.674000000 Z updated_at: !ruby/object:DateTime 2015-11-25 10:47:14.674000000 Z content_type_id: image revision: 1 image: sys: id: pU5IbmTygg4ka2kYisEyc created_at: !ruby/object:DateTime 2015-11-25 10:45:07.360000000 Z updated_at: !ruby/object:DateTime 2015-11-25 10:45:07.360000000 Z title: '2013,2034.16227' description: url: "//images.ctfassets.net/xt8ne4gbbocd/pU5IbmTygg4ka2kYisEyc/72c98385edd3833e70e9763f66945e98/ETHSID0050002.jpg" caption: View of the crease where the Shepe engravings are placed. Shepe, Ethiopia. 2013,2034.16227. col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3691737&partId=1&searchText=2013,2034.16227&page=1 - sys: id: 5EG7K0Z26cUMISeKsAww4s created_at: !ruby/object:DateTime 2015-11-25 10:47:14.674000000 Z updated_at: !ruby/object:DateTime 2015-11-25 10:47:14.674000000 Z content_type_id: image revision: 1 image: sys: id: pU5IbmTygg4ka2kYisEyc created_at: !ruby/object:DateTime 2015-11-25 10:45:07.360000000 Z updated_at: !ruby/object:DateTime 2015-11-25 10:45:07.360000000 Z title: '2013,2034.16227' description: url: "//images.ctfassets.net/xt8ne4gbbocd/pU5IbmTygg4ka2kYisEyc/72c98385edd3833e70e9763f66945e98/ETHSID0050002.jpg" caption: View of the crease where the Shepe engravings are placed. Shepe, Ethiopia. 2013,2034.16227. col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3691737&partId=1&searchText=2013,2034.16227&page=1 - sys: id: 1meXvF3KKYugMos2qqyyyA created_at: !ruby/object:DateTime 2015-11-25 10:50:09.415000000 Z updated_at: !ruby/object:DateTime 2017-01-11 11:21:36.739000000 Z content_type_id: chapter revision: 2 title_internal: 'Ethiopia: featured site, chapter 2' body: 'The rock art of Shepe consists almost exclusively of engravings of humpless cows which follow very strict conventions: profile bodies, small heads with long horns seen from above, U-like bellies and udders very clearly depicted. Some of the cows have an unidentified, triangular object hanging from their left horn. In total, around 50 relatively large cows (40 to 70 cm in length) are depicted throughout the gorge walls, distributed in rows and groups to represent herds. The most original feature of these engravings is, however, the technique used to depict them: rather than carving the outline of the cows, the area around them has been lowered to provide a bas-relief effect which has no known parallels in the region. The surface of the cows has been polished to obtain a smooth appearance.' images_and_captions: - sys: id: 3t1tUJZNRY4kkQAIeKmIea created_at: !ruby/object:DateTime 2015-11-25 10:50:00.721000000 Z updated_at: !ruby/object:DateTime 2015-11-25 10:50:00.721000000 Z content_type_id: image revision: 1 image: sys: id: 4wQ6Srd7EI0ckCYoA4IaWS created_at: !ruby/object:DateTime 2015-11-25 10:45:25.200000000 Z updated_at: !ruby/object:DateTime 2015-11-25 10:45:25.200000000 Z title: '2013,2034.16236' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4wQ6Srd7EI0ckCYoA4IaWS/3b87b98a6668f272110f5baf48e65a5b/ETHSID0060007.jpg" caption: View of the Shepe main panel. Shepe, Ethiopia. 2013,2034.16236. col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3691722&partId=1&searchText=2013,2034.16236&page=1 - sys: id: 3t1tUJZNRY4kkQAIeKmIea created_at: !ruby/object:DateTime 2015-11-25 10:50:00.721000000 Z updated_at: !ruby/object:DateTime 2015-11-25 10:50:00.721000000 Z content_type_id: image revision: 1 image: sys: id: 4wQ6Srd7EI0ckCYoA4IaWS created_at: !ruby/object:DateTime 2015-11-25 10:45:25.200000000 Z updated_at: !ruby/object:DateTime 2015-11-25 10:45:25.200000000 Z title: '2013,2034.16236' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4wQ6Srd7EI0ckCYoA4IaWS/3b87b98a6668f272110f5baf48e65a5b/ETHSID0060007.jpg" caption: View of the Shepe main panel. Shepe, Ethiopia. 2013,2034.16236. col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3691722&partId=1&searchText=2013,2034.16236&page=1 - sys: id: 2MCiQOzg1WWksmyW4kiCko created_at: !ruby/object:DateTime 2015-11-25 10:51:18.446000000 Z updated_at: !ruby/object:DateTime 2015-11-25 10:51:18.446000000 Z content_type_id: chapter revision: 1 title_internal: 'Ethiopia: featured site, chapter 3' body: The chronology of the Shepe cows is difficult to determine, but stylistically they have been related to the Laga Oda paintings in the area of Harar and to other sites in Eritrea and Djibouti. According to most researchers, the Shepe figures have been ascribed to the so-called Ethiopian-Arabian style, with a generic chronology from the 3rd to the 1st millennia BC. Shepe engravings can be considered relatively naturalistic, and therefore should be among the oldest depictions of this style. Other interpretations, however, consider Shepe and the nearby sites a completely differentiated school whose chronology is still unclear but could be more recent. images_and_captions: - sys: id: 23e0al3lEEaeCEawuaEuei created_at: !ruby/object:DateTime 2015-11-25 10:51:09.956000000 Z updated_at: !ruby/object:DateTime 2015-11-25 10:51:09.956000000 Z content_type_id: image revision: 1 image: sys: id: 2NxPqNw24UkMkmY0oAeMUW created_at: !ruby/object:DateTime 2015-11-25 10:45:40.809000000 Z updated_at: !ruby/object:DateTime 2015-11-25 10:45:40.809000000 Z title: '2013,2034.16235' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2NxPqNw24UkMkmY0oAeMUW/2722889dec86c49a3d5c1fa47f5c96ff/ETHSID0060006.jpg" caption: Frontal view of one the Shepe panels. Shepe, Ethiopia. 2013,2034.16235. col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3691723&partId=1&searchText=2013,2034.16235&page=1 - sys: id: 23e0al3lEEaeCEawuaEuei created_at: !ruby/object:DateTime 2015-11-25 10:51:09.956000000 Z updated_at: !ruby/object:DateTime 2015-11-25 10:51:09.956000000 Z content_type_id: image revision: 1 image: sys: id: 2NxPqNw24UkMkmY0oAeMUW created_at: !ruby/object:DateTime 2015-11-25 10:45:40.809000000 Z updated_at: !ruby/object:DateTime 2015-11-25 10:45:40.809000000 Z title: '2013,2034.16235' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2NxPqNw24UkMkmY0oAeMUW/2722889dec86c49a3d5c1fa47f5c96ff/ETHSID0060006.jpg" caption: Frontal view of one the Shepe panels. Shepe, Ethiopia. 2013,2034.16235. col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3691723&partId=1&searchText=2013,2034.16235&page=1 - sys: id: 5Ts9l53bJ6uU4OKaqYEAMO created_at: !ruby/object:DateTime 2015-11-25 10:51:54.888000000 Z updated_at: !ruby/object:DateTime 2015-12-11 12:20:03.439000000 Z content_type_id: chapter revision: 2 title_internal: 'Ethiopia: featured site, chapter 4' body: Regarding their meaning, only conjecture can be made at present, but it seems quite likely that they were made by pastoral communities to whom cattle were fundamental. The careful depiction of the udders, the repetition of this single motif and the effort paid to achieve the bas-relief effect imply a paramount importance of cattle in the economy and society of the group that engraved them. The fact that some of the cows have what seem to be adornments hanging from the horns (a feature documented in other rock art regions as the Libyan Messak) also points in that direction. Contemporary groups, such as the Nuer in nearby Sudan have similar traditions of horn adornments, and throughout the Omo river region different techniques of embellishment (ear cutting, horn shaping, modifications of the hump) have been documented, and in all of them cattle are a key cultural mark as well as an economic resource. Of course, direct links cannot be established between these contemporary examples and the communities that made the engravings of Shepe, but the cattle depictions in the ravine are nevertheless a document of the importance and consideration given to cattle, an animal which was undoubtedly part of these groups’ identity. citations: - sys: id: 435YtX7CQ08gcuU240ucwc created_at: !ruby/object:DateTime 2015-11-25 10:52:31.089000000 Z updated_at: !ruby/object:DateTime 2015-12-11 12:20:33.907000000 Z content_type_id: citation revision: 3 citation_line: |- <NAME>. (1967): Les sculptures rupestres de Chabbè dans le Sidamo. *Annales d'Ethiopie* 7: 19-32. <NAME>. (ed.) (1995): *Tiya, l’Ethiopie des mégalithes : du biface à l’art rupestre dans la Corne de l’Afrique*. Association des publications chauvinoises (A.P.C.), Chauvigny. <NAME>., & <NAME> (2001): New sites of South Ethiopian rock engravings: <NAME>, <NAME>, and remarks on the Sappe-Galma School. *Annales d’Ethiopie*, 17: 205-224. background_images: - sys: id: 6bqPx8NVF6CsoC6kS4KkQ4 created_at: !ruby/object:DateTime 2015-12-07 20:36:14.616000000 Z updated_at: !ruby/object:DateTime 2015-12-07 20:36:14.616000000 Z title: ETHSID0080008 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6bqPx8NVF6CsoC6kS4KkQ4/2b81668d390ad745fc484b83c33c3548/ETHSID0080008.jpg" - sys: id: 6johOxHojKY4EkOqEco6c6 created_at: !ruby/object:DateTime 2015-11-25 19:45:27.772000000 Z updated_at: !ruby/object:DateTime 2015-11-25 19:45:27.772000000 Z title: ETHSOD0030007 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6johOxHojKY4EkOqEco6c6/2640f76a5871320bf2ff03fefd8c37a7/ETHSOD0030007.jpg" ---<file_sep>/_coll_country/kenya/mfangano-island.md --- breadcrumbs: - label: Countries url: "../../" - label: Kenya url: "../" layout: featured_site contentful: sys: id: 2kZmXHcYEkaWQGMK4sGq0Y created_at: !ruby/object:DateTime 2015-11-25 12:47:03.425000000 Z updated_at: !ruby/object:DateTime 2015-12-08 18:51:10.317000000 Z content_type_id: featured_site revision: 6 title: Mfangano Island, Kenya slug: mfangano-island chapters: - sys: id: 4ffcl2AJFuUmcS2oykeieO created_at: !ruby/object:DateTime 2015-11-25 13:54:02.102000000 Z updated_at: !ruby/object:DateTime 2015-11-25 13:54:02.102000000 Z content_type_id: chapter revision: 1 title_internal: 'Kenya: featured site, chapter 1' body: 'Lake Victoria is the largest lake in Africa, and at 69,484km², the second largest in the world by surface area. Sitting in a depression in the plateau between the eastern and western valley branches of the geological East African Rift System, its shores are in Uganda, Tanzania, and to the south-east, in Kenya. Mfangano Island, rising 300m out of the lake near the Kenyan shore, is home to some of the most prominent rock painting sites in the country, featuring abstract patterned paintings thought to have been created between 1,000 and 4,000 years ago by hunter-gatherers. The rock paintings on Mfangano Island are found at two principal sites: in a cave near the sea known as Mawanga, and at a rock shelter further inland called Kwitone.' - sys: id: Ak4bSLKQyOCQESmSuukEk created_at: !ruby/object:DateTime 2015-11-25 12:47:44.566000000 Z updated_at: !ruby/object:DateTime 2017-01-23 16:45:35.105000000 Z content_type_id: image revision: 4 image: sys: id: 37G9MkkxFuC0mu6qGwcs2y created_at: !ruby/object:DateTime 2015-12-08 18:49:22.433000000 Z updated_at: !ruby/object:DateTime 2015-12-08 18:49:22.433000000 Z title: KENVIC0010032 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/37G9MkkxFuC0mu6qGwcs2y/20dfc41bbaef46d2cc5b733269b032ce/KENVIC0010032_1.jpg" caption: Lake Victoria. 2013,2034.14266 © <NAME>/TARA. col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3692066&partId=1&searchText=2013,2034.14266&page=1 - sys: id: 3MSOAnbnKoq0ACuaYEK0AK created_at: !ruby/object:DateTime 2015-11-25 13:55:03.942000000 Z updated_at: !ruby/object:DateTime 2015-11-25 13:55:03.942000000 Z content_type_id: chapter revision: 1 title_internal: 'Kenya: featured site, chapter 2' body: Mawanga is a roughly triangular limestone cavern, about 18m wide across the mouth and 12m deep. The roof slopes sharply to the back towards a raised platform against the rear of the left wall, on which 12 images of concentric circles and spirals in white and red have been painted. Kwitone has similar paintings, situated at one end of a long overhang in a sandstone cliff, below the shoulder of a ridge. The rock art at Kwitone is at the far end on the shelter wall, several metres above a cleared floor section. The paintings here feature 11 distinct shapes including concentric circles and oblongs. One of these is a prominent sunburst pattern in brown, with rays emanating from the outermost band. The images are larger than those at Mawanga, averaging around 40cm in diameter, and less faded, exhibiting more brown pigment, although both sites appear to reflect the same artistic tradition. These are finger paintings, with pigment probably made of haematite or white clay mixed with a natural binder such as egg white or urine. There is evidence that the surface may also have also been prepared prior to painting, by polishing, and that some of the images may have reapplied or retouched over time. - sys: id: 2W5cMhvviwo6OEMc04u40E created_at: !ruby/object:DateTime 2015-11-25 12:49:05.022000000 Z updated_at: !ruby/object:DateTime 2017-01-23 16:46:53.507000000 Z content_type_id: image revision: 3 image: sys: id: 4RTDlc6IOIikMaMg8mQaoc created_at: !ruby/object:DateTime 2015-12-08 18:49:43.951000000 Z updated_at: !ruby/object:DateTime 2015-12-08 18:49:43.951000000 Z title: KENVIC0020005 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/4RTDlc6IOIikMaMg8mQaoc/2572f0ad5751cb16ffb281daccfc39d3/KENVIC0020005_1.jpg" caption: Painted panel at Mawanga Cave. 2013,2034.14278 © <NAME>/TARA. col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3692333&partId=1&searchText=2013,2034.14278&page=1 - sys: id: 5yjxz7az7yYSQi2u4UQaIk created_at: !ruby/object:DateTime 2015-11-25 12:49:47.517000000 Z updated_at: !ruby/object:DateTime 2017-01-23 16:47:08.898000000 Z content_type_id: image revision: 3 image: sys: id: 516BFdHg1G4yO6IkWOQimW created_at: !ruby/object:DateTime 2015-12-08 18:49:43.951000000 Z updated_at: !ruby/object:DateTime 2015-12-08 18:49:43.951000000 Z title: KENVIC0010001 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/516BFdHg1G4yO6IkWOQimW/7c7491674484c9ae4d39ccc06d98b6be/KENVIC0010001_1.jpg" caption: Spiral and sunburst at Kwitone. 2013,2034.14250 © <NAME>/TARA. col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3685756&partId=1&searchText=2013,2034.14250&page=1 - sys: id: 2UpIfZaJVSIyUweYYKak64 created_at: !ruby/object:DateTime 2015-11-25 13:55:35.312000000 Z updated_at: !ruby/object:DateTime 2015-11-25 13:55:35.312000000 Z content_type_id: chapter revision: 1 title_internal: 'Kenya: featured site, chapter 3' body: The circular shapes seen here are typical of an apparent wider East and Central African rock art tradition featuring a preponderance of circular motifs, usually attributed to people known as the Batwa, a Bantu-origin name for a series of culturally related groups historically living around Africa’s Great Lakes region and more widely throughout Central Africa. Like the San people, who are known to have been the creators of most of the famous rock art of Southern Africa, Batwa were traditionally hunter-gatherers, and are considered the most ancient indigenous populations of the area. In the early 20th century, it was proposed that East African rock art of this tradition could have been the work of ancestral San people, but it is now generally assumed to be of Batwa origin with, for example, possible parallels to be seen in the symbolic iconography with contemporary barkcloth designs of the related Mbuti people from the Democratic Republic of Congo (Namono, 2010). - sys: id: 1AWKNMNRSImMCASQusuWc0 created_at: !ruby/object:DateTime 2015-11-25 12:50:25.070000000 Z updated_at: !ruby/object:DateTime 2017-01-23 17:17:59.954000000 Z content_type_id: image revision: 3 image: sys: id: 2wD915QEYQqsQCCyEusyoW created_at: !ruby/object:DateTime 2015-12-08 18:49:35.128000000 Z updated_at: !ruby/object:DateTime 2015-12-08 18:49:35.128000000 Z title: UGAVIC0060005 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/2wD915QEYQqsQCCyEusyoW/1d5d5b96ebac21badfaaa87cbb154ca5/UGAVIC0060005_1.jpg" caption: "“Dumbbell” shapes at nearby Lolui Island. 2013,2304.15306 © <NAME>/TARA." col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3691242&partId=1 - sys: id: 7KbMWDFuY8CwgkwiQuiWew created_at: !ruby/object:DateTime 2015-11-25 13:56:16.375000000 Z updated_at: !ruby/object:DateTime 2015-11-25 13:56:16.375000000 Z content_type_id: chapter revision: 1 title_internal: 'Kenya: featured site, chapter 4' body: 'Further examples of apparently Batwa origin rock art can be seen in neighbouring Uganda and Tanzania, a reminder that contemporary political borders do not reflect physical partitions in the spatial coverage of rock art traditions. Lolui Island, about 50km north west of Mfangano Island and in Ugandan waters, is another important Lake Victoria rock art environment, featuring both painting sites and rock gongs (sonorous natural percussive instruments with the wear of use) which seem to be associated with the painting sites. There are also numerous sets of cupules—ground circular depressions in the rocks. Some of these are referred to locally as Omweso, due to their bearing some resemblance to the depressions used for holding gaming pieces in the so-named local variant of the Mancala-type board games played widely throughout eastern Africa. However, their original significance and use is unknown. Cupule sites are also found on the Kenyan mainland and on Mfangano island. Many of these are clearly anthropogenic, however an unusual phenomenon is to be noted in the spectacular array of naturally formed cupule-like depressions in the limestone of Mawanga cave. This may remind us to exercise caution in ascribing ‘rock art’ status to all apparently patterned rock formations. The cause of these multitudinous small depressions is so far unknown. ' - sys: id: 5j3ZVzX81O8qs44GE4i6Oa created_at: !ruby/object:DateTime 2015-11-25 12:51:05.574000000 Z updated_at: !ruby/object:DateTime 2017-01-23 17:18:53.166000000 Z content_type_id: image revision: 3 image: sys: id: iF8lN8WDzqKWeu2OUQ8gc created_at: !ruby/object:DateTime 2015-12-08 18:49:22.434000000 Z updated_at: !ruby/object:DateTime 2015-12-08 18:49:22.434000000 Z title: KENVIC0020012 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/iF8lN8WDzqKWeu2OUQ8gc/1ea0ae4e085ae7da13cb701cb35493c5/KENVIC0020012_1.jpg" caption: Natural “cupules”, Mawanga Cave. 2013,2034.14285 © <NAME>/TARA. col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3692304&partId=1&searchText=2013,2034.14285&page=1 - sys: id: 1MO5OjJiaQyeUYEkA0ioOi created_at: !ruby/object:DateTime 2015-11-25 13:57:11.093000000 Z updated_at: !ruby/object:DateTime 2015-11-25 13:57:11.093000000 Z content_type_id: chapter revision: 1 title_internal: 'Kenya: featured site, chapter 5' body: 'The rock art sites of the eastern Lake Victoria region retain spiritual connotations for the communities living around them, even if their denoted modern significance differs from that envisioned by the original artists. The modern inhabitants of Mfangano Island are the Abasuba people, a Bantu language-speaking group unrelated to the Batwa who have nevertheless appropriated the sites as arenas of spiritual importance. Members of the Wasamo clan in the area around Mawanga remember their having used the site for rain making rituals until a few decades ago, with red and white pigment apparently representing the moon and sun respectively. Soot on the cave roof may indicate other recent human activity there. When the archaeologist <NAME>—who first investigated the Kwitone site in the 1960s—visited it later, he was told by local Wagimbe clan people that they also held the paintings there to be associated with some taboos, and connected it with ancestor worship. These beliefs reflect events of the recent past, as the Abasuba only moved into the area in the last 400 years. This followed an earlier occupation by Luo peoples, prior to which habitation by the Batwa is assumed. The local importance of the sites is highlighted in their stewardship by the Abasuba Peace Museum, which fosters a continuing relationship with the sites and those who live around them. ' - sys: id: 38TIUovoUMimQ6G4UmiCOS created_at: !ruby/object:DateTime 2015-11-25 12:51:38.839000000 Z updated_at: !ruby/object:DateTime 2017-01-23 17:19:17.336000000 Z content_type_id: image revision: 3 image: sys: id: 4QK41OYhpSa0qogICAW2aQ created_at: !ruby/object:DateTime 2015-12-08 18:49:22.436000000 Z updated_at: !ruby/object:DateTime 2015-12-08 18:49:22.436000000 Z title: KENVIC0010039 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/4QK41OYhpSa0qogICAW2aQ/fddcfe64e7040cb2dfde96be8d043a2d/KENVIC0010039_1.jpg" caption: Sign leading to the rock art on Mfangano Island. 2013,2034.14273 © <NAME>/TARA. col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3692275&partId=1&searchText=2013,2034.14273&page=1 - sys: id: 6872dmGUjSMsOgWqW0GKOa created_at: !ruby/object:DateTime 2015-11-25 13:59:14.477000000 Z updated_at: !ruby/object:DateTime 2015-11-25 13:59:14.477000000 Z content_type_id: chapter revision: 1 title_internal: 'Kenya: featured site, chapter 6' body: In 2014, <NAME>, curator of the Abasuba Peace Museum, [visited The British Museum](http://www.britishmuseum.org/pdf/BM_Africa_Programme_Newsletter_spring_2015.pdf) for a training and skills exercise as part of the [Africa Programme](http://www.britishmuseum.org/about_us/skills-sharing/africa_programme.aspx), which works closely with national and independent museums across the continent to develop training initiatives. citations: - sys: id: t1Gh6AyCYKqaQ442MgGUI created_at: !ruby/object:DateTime 2015-11-25 12:52:31.875000000 Z updated_at: !ruby/object:DateTime 2015-11-25 12:52:31.875000000 Z content_type_id: citation revision: 1 citation_line: |- <NAME>. 1974. *The Prehistoric rock art of the lake Victoria region*. Azania, IX, 1-50. <NAME>, 2010. *Surrogate Surfaces: a contextual interpretive approach to the rock art of Uganda*. Unpublished PhD Thesis, Graduate School of Humanities, University of the Witwatersrand, Johannesburg Odede, <NAME>., <NAME>. & Agong, <NAME>. 2014. *Rock Paintings and Engravings in Suba Region along the Eastern Shores of Lake Victoria Basin*. Kenya International Journal of Business and Social Research, Issue 04, Volume 10 pp. 15-24 2014 background_images: - sys: id: 37G9MkkxFuC0mu6qGwcs2y created_at: !ruby/object:DateTime 2015-12-08 18:49:22.433000000 Z updated_at: !ruby/object:DateTime 2015-12-08 18:49:22.433000000 Z title: KENVIC0010032 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/37G9MkkxFuC0mu6qGwcs2y/20dfc41bbaef46d2cc5b733269b032ce/KENVIC0010032_1.jpg" - sys: id: iF8lN8WDzqKWeu2OUQ8gc created_at: !ruby/object:DateTime 2015-12-08 18:49:22.434000000 Z updated_at: !ruby/object:DateTime 2015-12-08 18:49:22.434000000 Z title: KENVIC0020012 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/iF8lN8WDzqKWeu2OUQ8gc/1ea0ae4e085ae7da13cb701cb35493c5/KENVIC0020012_1.jpg" ---<file_sep>/Gemfile # frozen_string_literal: true source 'https://rubygems.org' gem 'colorize', require: false gem 'contentful_bootstrap' gem 'kramdown-parser-gfm' gem 'html-proofer' gem 'minima' gem 'rake' gem 'rubocop', require: false gem 'webrick' gem 'jekyll' group :jekyll_plugins do gem 'jekyll-contentful-data-import' gem 'jekyll-minifier' end <file_sep>/README.md # African Rock Art [![Build and deploy to GitHub Pages](https://github.com/kingsdigitallab/african-rock-art/actions/workflows/main.yml/badge.svg?branch=develop)](https://github.com/kingsdigitallab/african-rock-art/actions/workflows/main.yml) ## Requirements The project is built with [Jekyll](https://jekyllrb.com/), which has the following requirements: - GNU/Linux, Unix, or macOS - Ruby version 2.1 or above, including all development headers - [RubyGems](https://rubygems.org/pages/download) - [GCC](https://gcc.gnu.org/install/) and [Make](https://www.gnu.org/software/make/) ## How to Run ```bash echo "Clone repository" git clone <EMAIL>:kingsdigitallab/african-rock-art.git echo "Go to the project directory" cd african-rock-art && git checkout develop echo "Install Bundler gem (may need sudo)" [sudo] gem install bundler echo "Install Dependencies" bundle install --path vendor/bundle && bundle install echo "Start Jekyll Server" bundle exec rake serve ``` Open your browser and go to: [localhost:4000](http://localhost:4000) ## Contentful To import content from the Contentful CMS, copy the file `env.sh.sample` into a file named `env.sh` and edit the Contentful API settings. ```bash echo "Edit Contentful settings" cp env.sh.sample env.sh && nano env.sh echo "Import and process Contentful data" bundle exec rake contentful ``` ## Utilities The project has a `Rakefile` that contains taks and build utilities. To see the tasks available run the command `bundle exec rake --tasks` inside the project directory. Current tasks: ```bash $ bundle exec rake --tasks rake build:dev # Regenerate files for development rake build:prod # Regenerate files for production rake contentful:all # Import and process data from Contentful rake contentful:assets[force] # Import assets from Contentful; by default it only downloads new images, to overwrite existing images do `rake contentful:assets[true]` rake contentful:import # Import data from Contentful rake contentful:process # Process imported data: re-maps Contentful content types and creates content pages rake contentful:resize # Resizes the images imported from Contentful to a maximum of 500k rake gallery # Creates surrogates for the gallery images rake rubocop # Run RuboCop rake rubocop:auto_correct # Auto-correct RuboCop offenses rake serve:dev # Serve development Jekyll site locally rake serve:prod # Serve production Jekyll site locally rake test:all # Test development and production sites rake test:dev # Test development site rake test:prod # Test production site ``` By default, running `bundle exec rake` will run the `test:all` task. [ImageMagick](https://www.imagemagick.org/) is needed to run the `contentful:resize` task. <file_sep>/_coll_country_information/malawi-country-introduction.md --- contentful: sys: id: Yh91lE4KycSSwYOQQOqkW created_at: !ruby/object:DateTime 2016-07-27 07:44:27.867000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:44:27.867000000 Z content_type_id: country_information revision: 1 title: 'Malawi: country introduction' chapters: - sys: id: 3xJlmjTd44aAqYWCeI82ac created_at: !ruby/object:DateTime 2016-07-27 07:45:21.966000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:45:21.966000000 Z content_type_id: chapter revision: 1 title: Introduction title_internal: 'Malawi: country, chapter 1' body: "Malawi is a landlocked country in south-eastern Africa, located between Mozambique, Tanzania and Zambia. It stretches from north to south with the eastern boundary of the country marked by the Lake Malawi. Rock art can be found throughout the country but is especially abundant in central Malawi, near the western border with Mozambique. It consists exclusively of paintings attributed to two very distinctive groups (hunter-gatherers and farmers), and shows obvious links with other sites located in Zambia and western Mozambique. The images consist mainly of animals, anthropomorphic figures and geometric symbols, with a chronology that ranges from the Late Stone Age to the 1950s. \n" - sys: id: 5KKSbUlQm4MUMEgAUaweyu created_at: !ruby/object:DateTime 2016-07-27 07:45:21.937000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:45:21.937000000 Z content_type_id: chapter revision: 1 title: Geography and rock art distribution title_internal: 'Malawi: country, chapter 2' body: 'The geography of Malawi is conditioned by the Great Rift Valley, which runs from north to south and which contains Lake Malawi (also known as Lake Nyasa). Almost 600 km long and more than 50 km wide, Lake Malawi is the second biggest lake in Africa and a key geographical feature of Malawi and the surrounding countries, as well as an important economic resource for the country. The rest of the country west of the Rift Valley is dominated by high plateaus, mostly ranging from 900-1200 m above sea level but reaching 2500 m in the Nyika Plateau to the north and 3000 m at Mt. Mulanje, to the south. The climate is equatorial, with strong seasonal differences, and hotter in the southern part of the country. ' - sys: id: 1zuN2gMyiAg88cw2aKGYWe created_at: !ruby/object:DateTime 2016-07-27 07:45:21.761000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:45:21.761000000 Z content_type_id: image revision: 1 image: sys: id: pDDj71RyBUyqiqsouEeew created_at: !ruby/object:DateTime 2016-07-27 07:46:39.282000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:39.282000000 Z title: MALCHE0010001 description: url: "//images.ctfassets.net/xt8ne4gbbocd/pDDj71RyBUyqiqsouEeew/a0ab78ba58be69235256271b0af54de2/MALCHE0010001.jpg" caption: Landscape in the Chongoni Hills. 2013,2034.20054 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3737098&partId=1 - sys: id: 2iANG11zHqMAmKYmsIKeu8 created_at: !ruby/object:DateTime 2016-07-27 07:45:21.150000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:45:21.150000000 Z content_type_id: chapter revision: 1 title_internal: 'Malawi: country, chapter 3' body: 'Although rock art can be found in several areas in Malawi, the main concentration of sites is located in the Chongoni area, in the westernmost part of central Malawi, very near the border with Mozambique. In that area around 150 rock art sites have been located so far, belonging to the two main traditions of rock art found in the country. Other smaller concentrations of rock art can be found to the south and to the north-west, and around the southern side of Lake Malawi. The distribution of the different styles of Malawian rock art varies substantially: while the older paintings attributed to hunter-gatherers can be found everywhere throughout the country, those made by farmers are concentrated in the Chongoni area, as well as nearby areas of Mozambique and Zambia. Rock art is usually scattered throughout the landscape, in hilly areas where gneiss outcrops provide shelters and well-protected surfaces adequate for painting. ' - sys: id: 271lgJ95Pmkmu0s8a4Qw2k created_at: !ruby/object:DateTime 2016-07-27 07:45:21.218000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:45:21.218000000 Z content_type_id: image revision: 1 image: sys: id: 3lEqMHYBwIse0EmgGkOygW created_at: !ruby/object:DateTime 2016-07-27 07:46:40.051000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:40.051000000 Z title: MALMPH0030003 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3lEqMHYBwIse0EmgGkOygW/26ce17dd2e9b61bef2220ce2ba9afb60/MALMPH0030003.jpg" caption: Rock Art panel showing a lizard and several geometric shapes. Mphunzi, <NAME>. 2013,2034.20205 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3739366&partId=1 - sys: id: 5qpJtPXB4W0a4a04aQeSgG created_at: !ruby/object:DateTime 2016-07-27 07:45:21.145000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:45:21.145000000 Z content_type_id: chapter revision: 1 title: Research history title_internal: 'Malawi: country, chapter 4' body: 'Rock art in Malawi has been documented by Europeans since at least the 1920s, although it wasn’t until the 1950s when the first articles on the subject were published, and it was only in 1978 a first synthesis on Malawian rock art was undertaken (Lindgren, N.E. & Schoffeleers, J.M. 1978). In the 1980s research increased, especially on Chongoni rock art as its importance as a secret society artefact became evident. In 1995 the Chongoni rock art area was comprehensively studied by <NAME> as a part of his doctoral research (1995), which is still the main reference on the topic. Most of the research on Malawi rock art has focused on the study of the two different painting traditions found in Malawi. A basic proposal was made in 1978 when the red paintings—mostly geometric—considered older and attributed to hunter-gatherers, while white paintings were related to more modern groups of farmers which arrived early in the 2nd millennium AD and preserved their painting traditions until the 1950s. Since 1978, the knowledge of these two groups has substantially improved, with a more refined proposal made by <NAME> in his doctoral dissertation. ' - sys: id: 1JMW93aEcQSEcwcG06gg6y created_at: !ruby/object:DateTime 2016-07-27 07:45:21.025000000 Z updated_at: !ruby/object:DateTime 2018-09-19 14:56:42.286000000 Z content_type_id: image revision: 2 image: sys: id: 2OXCOlKLfWO4yUYMc6YiOK created_at: !ruby/object:DateTime 2016-07-27 07:46:40.017000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:40.017000000 Z title: MALDED0090006 description: url: "//images.ctfassets.net/xt8ne4gbbocd/2OXCOlKLfWO4yUYMc6YiOK/0446391cb8c39e21a2baeca5d2566522/MALDED0090006.jpg" caption: Rock Art panel with multitude of red geometric signs. Nthulu, Chongoni Hills. 2013,2034.20003 © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3733695&partId=1&searchText=2013,2034.20003&page=1 - sys: id: 5lHiHzAofecm6YEEG8YGOu created_at: !ruby/object:DateTime 2016-07-27 07:45:20.950000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:45:20.950000000 Z content_type_id: chapter revision: 1 title_internal: 'Malawi: country, chapter 5' body: 'Another important aspect of rock art research in Malawi has been to look at the maintenance of painting traditions until relatively recent times. These exceptional examples have provided fertile ground for further research, as many of these later paintings have been effectively interpreted as parts of initiation rituals that are still undertaken today. The study of the secret societies that preserve this knowledge has been a characteristic feature of Malawi rock art research since the 1970s (Lindgren, N.E. & Schoffeleers, J.M. 1978). ' - sys: id: 1oucgcWELuwwQ8QgCG4kKY created_at: !ruby/object:DateTime 2016-07-27 07:45:20.830000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:45:20.830000000 Z content_type_id: chapter revision: 1 title: 'Themes ' title_internal: 'Malawi: country, chapter 6' body: 'Rock art in Malawi is clearly defined in two groups with different styles, chronologies and production contexts. The first one is characterized by red schematic paintings with parallels in Central Africa from Malawi to Angola. These paintings are associated with the ancestors of modern Batwa hunter-gatherers, and can be classified into two different types. The first can be considered the most characteristic and is represented by circles with radiating lines, concentric circles, ovals, wavy or parallel lines. In some cases, red figures are infilled in white painting or white dots. The second type is very scarce (only two examples have been found in Chongoni) and depicts very schematic animals, sometimes accompanied by humans. Both types are finely executed with red oxide pigment. Regarding their interpretation, the figures seem to have been associated with rainmaking and fertility concepts. ' - sys: id: 2shnvvJ5isC2AcYeUmYogI created_at: !ruby/object:DateTime 2016-07-27 07:45:20.783000000 Z updated_at: !ruby/object:DateTime 2016-07-27 08:55:24.416000000 Z content_type_id: image revision: 2 image: sys: id: 2D4MCayW9iK0Oi00QGWsIq created_at: !ruby/object:DateTime 2016-07-27 07:46:40.074000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:40.074000000 Z title: MALMPH0010008 description: url: "//images.ctfassets.net/xt8ne4gbbocd/2D4MCayW9iK0Oi00QGWsIq/278456bd2263cfcc1be94ccd74ad8437/MALMPH0010008.jpg" caption: Rock art panel with red geometric depictions ascribed to hunter-gatherers. Mphunzi. 2013,2034.20202 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3738324&partId=1 - sys: id: 1ggf46GoBKEqigYYyegCyC created_at: !ruby/object:DateTime 2016-07-27 07:45:20.069000000 Z updated_at: !ruby/object:DateTime 2016-07-27 08:56:52.968000000 Z content_type_id: chapter revision: 2 title_internal: 'Malawi: country, chapter 7' body: 'The second and more modern rock art tradition found in Malawi is represented by white figures made with white clay daubed onto rock surfaces with the finger. Associated with the agriculturalist Chewa people, the depictions usually represent zoomorphic, spread-eagled or snake-like figures which could represent mythological beings, sometimes accompanied by geometric symbols. As in the case of the schematic figures, two types of paintings have been proposed: those related to spread-eagled figures and those representing zoomorphs (animal-like figures). The paintings were made until several decades ago, as testified by depictions of cars that can be found at some sites. In this case, the interpretation of the paintings is straightforward, as the images depicted can still be related to current rituals often employing masks in a variety of shapes. The spread-eagled paintings may be associated with a Chewa girl’s initiation ceremony and would act as a mnemonic tool during the ritual, while the zoomorphic paintings may depict spirit characters of the Chewa men’s secret society, the *nyau*. In many cases, these paintings can overlap the older red paintings already existing at some sites' - sys: id: 2QkvnVmQb64kASYWcmGcge created_at: !ruby/object:DateTime 2016-07-27 07:45:20.051000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:45:20.051000000 Z content_type_id: image revision: 1 image: sys: id: 3jS61b3w2AMEwogGu2CoEI created_at: !ruby/object:DateTime 2016-07-27 07:46:39.175000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:46:39.175000000 Z title: MALCHE0010011 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3jS61b3w2AMEwogGu2CoEI/807f22eb6e58077d7a003f3e893a91a3/MALCHE0010011.jpg" caption: Rock Art panel with multitude of white human-like and reptile-like depictions, surrounded by red and white geometric signs. Chentcherere. 2013,2034.20064d © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3737077&partId=1 - sys: id: 5x1toGMQuWueQmUiYUmSa2 created_at: !ruby/object:DateTime 2016-07-27 07:45:20.009000000 Z updated_at: !ruby/object:DateTime 2016-07-27 07:45:20.009000000 Z content_type_id: chapter revision: 1 title: Chronology title_internal: 'Malawi: country, chapter 8' body: 'Although it is generally accepted that the red schematic paintings are older than the white ones, the exact chronology of these styles is still under discussion. The earliest evidence for human occupation in the region according to the archaeological record is around 2,500 years ago, and it is generally assumed that Late Stone Age hunters and gatherers made this rock art. Unfortunately no datable evidence has been found although groups of these people survived until the 1800s in Malawi. For the white paintings, chronologies are more accurate: the Chewa people are thought to have arrived to central Malawi in the 15th century, and as aforementioned, painting traditions were still alive in the mid-20th century. ' - sys: id: 5qd3rUg0MwUMKM2CkEgII created_at: !ruby/object:DateTime 2016-07-27 07:45:19.940000000 Z updated_at: !ruby/object:DateTime 2017-01-24 16:28:33.674000000 Z content_type_id: image revision: 2 image: sys: id: 2xzgTrXwqQKa0Wa0w6K06k created_at: !ruby/object:DateTime 2016-07-21 15:01:45.256000000 Z updated_at: !ruby/object:DateTime 2016-07-21 15:01:45.256000000 Z title: MALPHA0010009 description: url: "//images.ctfassets.net/xt8ne4gbbocd/2xzgTrXwqQKa0Wa0w6K06k/dbe565ce1dd67cb2835e2a9201be3e7f/MALPHA0010009.jpg" caption: Rock Art panel with multitude of white human-like and reptile-like depictions, surrounded by geometric signs. Phanga la Ngoni. 2013,2034.20346 © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3733409&partId=1 citations: - sys: id: Ao0sic2MKGOE4G66MYqkm created_at: !ruby/object:DateTime 2016-07-27 07:45:19.885000000 Z updated_at: !ruby/object:DateTime 2016-07-27 10:02:45.154000000 Z content_type_id: citation revision: 2 citation_line: "<NAME>. & <NAME>. 1978. 'Rock art and nyau symbolism in Malawi' *Malawi Government, Department of Antiquities 18.* Malawi, Montfort Press \n\nSmith, B.W. 1995. 'Rock art in south-Central Africa: A study based on the pictographsof Dedza District, Malawi and Kasama District Zambia'. Cambridge, University of Cambridge, Unpublished Ph.D. dissertation\n\nSmith, B.W. 2014. 'Chongoni rock art area' In: <NAME>. (ed) *Encyclopedia of Global Archaeology*, pp. 1448-1452. New York, Springer\n" ---<file_sep>/_coll_thematic/the-art-of-the-warrior.md --- contentful: sys: id: bl0Xb7b67YkI4CMCwGwgy created_at: !ruby/object:DateTime 2015-11-27 11:40:20.548000000 Z updated_at: !ruby/object:DateTime 2019-02-12 02:25:05.303000000 Z content_type_id: thematic revision: 8 title: The art of the warrior slug: the-art-of-the-warrior lead_image: sys: id: 69ZiYmRsreOiIUUEiCuMS6 created_at: !ruby/object:DateTime 2015-11-25 17:20:27.484000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:20:27.484000000 Z title: '2013,2034.9707' description: url: "//images.ctfassets.net/xt8ne4gbbocd/69ZiYmRsreOiIUUEiCuMS6/3b4c3bdee6c66bce875eef8014e5fe93/2013_2034.9707.jpg" chapters: - sys: id: 2YeH0ki7Pq08iGWoyeI2SY created_at: !ruby/object:DateTime 2015-11-27 12:04:20.772000000 Z updated_at: !ruby/object:DateTime 2015-12-11 11:29:10.545000000 Z content_type_id: chapter revision: 2 title_internal: 'Warrior: thematic, chapter 1' body: | Historically, much of the rock art from across northern Africa has been classified according to a particular style or ‘school’ of depictions. One such category of images, known as the Libyan Warrior School or Libyan Warrior style is found predominantly in Niger. Typically, this style “…commonly depicts human figures, mainly armed warriors; women are very rare. The style is fairly crude and the technique unsophisticated, almost invariably a rather careless pecking. The figures, almost always presented frontally with their heads quite circular, with added lobes, or mushroom-shaped, are shown according to a symmetrical schema. Various garment decorations and feathers in the hair are common, and the warrior often holds one or two throwing-spears – the bow is almost lacking – and frequently also holds by the leading rein a typical horse; foreshortened with large hindquarters” (Muzzolini, 2001:614) Termed *Libyan Warriors* by French ethnographer <NAME>, these representations have been associated with Garamantes’ raids, possibly 2,500 years ago. Thought to be descended from Berbers and Saharan pastoralists who settled in central Libya from around 1500 BC, the Garamantes developed a thriving urban centre, with flourishing trade networks from Libya to Niger. In contrast, <NAME>, a military man who led two big expeditions to the Sahara in the 1920s, proposed that these figures represent Tuareg; a people reputedly of Berber descent who live a nomadic pastoralist lifestyle. They have their own script known as Tifinagh, which is thought to have Libyan roots and which is engraved onto rocks alongside other rock art depictions. - sys: id: 3TQXxJGkAgOkCuQeq4eEEs created_at: !ruby/object:DateTime 2015-11-25 17:21:56.426000000 Z updated_at: !ruby/object:DateTime 2018-05-15 14:09:37.769000000 Z content_type_id: image revision: 2 image: sys: id: 2HdsFc1kI0ogGEmGWi82Ci created_at: !ruby/object:DateTime 2015-11-25 17:20:56.981000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:20:56.981000000 Z title: '2013,2034.11148' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2HdsFc1kI0ogGEmGWi82Ci/5c85cb71338ff7ecd923c26339a73ef5/2013_2034.11148.jpg" caption: "‘Typical’ Libyan Warrior style figure with horse. Indakatte, Western Aïr Mountains, Niger. 2013,2034.11148 © TARA/<NAME>" col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3649143&partId=1&searchText=2013,2034.11148&page=1 - sys: id: IENFM2XWMKmW02sWeYkaI created_at: !ruby/object:DateTime 2015-11-27 12:05:01.774000000 Z updated_at: !ruby/object:DateTime 2015-12-11 11:30:21.015000000 Z content_type_id: chapter revision: 2 title_internal: 'Warrior: thematic, chapter 2' body: | Libyan Warrior figures are almost exclusively located in the Aïr Mountains of Niger although can also be found in the Adrar des Iforas, north-east Mali extending into Algeria. Defining the Libyan Warrior Period chronologically is a challenge and dates are fairly fluid; the earliest dates suggested start from 5,200 years ago; it certainly coincides with the Horse period between 3,000-2,000 years ago but has also been proposed to continue throughout the Camel Period, from 2,000 years ago to present. From the sample of images we have as part of this collection it is clear that not all figures designated as falling under the umbrella term of Libyan Warrior style all share the same characteristics; there are similarities, differences and adjacencies even between what we may term a ‘typical’ representation. Of course, if these images span a period of 5,000 years then this may account for the variability in the depictions. - sys: id: 1vwQrEx1gA2USS0uSUEO8u created_at: !ruby/object:DateTime 2015-11-25 17:22:32.328000000 Z updated_at: !ruby/object:DateTime 2018-05-15 14:10:06.087000000 Z content_type_id: image revision: 2 image: sys: id: 69ZiYmRsreOiIUUEiCuMS6 created_at: !ruby/object:DateTime 2015-11-25 17:20:27.484000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:20:27.484000000 Z title: '2013,2034.9707' description: url: "//images.ctfassets.net/xt8ne4gbbocd/69ZiYmRsreOiIUUEiCuMS6/3b4c3bdee6c66bce875eef8014e5fe93/2013_2034.9707.jpg" caption: "‘Typical’ Libyan Warrior style figure with antelope. Iwellene, Northern Aïr Mountains, Niger. 2013,2034.9707 © TARA/<NAME>" col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3649767&partId=1&searchText=2013,2034.9707&page=1 - sys: id: 13aC6FIWtQAauy2SYC6CQu created_at: !ruby/object:DateTime 2015-11-27 12:05:26.289000000 Z updated_at: !ruby/object:DateTime 2015-11-27 12:05:26.289000000 Z content_type_id: chapter revision: 1 title_internal: 'Warrior: thematic, chapter 3' body: However, for the majority of figures their posture is remarkably similar even though objects of material culture and the types of garments they wear may show more diversity. The overriding feature is that figures are positioned frontally with arms bent and raised, often displaying splayed fingers. In some cases figures hold weapons and shields, but some do not. Some wear obviously elaborate headdresses, but in others the features look more coiffure-like. Selected garments are decorated with geometric patterns, others are plain; not all wear items of personal ornamentation. Certainly, not all figures are associated with horses, as typically characterised. Moreover, rather than all being described as unsophisticated or careless, many are executed showing great technique and skill. So how do we start to make sense of this contradiction between consistency and variation? - sys: id: 4thny4IiHKW66c2sGySMqE created_at: !ruby/object:DateTime 2015-11-25 17:28:05.405000000 Z updated_at: !ruby/object:DateTime 2018-05-15 14:15:37.257000000 Z content_type_id: image revision: 3 image: sys: id: 4Mq2eZY2bKogMqoCmu6gmW created_at: !ruby/object:DateTime 2015-11-25 17:20:40.548000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:20:40.548000000 Z title: '2013,2034.11167' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4Mq2eZY2bKogMqoCmu6gmW/9916aa4ecde51858768639f010a0442e/2013_2034.11167.jpg" caption: Infissak, Western Aïr Mountains, Niger. 2013,2034.11167 © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3648925&partId=1&searchText=2013,2034.11167&page=1 - sys: id: 1D7OVEK1eouQAsg6e6esS4 created_at: !ruby/object:DateTime 2015-11-27 12:05:50.702000000 Z updated_at: !ruby/object:DateTime 2015-12-11 11:36:43.690000000 Z content_type_id: chapter revision: 3 title_internal: 'Warrior: thematic, chapter 4' body: A criticism of Saharan rock art research, in comparison to that which has focused on other parts of Africa, is an under-theorisation of how the art links to past ethnic, archaeological or other identities (Smith,2013:156). This is tricky when dealing with past societies which were potentially nomadic, and where their archaeological remains are scarce. However, recent anthropological research may inform our thinking in this area. A member of the Wodaabe cultural group (nomadic cattle-herders and traders in the Sahel) on seeing a photograph of a Libyan-Warrior engraving and noting the dress and earrings told photographer <NAME> that it represents a woman performing a traditional greeting dance with arms outstretched and about to clap (Coulson and Campbell,2001:210). - sys: id: 6GvLgKrVXaSIQaAMECeE2m created_at: !ruby/object:DateTime 2015-11-25 17:31:34.914000000 Z updated_at: !ruby/object:DateTime 2018-05-15 14:15:11.171000000 Z content_type_id: image revision: 2 image: sys: id: 18c47Fe9jeoIi4CouE8Eya created_at: !ruby/object:DateTime 2015-11-25 17:20:10.453000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:20:10.453000000 Z title: '2013,2034.11133' description: url: "//images.ctfassets.net/xt8ne4gbbocd/18c47Fe9jeoIi4CouE8Eya/189da8bf1c84d7f95b532cf59780fe82/2013_2034.11133.jpg" caption: Two Libyan Warrior style figures, Western Aïr Mountains, Niger. 2013,2034.11133 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3649155&partId=1&searchText=2013,2034.11133&page=1 - sys: id: 4wQK9fpysE0GEaGYOEocws created_at: !ruby/object:DateTime 2015-11-27 12:06:27.167000000 Z updated_at: !ruby/object:DateTime 2018-05-15 14:17:33.313000000 Z content_type_id: chapter revision: 3 title_internal: 'Warrior: thematic, chapter 5' body: "Such a comment suggests that local ethnographies might assist in an understanding of more recent rock art, that not all figures described as Libyan-Warrior may necessarily be the same, and indeed that women may not be as rare as previously documented. In fact, the Wodaabe have been noted to resemble figures in other Saharan rock art contexts (see article on Hairdressing in the Acacus).\n\nIf we accept that some of these representations share affinities with the Wodaabe then thinking about this category of images from an ethnographic perspective may prove productive. Moreover, the British Museum’s existing ethnographic collections are simultaneously a useful resource by which we can potentially add more meaning to the rock art images.\n\nThe Wodaabe belong to the Fulani people, numbering 20 million and currently living across eighteen countries. The Wodaabe comprise 2-3% of the Fulani cultural group, still live as true nomads and are considered to have the most traditional culture of all the Fulani (Bovin,2001:13).\t\n" - sys: id: 2oNDIVZY2cY6y2ACUykYiW created_at: !ruby/object:DateTime 2015-11-25 17:31:55.456000000 Z updated_at: !ruby/object:DateTime 2018-05-15 14:26:02.339000000 Z content_type_id: image revision: 2 image: sys: id: 2klydX5Lbm6sGIUO8cCuow created_at: !ruby/object:DateTime 2015-11-25 17:20:40.581000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:20:40.581000000 Z title: Wodaabe description: url: "//images.ctfassets.net/xt8ne4gbbocd/2klydX5Lbm6sGIUO8cCuow/af221201c757ffe51e741300ffaefcba/Wodaabe.jpg" caption: Wodaabe men preparing for Gerewol ceremony ©<NAME>, Wikimedia Commons col_link: https://commons.wikimedia.org/wiki/File:Flickr_-_Dan_Lundberg_-_1997_%5E274-33_Gerewol_contestants.jpg - sys: id: 3SOhBsJLQACesg4wogaksm created_at: !ruby/object:DateTime 2015-11-27 12:07:09.983000000 Z updated_at: !ruby/object:DateTime 2015-11-27 12:07:09.983000000 Z content_type_id: chapter revision: 1 title_internal: 'Warrior: thematic, chapter 6' body: "The Wodaabe have become particularly well-known in the West through visual anthropology, because of their emphasis on cultivating male personal beauty and adornment. Men invest enormous amounts of time in personal artistic expression; much more so than women. Anthropologists have documented the constant checking of Wodaabe men in their mirrors; a Wodaabe man will not even go out among the cows in the morning until he has checked and tidied himself. They spend hours every day on their appearance and have been described as styling themselves like “living paintings” and “living statues” (Bovin, 2001:72). Symmetry plays a particularly significant part in Wodaabe culture and is reflected in all their artistic expressions. Symmetry stands for culture, asymmetry stands for nature. Culture is order and nature is disorder (Bovin,2001:17). Everyday Wodaabe life is imbued with artistic expression, whereby “every individual is an active creator, decorator and performer (Bovin, 2001:15).\n\nSo, how might we see Wodaabe cultural traits reflected in the Libyan-Warrior figures?\n\nPlumage is often depicted on these Warrior figures and for the most part is assumed to simply be part of the warrior regalia. The ostrich feather, a phallic symbol in Wodaabe culture, is an important element in male adornment and is carefully placed in the axis of symmetry in the middle of a man’s turban, worn during dancing ceremonies (Bovin, 2001:41). Music and dancing are typical of Fulani traditions, characterized by group singing and accompanied by clapping, stomping and bells. The feathers in the British Museum’s collections are known to be dance ornaments, worn during particular ceremonies. \n" - sys: id: 4AsNsHJ1n2USWMU68cIUko created_at: !ruby/object:DateTime 2015-11-27 11:46:03.474000000 Z updated_at: !ruby/object:DateTime 2018-05-15 14:30:37.659000000 Z content_type_id: image revision: 4 image: sys: id: 6QT0CdFAgoISmsuUk6u4OW created_at: !ruby/object:DateTime 2015-11-27 11:54:37.045000000 Z updated_at: !ruby/object:DateTime 2015-11-27 11:54:37.045000000 Z title: Af2005,04.6 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6QT0CdFAgoISmsuUk6u4OW/02489b2a4374bdb0a92ad9684f6120f4/Af2005_04.6_1.jpg" caption: Wodaabe dancing feather from the British Museum collections. Af2005,04.6 © Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=1585897&partId=1&searchText=Af2005%2c04.6&view=list&page=1 - sys: id: 5z7EqYMmFaI0Eom6AAgu6i created_at: !ruby/object:DateTime 2015-11-27 11:57:19.817000000 Z updated_at: !ruby/object:DateTime 2018-05-15 14:28:41.984000000 Z content_type_id: image revision: 2 image: sys: id: 10pBS62m3eugyAkY8iQYGs created_at: !ruby/object:DateTime 2015-11-25 17:20:48.548000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:20:48.548000000 Z title: '2013,2034.9037' description: url: "//images.ctfassets.net/xt8ne4gbbocd/10pBS62m3eugyAkY8iQYGs/b54aab41922ff6690ca59533afddeb84/2013_2034.9037.jpg" caption: Libyan Warrior figure showing symmetrical plumage from Eastern Aïr Mountains, Niger. 2013,2034.9037 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3636108&partId=1&searchText=2013,2034.9037&page=1 - sys: id: 1UmQD1rR0IISqKmGe4UWYs created_at: !ruby/object:DateTime 2015-11-27 11:47:12.062000000 Z updated_at: !ruby/object:DateTime 2018-05-15 14:28:08.133000000 Z content_type_id: image revision: 3 image: sys: id: 5oL3JD0PbaEMMyu4mA0oGw created_at: !ruby/object:DateTime 2015-11-27 11:54:37.053000000 Z updated_at: !ruby/object:DateTime 2015-11-27 11:54:37.053000000 Z title: Af2005,04.20 1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/5oL3JD0PbaEMMyu4mA0oGw/72bb636538c36d21c62fef5628556238/Af2005_04.20_1.jpg" caption: Wodaabe dancing feather from the British Museum collections. Af2005,04.20 © Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=1585792&partId=1&searchText=Af2005%2c04.20&view=list&page=1 - sys: id: 45NYo7UU5ymOCYiqEYyQQO created_at: !ruby/object:DateTime 2015-11-27 12:07:34.816000000 Z updated_at: !ruby/object:DateTime 2015-11-27 12:07:34.816000000 Z content_type_id: chapter revision: 1 title_internal: 'Warrior: thematic, chapter 7' body: One of the recurring features of the Warrior engravings is the round discs that seem to be suspended from a figure’s arm or shoulder. Historically, these have been interpreted as shields, which one might expect a warrior to be carrying and in part this may be the case. - sys: id: 55JXs6mmfCoM6keQuwSeKA created_at: !ruby/object:DateTime 2015-11-27 11:59:13.850000000 Z updated_at: !ruby/object:DateTime 2018-05-15 14:31:16.112000000 Z content_type_id: image revision: 2 image: sys: id: 3s0PrjlXlS2QwMKMk0giog created_at: !ruby/object:DateTime 2015-11-25 17:20:56.985000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:20:56.985000000 Z title: '2013,2034.9554' description: url: "//images.ctfassets.net/xt8ne4gbbocd/3s0PrjlXlS2QwMKMk0giog/bef0019b59e2abe3ba3e29a4377eedd0/2013_2034.9554.jpg" caption: Warrior style figure holding ‘shields’. Eastern Aïr Mountains, Niger. 2013,2034.9554 © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3639988&partId=1&searchText=2013,2034.9554&page=1 - sys: id: 2UL4zsEuwgekwI0ugSOSok created_at: !ruby/object:DateTime 2015-11-27 11:59:49.961000000 Z updated_at: !ruby/object:DateTime 2018-05-15 14:31:41.776000000 Z content_type_id: image revision: 2 image: sys: id: 3XjtbP2JywoCw8Qm0O8iKo created_at: !ruby/object:DateTime 2015-11-25 17:20:48.555000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:20:48.555000000 Z title: '2013,2034.9600' description: url: "//images.ctfassets.net/xt8ne4gbbocd/3XjtbP2JywoCw8Qm0O8iKo/fc0ccf0eb00a563da9a60276c87bbc11/2013_2034.9600.jpg" caption: Warrior style figure holding ‘shields’. Eastern Aïr Mountains, Niger. 2013,2034.9600 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3639940&partId=1&searchText=2013,2034.9600&page=1 - sys: id: 64MCgMHx60M8e0GSCaM2qm created_at: !ruby/object:DateTime 2015-11-27 12:07:53.749000000 Z updated_at: !ruby/object:DateTime 2015-11-27 12:07:53.749000000 Z content_type_id: chapter revision: 1 title_internal: 'Warrior: thematic, chapter 8' body: However, others may represent shoulder bags or flat baskets which are used as vessel covers or food trays; both of which are vital items in a nomadic lifestyle. Alternatively, they may represent calabashes. Wodaabe women measure their worldly wealth in calabashes and can acquire many in a lifetime, mostly ornamental to be displayed only on certain ceremonial occasions. If some of these depictions are not necessarily men or warriors then what have been considered shields may in fact represent some other important item of material culture. - sys: id: 78Ks1B0PPUA8YIm0ugMkQK created_at: !ruby/object:DateTime 2015-11-27 12:00:47.553000000 Z updated_at: !ruby/object:DateTime 2018-05-15 14:33:27.671000000 Z content_type_id: image revision: 2 image: sys: id: 5SDdxljduwuQggsuWcYUCA created_at: !ruby/object:DateTime 2015-11-25 17:20:48.583000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:20:48.583000000 Z title: Af,B47.19 description: url: "//images.ctfassets.net/xt8ne4gbbocd/5SDdxljduwuQggsuWcYUCA/eeb48a1ec8550bb4e1622317e5b7cea0/Af_B47.19.jpg" caption: Photograph of three Fulani male children 'dressed up for a ceremonial dance'. They are carrying shoulder-bags and holding sticks, and the male at right has flat basket impaled on stick. Rural setting. Af,B47.19 © Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=1410664&partId=1&searchText=Af,B47.19&page=1 - sys: id: 5nvXXoq4Baa0IwOmMSiUkI created_at: !ruby/object:DateTime 2015-11-27 12:08:13.833000000 Z updated_at: !ruby/object:DateTime 2015-11-27 12:08:13.833000000 Z content_type_id: chapter revision: 1 title_internal: 'Warrior: thematic, chapter 9' body: Engraved figures are often depicted with geometric patterning across their torso which may reflect traditional garments. This armless Wodaabe vest is decorated with abstract geometric combinations; patterns similar to those found on amulets, bags, containers and other artefacts as well as rock art. - sys: id: 1Huul8DwMcACSECuGoASE2 created_at: !ruby/object:DateTime 2015-11-27 12:01:35.826000000 Z updated_at: !ruby/object:DateTime 2018-05-15 14:35:18.268000000 Z content_type_id: image revision: 2 image: sys: id: 1PmWIHnxq0cAESkGiiWCkK created_at: !ruby/object:DateTime 2015-11-25 17:20:48.554000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:20:48.554000000 Z title: '7,2023.1' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1PmWIHnxq0cAESkGiiWCkK/51912ac1b7bffafe18fbbbb48a253fe9/7_2023.1.jpg" caption: Wodaabe vest, Niger. 2007,2023.1 ©Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3372277&partId=1&searchText=2007%2c2023.1&view=list&page=1 - sys: id: GT1E1E6FMc04CaQQUEuG6 created_at: !ruby/object:DateTime 2015-11-27 12:02:14.003000000 Z updated_at: !ruby/object:DateTime 2018-05-15 14:37:15.633000000 Z content_type_id: image revision: 2 image: sys: id: lz2F9O4kSWoi2g68csckA created_at: !ruby/object:DateTime 2015-11-25 17:20:48.580000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:20:48.580000000 Z title: '2013,2034.9016' description: url: "//images.ctfassets.net/xt8ne4gbbocd/lz2F9O4kSWoi2g68csckA/97f7a9fbec98c4af224273fbd3f7e9a5/2013_2034.9016.jpg" caption: Eastern Aïr Mountains, Niger. 2013,2034.9016 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3636134&partId=1&searchText=2013%2c2034.9016&&page=1 - sys: id: MH7tazL1u0ocyy6ysc8ci created_at: !ruby/object:DateTime 2015-11-27 12:08:38.359000000 Z updated_at: !ruby/object:DateTime 2015-11-27 12:08:38.359000000 Z content_type_id: chapter revision: 1 title_internal: 'Warrior: thematic, chapter 10' body: |- There is also a consensus within Wodaabe society about beauty and ugliness; what makes something beautiful or indeed ugly generally is agreed upon, there is a commonality of taste. This may account for the paradox of why there is individuality within a corpus of images that inherently are comparable (Bovin,2001:16). As nomads, Wodaabe do not identify themselves by place or territory as such, but a Wodaabe’s body is a repository of culture to mark them out against nature. Culture is not seen as an unessential indulgence but as an imperative necessity, it is part of one’s survival and existence in an inhospitable environment. We may speculate that rock art images may be seen as a way of stamping culture on nature; markers of socialised space. - sys: id: 5f7LkndYMoCiE0C6cYI642 created_at: !ruby/object:DateTime 2015-11-27 12:02:44.521000000 Z updated_at: !ruby/object:DateTime 2018-05-15 15:04:54.162000000 Z content_type_id: image revision: 4 image: sys: id: 4S1bl6LKUEKg0mMiQMoS2i created_at: !ruby/object:DateTime 2015-11-25 17:20:33.489000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:20:33.489000000 Z title: Gerewol description: url: "//images.ctfassets.net/xt8ne4gbbocd/4S1bl6LKUEKg0mMiQMoS2i/77678da7ac7b9573cfdfdcc9222b4187/Gerewol.jpg" caption: Wodaabe participants in the Gerewol beauty contest. ©<NAME> via Wikimedia Commons col_link: https://commons.wikimedia.org/wiki/File:1997_274-5_Gerewol.jpg - sys: id: 2s5eLxURwgEKUGYiCc62MM created_at: !ruby/object:DateTime 2015-11-27 12:03:20.752000000 Z updated_at: !ruby/object:DateTime 2018-05-15 14:40:40.756000000 Z content_type_id: image revision: 2 image: sys: id: 3as8UfaNIk22iQwu2uccsO created_at: !ruby/object:DateTime 2015-11-25 17:20:57.016000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:20:57.016000000 Z title: '2013,2034.9685' description: url: "//images.ctfassets.net/xt8ne4gbbocd/3as8UfaNIk22iQwu2uccsO/bef9cc4c65f13f394c4c6c03fa665aab/2013_2034.9685.jpg" caption: Four Warrior style figures, Eastern Aïr Mountains, Niger. 2013,2034.9685 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3644735&partId=1&searchText=2013,2034.9685&page=1 - sys: id: 4c37ixkB72GaCAkSYwGmSI created_at: !ruby/object:DateTime 2015-11-27 12:08:59.408000000 Z updated_at: !ruby/object:DateTime 2015-11-27 12:08:59.408000000 Z content_type_id: chapter revision: 1 title_internal: 'Warrior: thematic, chapter 11' body: This brief review was motivated, in part, by the underlying problems inherent in the categorisation of visual culture. Historically assigned classifications are not fixed and armed with current knowledge across a range of resources we may provide further insights into these enigmatic representations. Obviously, a much more systematic study of this category known as Libyan-Warrior figures needs to be undertaken to determine their distribution and the similarities and differences between depictions across sites. Additionally, care must be taken making connections with a cultural group whose material culture has changed over the course of the twentieth century. Nevertheless, it seems the category of Libyan-Warrior figures is an area that is ripe for more intensive investigation. citations: - sys: id: 2YpbTzVtq8og44KCIYKySK created_at: !ruby/object:DateTime 2015-11-25 17:17:36.606000000 Z updated_at: !ruby/object:DateTime 2015-11-25 17:17:36.606000000 Z content_type_id: citation revision: 1 citation_line: | <NAME>. 2001. *Nomads Who Cultivate Beauty*. Uppsala: Nordiska Afrikainstitutet <NAME> and <NAME>. 2001. *African Rock Art: Paintings and Engravings on Stone*. New York: <NAME> <NAME>. 2001. ‘Saharan Africa’ In Whitley, D. (ed) *Handbook of Rock Art Research*: pp.605-636. Walnut Creek: Altamira Press <NAME>. 2013. Rock art research in Africa. In: Lane, P. & Mitchell, P. (eds) *Handbook of African Archaeology*: 145-162. Oxford: Oxford University Press. background_images: - sys: id: 4ICv2mLYykaUs2K6sI600e created_at: !ruby/object:DateTime 2015-12-07 19:16:46.680000000 Z updated_at: !ruby/object:DateTime 2015-12-07 19:16:46.680000000 Z title: NIGNAM0010007 description: url: "//images.ctfassets.net/xt8ne4gbbocd/4ICv2mLYykaUs2K6sI600e/175a170bba1f5856e70c2bb59a88e28f/NIGNAM0010007.jpg" - sys: id: 4sWbJZXtCUKKqECk24wOwi created_at: !ruby/object:DateTime 2015-12-07 19:16:46.673000000 Z updated_at: !ruby/object:DateTime 2015-12-07 19:16:46.673000000 Z title: NIGEAM0070022 description: url: "//images.ctfassets.net/xt8ne4gbbocd/4sWbJZXtCUKKqECk24wOwi/63797d84c9f0c89db25bd2f2cebaa21b/NIGEAM0070022.jpg" ---<file_sep>/_coll_thematic/rock-art-in-central-and-east-africa.md --- contentful: sys: id: 5HZTuIVN8AASS4ikIea6m6 created_at: !ruby/object:DateTime 2017-12-19 12:27:08.508000000 Z updated_at: !ruby/object:DateTime 2017-12-19 12:27:08.508000000 Z content_type_id: thematic revision: 1 title: Introduction to rock art in central and eastern Africa slug: rock-art-in-central-and-east-africa lead_image: sys: id: 3esXNapo5GOWIKSImcY4QW created_at: !ruby/object:DateTime 2015-11-25 18:56:43.836000000 Z updated_at: !ruby/object:DateTime 2017-12-15 17:01:05.082000000 Z title: '2013,2034.12982' description: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3776396 url: "//images.ctfassets.net/xt8ne4gbbocd/3esXNapo5GOWIKSImcY4QW/6436b2034659eccb953844b21a400070/2013_2034.12982.jpg" chapters: - sys: id: 4ln5fQLq2saMKsOA4WSAgc created_at: !ruby/object:DateTime 2015-11-25 19:09:33.580000000 Z updated_at: !ruby/object:DateTime 2015-12-11 11:17:25.155000000 Z content_type_id: chapter revision: 4 title: Central and East Africa title_internal: 'East Africa: regional, chapter 1' body: |- Central Africa is dominated by vast river systems and lakes, particularly the Congo River Basin. Characterised by hot and wet weather on both sides of the equator, central Africa has no regular dry season, but aridity increases in intensity both north and south of the equator. Covered with a forest of about 400,000 m² (1,035,920 km²), it is one of the greenest parts of the continent. The rock art of central Africa stretches from the Zambezi River to the Angolan Atlantic coast and reaches as far north as Cameroon and Uganda. Termed the ‘schematic rock art zone’ by <NAME> (1959), it is dominated by finger-painted geometric motifs and designs, thought to extend back many thousands of years. Eastern Africa, from the Zambezi River Valley to Lake Turkana, consists largely of a vast inland plateau with the highest elevations on the continent, such as Mount Kilimanjaro (5,895m above sea level) and Mount Kenya (5,199 m above sea level). Twin parallel rift valleys run through the region, which includes the world’s second largest freshwater lake, Lake Victoria. The climate is atypical of an equatorial region, being cool and dry due to the high altitude and monsoon winds created by the Ethiopian Highlands. The rock art of eastern Africa is concentrated on this plateau and consists mainly of paintings that include animal and human representations. Found mostly in central Tanzania, eastern Zambia and Malawi; in comparison to the widespread distribution of geometric rock art, this figurative tradition is much more localised, and found at just a few hundred sites in a region of less than 100km in diameter. - sys: id: 4nyZGLwHTO2CK8a2uc2q6U created_at: !ruby/object:DateTime 2015-11-25 18:57:48.121000000 Z updated_at: !ruby/object:DateTime 2017-12-15 17:05:00.916000000 Z content_type_id: image revision: 2 image: sys: id: 3esXNapo5GOWIKSImcY4QW created_at: !ruby/object:DateTime 2015-11-25 18:56:43.836000000 Z updated_at: !ruby/object:DateTime 2017-12-15 17:01:05.082000000 Z title: '2013,2034.12982' description: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3776396 url: "//images.ctfassets.net/xt8ne4gbbocd/3esXNapo5GOWIKSImcY4QW/6436b2034659eccb953844b21a400070/2013_2034.12982.jpg" caption: <NAME>. 2013,2034.12982 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3776396 - sys: id: 1OvIWDPyXaCO2gCWw04s06 created_at: !ruby/object:DateTime 2015-11-25 19:10:23.723000000 Z updated_at: !ruby/object:DateTime 2015-12-11 11:18:19.325000000 Z content_type_id: chapter revision: 2 title_internal: 'East Africa: regional, chapter 2' body: This collection from Central and East Africa comprises rock art from Kenya, Uganda and Tanzania, as well as the Horn of Africa; although predominantly paintings, engravings can be found in most countries. - sys: id: 4JqI2c7CnYCe8Wy2SmesCi created_at: !ruby/object:DateTime 2015-11-25 19:10:59.991000000 Z updated_at: !ruby/object:DateTime 2016-10-17 13:34:14.653000000 Z content_type_id: chapter revision: 3 title: History of research title_internal: 'East Africa: regional, chapter 3' body: |- The rock art of East Africa, in particular the red paintings from Tanzania, was extensively studied by Mary and <NAME> in the 1930s and 1950s. <NAME> observed Sandawe people of Tanzania making rock paintings in the mid-20th century, and on the basis of oral traditions argued that the rock art was made for three main purposes: casual art; magic art (for hunting purposes or connected to health and fertility) and sacrificial art (to appease ancestral spirits). Subsequently, during the 1970s Fidelis Masao and <NAME> recorded numerous sites, classifying the art in broad chronological and stylistic categories, proposing tentative interpretations with regard to meaning. There has much debate and uncertainty about Central African rock art. The history of the region has seen much mobility and interaction of cultural groups and understanding how the rock art relates to particular groups has been problematic. Pioneering work in this region was undertaken by <NAME> in central Malawi in the early 1920s, <NAME> visited Zambia in 1936 and attempted to provide a chronological sequence and some insight into the meaning of the rock art. Since the 1950s (Clarke, 1959), archaeologists have attempted to situate rock art within broader archaeological frameworks in order to resolve chronologies, and to categorise the art with reference to style, colour, superimposition, subject matter, weathering, and positioning of depictions within the panel (Phillipson, 1976). Building on this work, our current understanding of rock in this region has been advanced by <NAME> (1995, 1997, 2001) with his work in Zambia and Malawi. - sys: id: 35HMFoiKViegWSY044QY8K created_at: !ruby/object:DateTime 2015-11-25 18:59:25.796000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:51:25.789000000 Z content_type_id: image revision: 5 image: sys: id: 6KOxC43Z9mYCuIuqcC8Qw0 created_at: !ruby/object:DateTime 2015-11-25 18:57:00.077000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:57:00.077000000 Z title: '2013,2034.17450' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6KOxC43Z9mYCuIuqcC8Qw0/e25141d07f483d0100c4cf5604e3e525/2013_2034.17450.jpg" caption: This painting of a large antelope is possibly one of the earliest extant paintings. <NAME> believes similar paintings could be more than 28,000 years old. 2013,2034.17450 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3711689 - sys: id: 1dSBI9UNs86G66UGSEOOkS created_at: !ruby/object:DateTime 2015-12-09 11:56:31.754000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:50:18.203000000 Z content_type_id: chapter revision: 5 title: East African Rock Art title_internal: Intro to east africa, chapter 3.5 body: "Rock art of East Africa consists mainly of paintings, most of which are found in central Tanzania, and are fewer in number in eastern Zambia and Malawi; scholars have categorised them as follows:\n\n*__Red Paintings__*: \nRed paintings can be sub-divided into those found in central Tanzania and those found stretching from Zambia to the Indian Ocean.\nTanzanian red paintings include large, naturalistic animals with occasional geometric motifs. The giraffe is the most frequently painted animal, but antelope, zebra, elephant, rhino, felines and ostrich are also depicted. Later images show figures with highly distinctive stylised human head forms or hairstyles and body decoration, sometimes in apparent hunting and domestic scenes. The Sandawe and Hadza, hunter-gatherer groups, indigenous to north-central and central Tanzania respectively, claim their ancestors were responsible for some of the later art.\n\nThe area in which Sandawe rock art is found is less than 100km in diameter and occurs at just a few hundred sites, but corresponds closely to the known distribution of this group. There have been some suggestions that Sandawe were making rock art early into the 20th century, linking the art to particular rituals, in particular simbo; a trance dance in which the Sandawe communicate with the spirit world by taking on the power of an animal. The art displays a range of motifs and postures, features that can be understood by reference to simbo and to trance experiences; such as groups of human figures bending at the waist (which occurs during the *simbo* dance), taking on animal features such as ears and tails, and floating or flying; reflecting the experiences of those possessed in the dance." - sys: id: 7dIhjtbR5Y6u0yceG6y8c0 created_at: !ruby/object:DateTime 2015-11-25 19:00:07.434000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:51:51.887000000 Z content_type_id: image revision: 5 image: sys: id: 1fy9DD4BWwugeqkakqWiUA created_at: !ruby/object:DateTime 2015-11-25 18:57:11.188000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:57:11.188000000 Z title: '2013,2034.16849' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1fy9DD4BWwugeqkakqWiUA/9f8f1330c6c0bc0ff46d744488daa152/2013_2034.16849.jpg" caption: Three schematic figures formed by the use of multiple thin parallel lines. The shape and composition of the heads suggests either headdresses or elaborate hairstyles. Kondoa, Tanzania. 2013,2034.16849 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3709812 - sys: id: 1W573pi2Paks0iA8uaiImy created_at: !ruby/object:DateTime 2015-11-25 19:12:00.544000000 Z updated_at: !ruby/object:DateTime 2015-12-11 11:21:09.647000000 Z content_type_id: chapter revision: 8 title_internal: 'East Africa: regional, chapter 4' body: "Zambian rock art does not share any similarities with Tanzanian rock art and can be divided into two categories; animals (with a few depictions of humans), and geometric motifs. Animals are often highly stylised and superimposed with rows of dots. Geometric designs include, circles, some of which have radiating lines, concentric circles, parallel lines and ladder shapes. Predominantly painted in red, the remains of white pigment is still often visible. <NAME>on (1976) proposed that the naturalistic animals were earlier in date than geometric designs. Building on Phillipson’s work, <NAME> studied ethnographic records and demonstrated that geometric motifs were made by women or controlling the weather.\n\n*__Pastoralist paintings__*: \nPastoralist paintings are rare, with only a few known sites in Kenya and other possible sites in Malawi. Usually painted in black, white and grey, but also in other colours, they include small outlines, often infilled, of cattle and are occasional accompanied by geometric motifs. Made during the period from 3,200 to 1,800 years ago the practice ceased after Bantu language speaking people had settled in eastern Africa. Similar paintings are found in Ethiopia but not in southern Africa, and it has been assumed that these were made by Cushitic or Nilotic speaking groups, but their precise attribution remains unclear (Smith, 2013:154).\n" - sys: id: 5jReHrdk4okicG0kyCsS6w created_at: !ruby/object:DateTime 2015-11-25 19:00:41.789000000 Z updated_at: !ruby/object:DateTime 2017-12-15 17:10:04.890000000 Z content_type_id: image revision: 3 image: sys: id: 1hoZEK3d2Oi8iiWqoWACo created_at: !ruby/object:DateTime 2015-11-25 18:56:43.848000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:56:43.848000000 Z title: '2013,2034.13653' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1hoZEK3d2Oi8iiWqoWACo/1a1adcfad5d5a1cf0a341316725d61c4/2013_2034.13653.jpg" caption: Two red bulls face right. Mt Elgon, Kenya. 2013,2034.13653. © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3700058 - sys: id: 7rFAK9YoBqYs0u0EmCiY64 created_at: !ruby/object:DateTime 2015-11-25 19:00:58.494000000 Z updated_at: !ruby/object:DateTime 2017-12-15 17:11:37.760000000 Z content_type_id: image revision: 3 image: sys: id: 3bqDVyvXlS0S6AeY2yEmS8 created_at: !ruby/object:DateTime 2015-11-25 18:56:43.880000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:56:43.880000000 Z title: '2013,2034.13635' description: url: "//images.ctfassets.net/xt8ne4gbbocd/3bqDVyvXlS0S6AeY2yEmS8/c9921f3d8080bcef03c96c6b8f1b0323/2013_2034.13635.jpg" caption: Two cattle with horns in twisted perspective. Mt Elgon, Kenya. 2013,2034.13635. © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3698905 - sys: id: 1tX4nhIUgAGmyQ4yoG6WEY created_at: !ruby/object:DateTime 2015-11-25 19:14:33.823000000 Z updated_at: !ruby/object:DateTime 2015-11-25 19:14:33.823000000 Z content_type_id: chapter revision: 1 title_internal: 'East Africa: regional, chapter 5' body: |- *__Late White Paintings__*: Commonly painted in white, or off-white with the fingers, so-called ‘Late White’ depictions include quite large crudely rendered representations of wild animals, mythical animals, human figures and numerous geometric motifs. These paintings are attributed to Bantu language speaking, iron-working farmers who entered eastern Africa about 2,000 years ago from the west on the border of Nigeria and Cameroon. Moving through areas occupied by the Batwa it is thought they learned the use of symbols painted on rock, skin, bark cloth and in sand. Chewa peoples, Bantu language speakers who live in modern day Zambia and Malawi claim their ancestors made many of the more recent paintings which they used in rites of passage ceremonies. - sys: id: 35dNvNmIxaKoUwCMeSEO2Y created_at: !ruby/object:DateTime 2015-11-25 19:01:26.458000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:52:15.838000000 Z content_type_id: image revision: 4 image: sys: id: 6RGZZQ13qMQwmGI86Ey8ei created_at: !ruby/object:DateTime 2015-11-25 18:57:11.188000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:57:11.188000000 Z title: '2013,2034.16786' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6RGZZQ13qMQwmGI86Ey8ei/6d37a5bed439caf7a1223aca27dc27f8/2013_2034.16786.jpg" caption: Under a long narrow granite overhang, Late White designs including rectangular grids, concentric circles and various ‘square’ shapes. 2013,2034.16786 © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3709608 - sys: id: 2XW0X9BzFCa8u2qiKu6ckK created_at: !ruby/object:DateTime 2015-11-25 19:01:57.959000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:53:21.559000000 Z content_type_id: image revision: 4 image: sys: id: 1UT4r6kWRiyiUIYSkGoACm created_at: !ruby/object:DateTime 2015-11-25 18:57:11.138000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:57:11.138000000 Z title: '2013,2034.16797' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1UT4r6kWRiyiUIYSkGoACm/fe915c6869b6c195d55b5ef805df7671/2013_2034.16797.jpg" caption: A monuments guard stands next to Late White paintings attributed to Bantu speaking farmers in Tanzania, probably made during the last 700 years. 2013,2034.16797 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3709628 - sys: id: 3z28O8A58AkgMUocSYEuWw created_at: !ruby/object:DateTime 2015-11-25 19:15:04.047000000 Z updated_at: !ruby/object:DateTime 2015-11-25 19:15:04.047000000 Z content_type_id: chapter revision: 1 title_internal: 'East Africa: regional, chapter 6' body: |- *__Meat-feasting paintings__*: Meat-feasting shelters exist from northern Tanzania through Kenya to Lake Turkana, and are places where Maa-speaking initiated men, who are not permitted to eat meat in their homes, gather to kill and feast on animals, predominantly cattle. The term Maa relates to a group of closely related Eastern Nilotic languages, which historically dominated the east African hinterland; and today is spoken by around a million people. During or after feasting, symbols of the animals that had been eaten were painted on the shelter ceiling in white or less often red. Maa speakers brand their cattle and camels with symbols that signify the lineage of their owners, but may also indicate if an animal has been treated for a particular disease. Different symbols may be used for male and female animals. Over the centuries, because the depictions are on the ceiling of meat feasting rock shelters, and because sites are used even today, a build-up of soot has obscured or obliterated the paintings. Unfortunately, few have been recorded or mapped. - sys: id: 1yjQJMFd3awKmGSakUqWGo created_at: !ruby/object:DateTime 2015-11-25 19:02:23.595000000 Z updated_at: !ruby/object:DateTime 2017-12-15 17:19:11.619000000 Z content_type_id: image revision: 3 image: sys: id: p4E0BRJzossaus6uUUkuG created_at: !ruby/object:DateTime 2015-11-25 18:56:49.743000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:56:49.743000000 Z title: '2013,2034.13004' description: url: "//images.ctfassets.net/xt8ne4gbbocd/p4E0BRJzossaus6uUUkuG/13562eee76ac2a9efe8c0d12e62fa23a/2013_2034.13004.jpg" caption: Huge granite boulder with Ndorobo man standing before a rock overhang used for meat-feasting. Laikipia, Kenya. 2013,2034. 13004. © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3700175 - sys: id: 6lgjLZVYrY606OwmwgcmG2 created_at: !ruby/object:DateTime 2015-11-25 19:02:45.427000000 Z updated_at: !ruby/object:DateTime 2017-12-15 17:20:14.877000000 Z content_type_id: image revision: 3 image: sys: id: 1RLyVKKV8MA4KEk4M28wqw created_at: !ruby/object:DateTime 2015-11-25 18:57:11.150000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:57:11.150000000 Z title: '2013,2034.13018' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1RLyVKKV8MA4KEk4M28wqw/044529be14a590fd1d0da7456630bb0b/2013_2034.13018.jpg" caption: This symbol is probably a ‘brand’ used on cattle that were killed and eaten at a Maa meat feast. Laikipia, Kenya. 2013,2034.13018 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3700193 - sys: id: 5UQc80DUBiqqm64akmCUYE created_at: !ruby/object:DateTime 2015-11-25 19:15:34.582000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:53:53.936000000 Z content_type_id: chapter revision: 4 title: Central African Rock Art title_internal: 'East Africa: regional, chapter 7' body: The rock art of central Africa is attributed to hunter-gatherers known as Batwa. This term is used widely in eastern central and southern Africa to denote any autochthonous hunter-gatherer people. The rock art of the Batwa can be divided into two categories which are quite distinctive stylistically from the Tanzanian depictions of the Sandawe and Hadza. Nearly 3,000 sites are currently known from within this area. The vast majority, around 90%, consist of finger-painted geometric designs; the remaining 10% include highly stylised animal forms (with a few human figures) and rows of finger dots. Both types are thought to date back many thousands of years. The two traditions co-occur over a vast area of eastern and central Africa and while often found in close proximity to each other are only found together at a few sites. However, it is the dominance of geometric motifs that make this rock art tradition very distinctive from other regions in Africa. - sys: id: 4m51rMBDX22msGmAcw8ESw created_at: !ruby/object:DateTime 2015-11-25 19:03:40.666000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:54:25.415000000 Z content_type_id: image revision: 4 image: sys: id: 2MOrR79hMcO2i8G2oAm2ik created_at: !ruby/object:DateTime 2015-11-25 18:56:49.737000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:56:49.737000000 Z title: '2013,2034.15306' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2MOrR79hMcO2i8G2oAm2ik/86179e84233956e34103566035c14b76/2013_2034.15306.jpg" caption: Paintings in red and originally in-filled in white cover the underside of a rock shelter roof. The art is attributed to central African Batwa; the age of the paintings is uncertain. Lake Victoria, Uganda. 2013,2034.15306 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3691242 - sys: id: 5rNOG3568geMmIEkIwOIac created_at: !ruby/object:DateTime 2015-11-25 19:16:07.130000000 Z updated_at: !ruby/object:DateTime 2015-11-25 19:16:19.722000000 Z content_type_id: chapter revision: 2 title_internal: 'East Africa: regional, chapter 8' body: "*__Engravings__*:\nThere are a few engravings occurring on inland plateaus but these have elicited little scientific interest and are not well documented. \ Those at the southern end of Lake Turkana have been categorised into two types: firstly, animals, human figures and geometric forms and also geometric forms thought to involve lineage symbols.\nIn southern Ethiopia, near the town of Dillo about 300 stelae, some of which stand up to two metres in height, are fixed into stones and mark grave sites. People living at the site ask its spirits for good harvests. \n" - sys: id: LrZuJZEH8OC2s402WQ0a6 created_at: !ruby/object:DateTime 2015-11-25 19:03:59.496000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:54:51.576000000 Z content_type_id: image revision: 5 image: sys: id: 1uc9hASXXeCIoeMgoOuO4e created_at: !ruby/object:DateTime 2015-11-25 18:57:11.176000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:57:11.176000000 Z title: '2013,2034.16206' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1uc9hASXXeCIoeMgoOuO4e/09a7504449897509778f3b9455a42f8d/2013_2034.16206.jpg" caption: Group of anthropomorphic stelae with carved faces. <NAME>, Southern Ethiopia. 2013,2034.16206 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3703754 - sys: id: 7EBTx1IjKw6y2AUgYUkAcm created_at: !ruby/object:DateTime 2015-11-25 19:16:37.210000000 Z updated_at: !ruby/object:DateTime 2015-12-11 11:22:04.007000000 Z content_type_id: chapter revision: 2 title_internal: 'East Africa: regional, chapter 9' body: In the Sidamo region of Ethiopia, around 50 images of cattle are engraved in bas-relief on the wall of a gorge. All the engravings face right and the cows’ udders are prominently displayed. Similar engravings of cattle, all close to flowing water, occur at five other sites in the area, although not in such large numbers. - sys: id: 6MUkxUNFW8oEK2aqIEcee created_at: !ruby/object:DateTime 2015-11-25 19:04:34.186000000 Z updated_at: !ruby/object:DateTime 2017-12-19 12:22:24.891000000 Z content_type_id: image revision: 3 image: sys: id: PlhtduNGSaOIOKU4iYu8A created_at: !ruby/object:DateTime 2015-11-25 18:56:43.849000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:56:43.849000000 Z title: '2013,2034.16235' description: url: "//images.ctfassets.net/xt8ne4gbbocd/PlhtduNGSaOIOKU4iYu8A/7625c8a21caf60046ea73f184e8b5c76/2013_2034.16235.jpg" caption: Around 50 images of cattle are engraved in bas-relief into the sandstone wall of a gorge in the Sidamo region of Ethiopia. 2013,2034.16235 © TARA/David Coulson col_link: http://bit.ly/2hMU0vm - sys: id: 6vT5DOy7JK2oqgGK8EOmCg created_at: !ruby/object:DateTime 2015-11-25 19:17:53.336000000 Z updated_at: !ruby/object:DateTime 2015-12-11 11:25:38.678000000 Z content_type_id: chapter revision: 3 title: Rock art in the Horn of Africa title_internal: 'East Africa: regional, chapter 10' body: "The Horn of Africa has historically been a crossroads area between the Eastern Sahara, the Subtropical regions to the South and the Arabic Peninsula. These mixed influences can be seen in many archaeological and historical features throughout the region, the rock art being no exception. Since the early stages of research in the 1930s, a strong relationship between the rock art in Ethiopia and the Arabian Peninsula was detected, leading to the establishment of the term *Ethiopian-Arabian* rock art by Pavel Červiček in 1971. This research thread proposes a progressive evolution from naturalism to schematism, ranging from the 4th-3rd millennium BC to the near past. Although the *Ethiopian-Arabian* proposal is still widely accepted and stylistic similarities between the rock art of Somalia, Ethiopia, Yemen or Saudi Arabia are undeniable, recent voices have been raised against the term because of its excessive generalisation and lack of operability. In addition, recent research to the south of Ethiopia have started to discover new rock art sites related to those found in Uganda and Kenya.\n\nRegarding the main themes of the Horn of Africa rock art, cattle depictions seem to have been paramount, with cows and bulls depicted either isolated or in herds, frequently associated with ritual scenes which show their importance in these communities. Other animals – zebus, camels, felines, dogs, etc. – are also represented, as well as rows of human figures, and fighting scenes between warriors or against lions. Geometric symbols are also common, usually associated with other depictions; and in some places they have been interpreted as tribal or clan marks. Both engraving and painting is common in most regions, with many regional variations. \n" - sys: id: 4XIIE3lDZYeqCG6CUOYsIG created_at: !ruby/object:DateTime 2015-11-25 19:04:53.913000000 Z updated_at: !ruby/object:DateTime 2019-03-19 14:55:12.472000000 Z content_type_id: image revision: 4 image: sys: id: 3ylztNmm2cYU0GgQuW0yiM created_at: !ruby/object:DateTime 2015-11-25 18:57:11.155000000 Z updated_at: !ruby/object:DateTime 2015-11-25 18:57:11.155000000 Z title: '2013,2034.15749' description: url: "//images.ctfassets.net/xt8ne4gbbocd/3ylztNmm2cYU0GgQuW0yiM/3be240bf82adfb5affc0d653e353350b/2013_2034.15749.jpg" caption: Painted roof of rock shelter showing decorated cows and human figures. <NAME>, Somaliland. 2013,2034.15749 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3691391 - sys: id: 2IKYx0YIVOyMSwkU8mQQM created_at: !ruby/object:DateTime 2015-11-25 19:18:28.056000000 Z updated_at: !ruby/object:DateTime 2015-12-11 11:26:13.401000000 Z content_type_id: chapter revision: 2 title_internal: 'East Africa: regional, chapter 11' body: |- Rock art in the Horn of Africa faces several challenges. One of them is the lack of consolidated chronologies and absolute dating for the paintings and engravings. Another is the uneven knowledge of rock art throughout the region, with research often affected by political unrest. Therefore, distributions of rock art in the region are steadily growing as research is undertaken in one of the most interactive areas in East Africa. The rock art of Central and East Africa is one of the least documented and well understood of the corpus of African rock art. However, in recent years scholars have undertaken some comprehensive reviews of existing sites and surveys of new sites to open up the debates and more fully understand the complexities of this region. citations: - sys: id: 7d9bmwn5kccgO2gKC6W2Ys created_at: !ruby/object:DateTime 2015-11-25 19:08:04.014000000 Z updated_at: !ruby/object:DateTime 2017-12-19 12:24:18.659000000 Z content_type_id: citation revision: 2 citation_line: "<NAME>. 1996. ‘Cultural Patterns in the Rock Art of Central Tanzania.’ in *The Prehistory of Africa*. XIII International Congress of Prehistoric and Protohistoric Sciences Forli-Italia-8/14 September.\n\nČerviček, P. 1971. ‘Rock paintings of Laga Oda (Ethiopia)’ in *Paideuma*, 17, pp.121-136.\n\nClark, <NAME>. 1954. *The Prehistoric Cultures of the Horn of Africa*. New York: Octagon Press.\n\nClark, J.C.D. 1959. ‘Rock Paintings of Northern Rhodesia and Nyasaland’, in Summers, R. (ed.) *Prehistoric Rock Art of the Federation of Rhodesia & Nyasaland*: Glasgow: National Publication Trust, pp.163- 220.\n\nJoussaume, R. (ed.) 1995. Tiya, *l’Ethiopie des mégalithes : du biface à l’art rupestre dans la Corne de l’Afrique*. Association des publications chauvinoises (A.P.C.), Chauvigny.\n\nLeakey, M. 1983. *Africa’s Vanishing Art – The Rock Paintings of Tanzania*. London: Hamish Hamilton Ltd.\n\nMasao, F.T. 1979. *The Later Stone Age and the Rock Paintings of Central Tanzania*. Wiesbaden: Franz Steiner Verlag. \n\nNamono, Catherine. 2010. *A contextual interpretive approach to the rock art of Uganda*. Unpublished PhD Thesis. Johannesburg: University of Witwatersrand\n\nPhillipson, D.W. 1976. ‘The Rock Paintings of Eastern Zambia’, in *The Prehistory of Eastern Zambia: Memoir 6 of the british Institute in Eastern Africa*. Nairobi.\n\nSmith B.W. (1995), Rock art in south-Central Africa: A study based on the pictographs of Dedza District, Malawi and Kasama District Zambia. dissertation. Cambridge: University of Cambridge, Unpublished Ph.D. dissertation.\n\n<NAME>. (1997), Zambia’s ancient rock art: The paintings of Kasama. Zambia: The National Heritage Conservation Commission of Zambia.\n\n<NAME>. (2001), Forbidden images: Rock paintings and the Nyau secret society of Central Malaŵi and Eastern Zambia. *African Archaeological Review*18(4): 187–211.\n\nSmith, Benjamin. 2013, ‘Rock art research in Africa; in In: Lane, P. & Mitchell, P. (eds) *Handbook of African Archaeology*. Oxford: Oxford University Press, pp.145-162.\n\nTen Raa, E. 1974. ‘A record of some prehistoric and some recent Sandawe rock paintings’ in *Tanzania Notes and Records* 75, pp.9-27." background_images: - sys: id: 4aeKk2gBTiE6Es8qMC4eYq created_at: !ruby/object:DateTime 2015-12-07 19:42:27.348000000 Z updated_at: !ruby/object:DateTime 2017-12-19 12:25:55.914000000 Z title: '2013,2034.1298' description: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3592557 url: "//images.ctfassets.net/xt8ne4gbbocd/4aeKk2gBTiE6Es8qMC4eYq/31cde536c4abf1c0795761f8e35b255c/2013_2034.1298.jpg" - sys: id: 6DbMO4lEBOU06CeAsEE8aA created_at: !ruby/object:DateTime 2015-12-07 19:41:53.440000000 Z updated_at: !ruby/object:DateTime 2017-12-19 12:26:40.898000000 Z title: '2013,2034.15749' description: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3691391 url: "//images.ctfassets.net/xt8ne4gbbocd/6DbMO4lEBOU06CeAsEE8aA/9fc2e1d88f73a01852e1871f631bf4ff/2013_2034.15749.jpg" ---<file_sep>/_coll_country/libya/fighting-cats.md --- breadcrumbs: - label: Countries url: "../../" - label: Libya url: "../" layout: featured_site contentful: sys: id: 5tEidWPQmAyy22u8wGEwC4 created_at: !ruby/object:DateTime 2015-11-25 15:32:46.632000000 Z updated_at: !ruby/object:DateTime 2015-12-07 20:53:06.792000000 Z content_type_id: featured_site revision: 3 title: Fighting cats, Libya slug: fighting-cats chapters: - sys: id: 1Bkxdxu3Pay6SEYMy8s08e created_at: !ruby/object:DateTime 2015-11-25 15:27:52.971000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:27:52.971000000 Z content_type_id: chapter revision: 1 title_internal: 'Libya: featured site, chapter 1' body: Running from the Red Sea to the Atlantic Ocean, the Sahara is by far the world's largest hot desert. It covers over 3,500,000 square miles (9,000,000 sq. km), a tenth of the whole African Continent. Yet we know it was not always so. Archaeological and geological research has shown that the Sahara has undergone major climatic changes since the end of the last Ice Age (c. 10,000 BC). During this period, rain was far more abundant, and vast areas of the current desert were a savannah. By around 4,200 BC, changes in the rainfall and seasonal patterns led to a gradual desertification of the Sahara into an arid expanse. The analysis of archaeological sites, animal bones and preserved vegetal remains tell us of a greener world, where some of the earliest attempts at domestication of animals and rudimentary farming took place. - sys: id: 1bjII0uFguycUGI0skGqS2 created_at: !ruby/object:DateTime 2015-11-25 15:24:17.896000000 Z updated_at: !ruby/object:DateTime 2017-01-09 14:44:36.006000000 Z content_type_id: image revision: 2 image: sys: id: 23Sckf5aOU4E8WOkg8yoIG created_at: !ruby/object:DateTime 2015-11-25 15:23:42.352000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:23:42.352000000 Z title: '2013,2034.2555' description: url: "//images.ctfassets.net/xt8ne4gbbocd/23Sckf5aOU4E8WOkg8yoIG/5ad5ab2517694ac7ebacdd58be96b254/2013_2034.2555.jpg" caption: 'View of the now dried-up riverbed at Wadi Mathendous, Messak Settafet, Libya. 2013,2034.2555 © <NAME>/TARA ' col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?assetId=1494150&objectId=3579237&partId=1 - sys: id: 4eUSc4QsRW2Mey02S8a2IM created_at: !ruby/object:DateTime 2015-11-25 15:28:11.936000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:28:11.936000000 Z content_type_id: chapter revision: 1 title_internal: 'Libya: featured site, chapter 2' body: |- Little is known about the people who lived in the Sahara thousands of years ago; however, through rock art, we can discern who they may have been and what images were important to them. Throughout the desert, rock art engravings and paintings depict an earlier story of the Sahara: the wild animals that lived there; the cattle herds that provided food and labour; their daily activities and beliefs are all displayed in caves and cliffs, valleys or plateaus. The Messak Settafet is one of these places. Situated in the Sahara, it is a large plateau running southwest to northeast through the Libyan province of Fezzan, near the borders of Algeria and Niger. Both plateaus are crossed by numerous wadis (dry riverbeds) that run to the east, flanked by cliffs filled with tens of thousands of rock art depictions, including some of the oldest engravings in the Sahara. Rich with depictions of the savannah, the rock art shows buffaloes, crocodiles, ostriches or hippopotami, all of which tells us of a wetter Sahara thousands of years ago. It is difficult to determine the motives of the people that created these images. There are many theories about why these people created rock art, what exactly is depicted and what the images meant to that group. One area of particular research interest is the depiction of mythical beings, therianthropic figures (part human part animal) and anthropomorphic animals (the personification of animals in human forms). Were these religious images? Cultural folklore? Or simply images pleasing to a group or culture? - sys: id: 6ggzCnM132qAMoMao64uG4 created_at: !ruby/object:DateTime 2015-11-25 15:25:04.359000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:25:04.359000000 Z content_type_id: image revision: 1 image: sys: id: xe9mLFNrG0Ga6yUIoQycG created_at: !ruby/object:DateTime 2015-11-25 15:23:42.433000000 Z updated_at: !ruby/object:DateTime 2017-12-15 14:29:10.261000000 Z title: '2013,2034.2761' description: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3584758 url: "//images.ctfassets.net/xt8ne4gbbocd/xe9mLFNrG0Ga6yUIoQycG/de7f087f96da7f9814d89ce25c7c4b44/2013_2034.2761.jpg" caption: Frontal view of the Fighting Cats. Wadi Mathendous, Messak Settafet, Libya. 2013,2034.2761 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3584758&partId=1&museumno=2013,2034.2761&page=1 - sys: id: DcfkeeG0wKKEIAMACYiOY created_at: !ruby/object:DateTime 2015-11-25 15:28:29.814000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:28:29.814000000 Z content_type_id: chapter revision: 1 title_internal: 'Libya: featured site, chapter 3' body: 'Deep in the Messak Settafet is a site that has intrigued researchers for decades: the image known as ‘Fighting Cats’. This iconic engraving shows two confronted, long-tailed figures standing on their hindquarters, with legs and arms partially outstretched against each other, as if fighting. The engravings are placed on an outcrop, as if they were looking down across the rest of the wadi, with several other engravings acting as milestones leading up to them. They are in an imposing position overlooking the valley.' - sys: id: 5OhCYs4J4Q0cWSgwEWUSSU created_at: !ruby/object:DateTime 2015-11-25 15:25:43.199000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:25:43.199000000 Z content_type_id: image revision: 1 image: sys: id: 3UCMJpOah2ayA8keMYsGkU created_at: !ruby/object:DateTime 2015-11-25 15:23:42.353000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:23:42.353000000 Z title: '2013,2034.2740' description: url: "//images.ctfassets.net/xt8ne4gbbocd/3UCMJpOah2ayA8keMYsGkU/eb104c365e0f4a5e3b5f792bde70cb3d/2013_2034.2740.jpg" caption: Sandstone cliffs, with the Fighting Cats faintly visible at the top. <NAME>, <NAME>, Libya. 2013,2034.2740 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3584701&partId=1&museumno=2013,2034.2740&page=1 - sys: id: 3aWDA5PA5is0yS4uQSKweS created_at: !ruby/object:DateTime 2015-11-25 15:28:48.305000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:29:09.496000000 Z content_type_id: chapter revision: 2 title_internal: 'Libya: featured site, chapter 4' body: The technical quality of the engravings is exceptional, with deeply outlined and carefully polished bodies and carved cupules within their heads to depict eyes. Claws were also marked, maybe to reinforce the idea of fighting. The specific type of animal depicted is subject to debate among scholars. Some have described them as monkeys or mythological blends of monkeys and men. Their pointed ears could also identify them as cat-like figures, although most probably they were the representation of mythical beings, considering their prominence above all other figures in this area. A polished line comes out from the waist of both figures to join four small ostriches, depicted between them, which often accompany rock art in this region. - sys: id: 2hR3so8KWQKAWS0oqWiGKm created_at: !ruby/object:DateTime 2015-11-25 15:26:11.459000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:26:11.459000000 Z content_type_id: image revision: 1 image: sys: id: 5WH8hIWyZOI0QWe0SyAkC8 created_at: !ruby/object:DateTime 2015-11-25 15:23:42.337000000 Z updated_at: !ruby/object:DateTime 2017-12-15 14:08:22.574000000 Z title: '2013,2034.2756' description: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3584749 url: "//images.ctfassets.net/xt8ne4gbbocd/5WH8hIWyZOI0QWe0SyAkC8/69ac9764bc2af640ff92531ee90422a4/2013_2034.2756.jpg" caption: General view of the Fighting Cats showing nearby engravings. <NAME>, <NAME>, Libya. 2013,2034.2756 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3584749&partId=1&museumno=2013,2034.2756&page=1 - sys: id: smcYmLtACOMwSYasYoYI0 created_at: !ruby/object:DateTime 2015-11-25 15:29:29.887000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:29:29.887000000 Z content_type_id: chapter revision: 1 title: title_internal: 'Libya: featured site, chapter 5' body: Several other engravings are found throughout the wadi. In its lower part to the right, another cat-like or monkey figure has been depicted, although in this case it has only been outlined. A small, unidentified quadruped has been represented to the left of its head. At the right side of the boulder, a fourth figure has been depicted, almost identical to those of the main scene, but with part of its arms unpolished, as if left unfinished. - sys: id: 6oRVe3BTckeksmGWA8gwyq created_at: !ruby/object:DateTime 2015-11-25 15:26:47.347000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:26:47.347000000 Z content_type_id: image revision: 1 image: sys: id: 1xfjGHyp6wMGQuKQikCeMo created_at: !ruby/object:DateTime 2015-11-25 15:23:42.353000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:23:42.353000000 Z title: '2013,2034.2768' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1xfjGHyp6wMGQuKQikCeMo/46389e1547a0da49bc8ed43c897e1f8a/2013_2034.2768.jpg" caption: Detail of engraved woman inside cat to the right. <NAME>, Messak Settafet, Libya. 2013,2034.2768 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3584772&partId=1&museumno=2013,2034.2768&page=1 - sys: id: 2T0VuynIPK2CYgyck6uSK8 created_at: !ruby/object:DateTime 2015-11-25 15:29:50.338000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:29:50.338000000 Z content_type_id: chapter revision: 1 title_internal: 'Libya: featured site, chapter 6' body: Besides its impressive position in the landscape, their expressivity and complex interpretation, the Fighting Cats keep a secret within. On the polished body of the figure to the left a small, delicate figure of a woman was shallowly engraved. Hair, fingers and breasts were carefully depicted, as well as an unidentified symbol placed at the bottom of the figure, which could have a fertility-related meaning. The difference in style and technique may point to the woman as a later addition to the panel, taking advantage of the polished surface, but respecting the main scene. - sys: id: 3aPHfOC1lSUW68GuUkOAQK created_at: !ruby/object:DateTime 2015-11-25 15:27:21.916000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:27:21.916000000 Z content_type_id: image revision: 1 image: sys: id: 1kO0IImYVGOk0oeQg6sqWm created_at: !ruby/object:DateTime 2015-11-25 15:23:42.352000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:23:42.352000000 Z title: '2013,2034.2769' description: url: "//images.ctfassets.net/xt8ne4gbbocd/1kO0IImYVGOk0oeQg6sqWm/631f5025d103fadbbcd966634cddc15f/2013_2034.2769.jpg" caption: Second pair of fighting cats. <NAME>, <NAME>, Libya. 2013,2034.2769 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3584770&partId=1&museumno=2013,2034.2769&page=1 - sys: id: 6GXWm1a2LSU0qg0iQEIeGw created_at: !ruby/object:DateTime 2015-11-25 15:30:37.290000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:30:37.290000000 Z content_type_id: chapter revision: 1 title_internal: 'Libya: featured site, chapter 7' body: |- Another example of fighting cats has been found nearby, although it is neither so carefully made nor in such a prominent place. The similarity is, however, astonishing, and we may wonder if this second pair of beings could be a copy of the first pair, thus reflecting its symbolic importance in the people’s collective imagination. As is often the case with rock art, the interpretation of these images remains up for discussion. Given the care taken to engrave the images, their technical quality and their dominant position in the landscape, we can gather that these images potentially had deep meaning for the people who created them thousands of years ago, and were possibly meant to be a symbolic as well as a physical landmark for travellers and local people alike. Although the original purpose and meaning have long since been lost, the expressive power of the engravings still remains, allowing us to gain a small view into the world of the people that lived in the Sahara thousands of years ago, when it was a sprawling green savannah. background_images: - sys: id: 5WH8hIWyZOI0QWe0SyAkC8 created_at: !ruby/object:DateTime 2015-11-25 15:23:42.337000000 Z updated_at: !ruby/object:DateTime 2017-12-15 14:08:22.574000000 Z title: '2013,2034.2756' description: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3584749 url: "//images.ctfassets.net/xt8ne4gbbocd/5WH8hIWyZOI0QWe0SyAkC8/69ac9764bc2af640ff92531ee90422a4/2013_2034.2756.jpg" - sys: id: 23Sckf5aOU4E8WOkg8yoIG created_at: !ruby/object:DateTime 2015-11-25 15:23:42.352000000 Z updated_at: !ruby/object:DateTime 2015-11-25 15:23:42.352000000 Z title: '2013,2034.2555' description: url: "//images.ctfassets.net/xt8ne4gbbocd/23Sckf5aOU4E8WOkg8yoIG/5ad5ab2517694ac7ebacdd58be96b254/2013_2034.2555.jpg" ---<file_sep>/_coll_thematic/rhinos-in-rock-art.md --- contentful: sys: id: 570TteJLy8EmE4SYAGKcQw created_at: !ruby/object:DateTime 2017-06-14 17:36:35.946000000 Z updated_at: !ruby/object:DateTime 2017-06-21 13:55:43.874000000 Z content_type_id: thematic revision: 5 title: Rhinos in rock art slug: rhinos-in-rock-art lead_image: sys: id: 4uVUj08mRGOCkmK64q66MA created_at: !ruby/object:DateTime 2016-09-26 14:46:35.956000000 Z updated_at: !ruby/object:DateTime 2019-02-12 02:01:17.553000000 Z title: '2013,2034.20476' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3730556&partId=1&searchText=NAMDMT0010010&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/4uVUj08mRGOCkmK64q66MA/c1c895d4f72a2260ae166ab9c2148daa/NAMDMT0010010.jpg" chapters: - sys: id: 4kAwRERjIIQ4wSkS6y2i8c created_at: !ruby/object:DateTime 2017-05-17 10:44:14.414000000 Z updated_at: !ruby/object:DateTime 2017-05-17 10:44:14.414000000 Z content_type_id: chapter revision: 1 title_internal: 'Rhinos: thematic, chapter 1' body: Around 30,000 years ago, in the hot, arid environment of the Huns Mountains in southern Namibia, modern humans painted images of animals, including rhinoceros, onto plaques of stone. A couple of thousand years earlier, in the cold, harsh tundra-like conditions of the Ardèche in south-central France, modern humans were also painting images of rhinoceros onto cave walls. The oldest scientifically dated rock art in Africa and Europe may be 8000 km apart but coincide both temporally and in subject matter. One of the oldest images that humans selected to depict was the formidable rhinoceros. The choice of subject matter in rock art depictions was not simply based on the presence or abundance of a particular species; rather they were conveying messages about the significance of an animal. - sys: id: 2hohzbPqWMU2IGWEeSo2ma created_at: !ruby/object:DateTime 2017-05-17 11:12:19.181000000 Z updated_at: !ruby/object:DateTime 2017-05-17 11:12:19.181000000 Z content_type_id: image revision: 1 image: sys: id: 37CIIcnQfC2GwQ6wUuAymc created_at: !ruby/object:DateTime 2017-05-17 11:10:25.789000000 Z updated_at: !ruby/object:DateTime 2017-05-17 11:11:03.005000000 Z title: Rhino Rifkin description: '' url: "//images.ctfassets.net/xt8ne4gbbocd/37CIIcnQfC2GwQ6wUuAymc/299bc822c6f3a17ca6db005e0868218d/Rhino_Rifkin.jpg" caption: "'Drawn’ outline depiction of what conceivably represents a rhinoceros. black rhinoceros (Diceros bicornis) (© courtesy of Rifkin 2015)" - sys: id: 5Ld8vmtLAAGcImkQaySck2 created_at: !ruby/object:DateTime 2017-05-17 11:45:29.394000000 Z updated_at: !ruby/object:DateTime 2017-05-17 11:45:29.394000000 Z content_type_id: image revision: 1 image: sys: id: 2ztUAznRiwc0qiE4iUIQGc created_at: !ruby/object:DateTime 2017-05-17 11:44:42.255000000 Z updated_at: !ruby/object:DateTime 2017-05-17 11:44:42.255000000 Z title: Rhinocéros grotte Chauvet description: url: "//images.ctfassets.net/xt8ne4gbbocd/2ztUAznRiwc0qiE4iUIQGc/5958ce98b795f63e5ee49806275209b7/Rhinoc__ros_grotte_Chauvet.jpg" caption: Rhinoceros from Chauvet Cave, Ardeche, France (© Inocybe/Wikimedia Commons) - sys: id: 6jA55SyPksGMQIYmYceMkQ created_at: !ruby/object:DateTime 2017-05-17 11:57:32.852000000 Z updated_at: !ruby/object:DateTime 2017-06-14 17:19:12.877000000 Z content_type_id: chapter revision: 2 title_internal: 'Rhinos: thematic, chapter 2' body: "Representations of rhinoceros in rock art can be found throughout the African continent and while their meaning is not always known, they are often depicted using great artistry, skill and knowledge of animal physiology. However, research undertaken in southern Africa has demonstrated that in some contexts rhinoceros may be incorporated into the cosmological belief systems of the San&#124;Bushman people (several culturally linked groups of indigenous people of southern Africa who were traditionally hunter-gatherers).\n\n" - sys: id: 7gBWq5BdnOYUGm6O4KK4u0 created_at: !ruby/object:DateTime 2017-05-17 12:18:12.142000000 Z updated_at: !ruby/object:DateTime 2017-05-17 12:18:12.142000000 Z content_type_id: image revision: 1 image: sys: id: 6hihVIK9s46Q00SG4Y2QMw created_at: !ruby/object:DateTime 2017-05-17 12:18:16.078000000 Z updated_at: !ruby/object:DateTime 2017-05-17 12:18:16.078000000 Z title: 2013.2034.19234 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6hihVIK9s46Q00SG4Y2QMw/a0b92ad1db5c66639a005036bfacb809/2013.2034.19234_small.jpeg" caption: The engraver of this charging rhinoceros captured its bulk and power in a simple pecked outline, South Africa. 2013,2034.19234 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3731815&partId=1 - sys: id: 1LYEwVNEogggeMOcuQUOQW created_at: !ruby/object:DateTime 2017-05-17 12:20:14.827000000 Z updated_at: !ruby/object:DateTime 2017-05-17 12:21:52.334000000 Z content_type_id: chapter revision: 2 title_internal: 'Rhinos: thematic, chapter 3' body: "Southern Africa is home to two species of rhinoceros - the white or square-lipped rhinoceros and the black or hook-lipped rhinoceros - both of which we see depicted in the rock art.\n\nWhite rhinos are the second largest land mammal after the elephant. Their name comes from the Afrikaans word “weit”, which means wide and refers to the animal’s muzzle. Adult males can reach 1.85m in height and can weigh up to 3.6 tonnes. Females are considerably smaller at about half the weight of an adult male. Their territory covers South Africa, Namibia, Zimbabwe and Kenya. They live in herds of up to 14 animals and are quick and agile animals being able to run up to 50 km/h. \n" - sys: id: 4dbpdyyr2UAk4yKAomw42I created_at: !ruby/object:DateTime 2017-05-17 12:23:12.939000000 Z updated_at: !ruby/object:DateTime 2017-05-17 12:23:12.939000000 Z content_type_id: image revision: 1 image: sys: id: 3YQnGwVj8swySQIqgcs0wq created_at: !ruby/object:DateTime 2017-05-17 12:23:18.441000000 Z updated_at: !ruby/object:DateTime 2017-05-17 12:23:18.441000000 Z title: White Rhino description: url: "//images.ctfassets.net/xt8ne4gbbocd/3YQnGwVj8swySQIqgcs0wq/d969ab42d8540b0c37aa0a6a0cfa8c59/White_Rhino.jpg" caption: White rhinoceros (© Ryan Harvey/Wikimedia Commons) - sys: id: 3VgqyhGcViwkwCoI88W4Ii created_at: !ruby/object:DateTime 2017-05-17 12:24:23.783000000 Z updated_at: !ruby/object:DateTime 2017-05-17 12:24:23.783000000 Z content_type_id: chapter revision: 1 title_internal: 'Rhinos: thematic, chapter 4' body: The black rhino is smaller than the white rhino, although adults can still reach 1.5 metres in height and weigh in at 1.4 tonnes. The black rhino has a reputation for being extremely aggressive, and will not hesitate to charge at a perceived threat. Black rhinos were once common throughout sub-Saharan Africa. However, persistent hunting by European settlers saw their numbers quickly decline, and they currently number around 5,000. The species is currently found in patchy distribution throughout South Africa, Namibia, Zimbabwe and Kenya. - sys: id: 4TnBbYK1SEueSCAIemKOcA created_at: !ruby/object:DateTime 2017-05-17 12:26:52.247000000 Z updated_at: !ruby/object:DateTime 2017-05-17 12:26:52.247000000 Z content_type_id: image revision: 1 image: sys: id: 6m2Q1HCGT6Q2cey00sKGmu created_at: !ruby/object:DateTime 2017-05-17 12:26:24.400000000 Z updated_at: !ruby/object:DateTime 2017-05-17 12:26:24.400000000 Z title: Black Rhino description: url: "//images.ctfassets.net/xt8ne4gbbocd/6m2Q1HCGT6Q2cey00sKGmu/92caad1c13d4bbefe80a5a94aef9844e/Black_Rhino.jpg" caption: Black rhinoceros (© Ikiwaner/Wikimedia Commons) - sys: id: 4Z8zcElzjOCyO6iOasMuig created_at: !ruby/object:DateTime 2017-05-17 12:32:11.389000000 Z updated_at: !ruby/object:DateTime 2017-05-17 12:32:11.389000000 Z content_type_id: chapter revision: 1 title_internal: 'Rhinos: thematic, chapter 5' body: | In both species, a layer of fat sits between the hide and the flesh of the animal and in the white rhinoceros this can be up to or exceed a thickness of 50mm. It is well known that San&#124;Bushmen believed the fat around the heart of the eland contained high levels of supernatural potency, and like the eland, they believed the rhinoceros to be especially potent animals (Ouzman, 1996:45) Rhinoceros in rock art imagery are both painted and engraved, but the prevalence of engraved images in southern African rock art is pronounced. Rhinoceros are well represented, even dominant, at numerous engraving sites in the Free State, Gauteng, Northern Cape and North West provinces of South Africa and at numerous Namibian sites (Ouzman, 1996:42) - sys: id: 2Z9GGCpzCMk4sCKKYsmaU8 created_at: !ruby/object:DateTime 2017-05-17 12:34:15.621000000 Z updated_at: !ruby/object:DateTime 2017-05-17 12:34:15.621000000 Z content_type_id: image revision: 1 image: sys: id: 4uVUj08mRGOCkmK64q66MA created_at: !ruby/object:DateTime 2016-09-26 14:46:35.956000000 Z updated_at: !ruby/object:DateTime 2019-02-12 02:01:17.553000000 Z title: '2013,2034.20476' description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3730556&partId=1&searchText=NAMDMT0010010&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/4uVUj08mRGOCkmK64q66MA/c1c895d4f72a2260ae166ab9c2148daa/NAMDMT0010010.jpg" caption: Block- pecked rhinoceros. Twyfelfontein, Namibia. 2013,2034.20476 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3730556 - sys: id: 2S3mX9yJfqoMka8QoWUqOE created_at: !ruby/object:DateTime 2017-05-17 14:02:05.953000000 Z updated_at: !ruby/object:DateTime 2017-05-17 14:02:05.953000000 Z content_type_id: image revision: 1 image: sys: id: 3BoFYuFzPWSOE2ewYOSWm2 created_at: !ruby/object:DateTime 2017-05-17 14:01:24.022000000 Z updated_at: !ruby/object:DateTime 2017-05-17 14:01:24.022000000 Z title: 2013.2034.20450 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3BoFYuFzPWSOE2ewYOSWm2/edb6148c3f4435bee2f57c72e79f6b20/2013.2034.20450.jpg" caption: Painted rhinoceros in the Tsodilo Hills, Botswana. 2013,2034.20450 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3729906&partId=1 - sys: id: 4KLSIsvlmEMeOsCo8SGOQA created_at: !ruby/object:DateTime 2017-05-17 14:47:15.208000000 Z updated_at: !ruby/object:DateTime 2017-05-17 14:47:15.208000000 Z content_type_id: chapter revision: 1 title_internal: 'Rhinos: thematic, chapter 6' body: "Most rock art researchers consider the engravings of San/Bushmen, like paintings, to have been influenced by shamanism (Ouzman, 1996:36). Both painted and engraved images share certain distinctive traits which suggest that both art forms were the result of a single belief system. These shared features include: a selected range of animals, unusual body postures in human figures, complex ‘scenes’ and non-realistic features on both animals and humans such as the addition or absence of limbs, conflation of human and animal morphology and exaggerated attributes (Ouzman, 1996:36) These features are critical to our understanding of the images as they are inextricably tied in to San&#124;Bushman belief systems.\n\nThere are very few references to rhinoceros in San&#124;Bushman ethnography. However, what does exist indicates that rhinoceros were of supernatural importance to certain groups of San&#124;Bushmen (Ouzman, 1996:42). One particular site named <NAME> in South Africa, is primarily known for its numerous engravings of rhinoceros and may have been chosen as an engraving site because rhinoceros were known to have frequented the site. \n\n<NAME> (Zion’s Hill) a low hill of less than nine metres in height is an important archaeological and rock art site in the North West province. It is scattered with more than 450 engraved dolerite boulders with the seasonal Thlakajeng River running 350 metres south-west containing numerous waterholes. The hill is bounded by 27 standing stones that have been rubbed smooth by rhinoceros after wallowing in the muddy waterholes of the river (Ouzman, 1996:40). Interestingly, one third of all the stones that he been rubbed by rhinoceros are also engraved (Lewis-Williams & Blundell, 1998:111).\n" - sys: id: 1IlptwbzFmIaSkIWWAqw8U created_at: !ruby/object:DateTime 2017-05-17 15:02:36.385000000 Z updated_at: !ruby/object:DateTime 2017-05-17 15:02:36.385000000 Z content_type_id: image revision: 1 image: sys: id: 6eRgAs6SRy6USaYCssaOKM created_at: !ruby/object:DateTime 2017-05-17 15:01:57.460000000 Z updated_at: !ruby/object:DateTime 2017-05-17 15:01:57.460000000 Z title: 2013.2034.18579 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6eRgAs6SRy6USaYCssaOKM/39136c061c79d1300e5dae2624e4fae2/2013.2034.18579.jpg" caption: View near the summit of the hill and location of rock art site, looking into the village. Thaba Sione. 2013,2034.18579 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3730570&partId=1 - sys: id: 2Moq7jFKLCc60oamksKUgU created_at: !ruby/object:DateTime 2017-05-17 15:31:58.834000000 Z updated_at: !ruby/object:DateTime 2017-05-17 15:31:58.834000000 Z content_type_id: chapter revision: 1 title_internal: 'Rhinos: thematic, chapter 7' body: "Dating rock engravings is always problematic, and the imagery at Thaba Sione has been estimated to fall within a broad estimate of between 1,200 - 10,000 years old (Ouzman, 1995:55). Rock art of the last 2,000 years correlates with a number of different cultural groups such as farmers, pastoralists, hunter-gatherers etc. However, the rock art at Thaba Sione is attributed to San&#124;Bushmen and widely understood to reflect a shamanic belief system. Situated close to a waterhole it has been proposed that Thaba Sione was selected specifically by the San&#124;Bushmen for rain-making beliefs and practices, but appears to have been modified as a result of Bantu-speaking farmers moving into the area from around 1500 years ago.\n\nIt is thought that the population of Thaba Sione were similar in social, economic and cultural terms to the now extinct &#124;Xam, a cultural group who inhabited the central interior of South Africa and for whom we have extensive ethnographic accounts. Additionally, they are likely to have been similarly comparable to the !Kung and Ju|’hoan, contemporary cultural groups who live to the north of Thaba Sione in Botswana and Namibia. A comparison of rock art imagery at Thaba Sione and the ethnographic accounts of the &#124;Xam and !Kung show strong similarities in belief systems pertaining to shamanism (Ouzman, 1996:39).\n\nThaba Sione has been a primary focus for archaeologists as there are [559 identified engraved images ](http://bit.ly/2pLfwp4)located on or close to the hill site showing a wide variety of depictions. Images include baboon, birds, buffalo, eland, elephant, felines, giraffe, human figures, lizard, ostrich, rhinoceros, warthog and zebra (Ouzman, 1996:41). " - sys: id: 2OfGVIZFbOOm8w6gg6AucI created_at: !ruby/object:DateTime 2017-05-25 16:08:20.404000000 Z updated_at: !ruby/object:DateTime 2017-05-25 16:08:46.939000000 Z content_type_id: image revision: 2 image: sys: id: 6usDWbit2ga4sM0qeqiKYo created_at: !ruby/object:DateTime 2017-05-25 16:07:54.767000000 Z updated_at: !ruby/object:DateTime 2017-05-25 16:07:54.767000000 Z title: 2013.2034.18610 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6usDWbit2ga4sM0qeqiKYo/e5cd82eb90dcf3312c2305d001ece795/2013.2034.18610.jpg" caption: On the left of the boulder is a pecked outline of a giraffe facing right and stretching forwards. On the right of the split rock is a pecked outline of a buffalo facing left. <NAME> 1. 2013,2034.18610 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3730605&partId=1 - sys: id: 16oCD2X1nmEYmCOMOm6oWi created_at: !ruby/object:DateTime 2017-05-25 16:12:08.925000000 Z updated_at: !ruby/object:DateTime 2017-05-25 16:12:08.925000000 Z content_type_id: chapter revision: 1 title_internal: 'Rhinos: thematic, chapter 8' body: Rhinoceros constitute the second largest category of identifiable imagery (62 or 11.1%), after human figures (72 or 12.9%) (Ouzman, 1996:43). Of the 62 engravings, around 65% have been identified as white rhinoceros, based on the animals’ pronounced nuchal hump (the hump on the dorsal part of the neck), its large front horn and its square lip. The remaining 35% are of the smaller black rhino based on the hook lip that hangs from its upper jaw and its smaller nuchal hump. Historically, both species of rhinoceros were widespread in the area around Thaba Sione (Ouzman, 1996:45). - sys: id: 2jfI6k6zKAauIS62IC6weq created_at: !ruby/object:DateTime 2017-05-25 16:18:32.881000000 Z updated_at: !ruby/object:DateTime 2017-05-25 16:18:32.881000000 Z content_type_id: image revision: 1 image: sys: id: 13ZhEkZUJQA6omECyuWKue created_at: !ruby/object:DateTime 2017-05-25 16:17:13.665000000 Z updated_at: !ruby/object:DateTime 2017-05-25 16:17:13.665000000 Z title: 2013.2034.18595 description: url: "//images.ctfassets.net/xt8ne4gbbocd/13ZhEkZUJQA6omECyuWKue/0e49ec26a4b7715f08336e240b1ff158/2013.2034.18595.jpg" caption: Pecked white rhinoceros and human/therianthrope figure on the far left. 2013,2034.18595 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3730595 - sys: id: 4k9Uy1dQzmkcIY0kIogeWK created_at: !ruby/object:DateTime 2017-06-14 16:40:28.801000000 Z updated_at: !ruby/object:DateTime 2017-06-14 16:40:28.801000000 Z content_type_id: chapter revision: 1 title_internal: 'Rhinos: thematic, chapter 9' body: "Rhinoceros show more ‘non-real’ features, combinations and variations in engraving techniques and occur in more complex ‘scenes’ than any other category of image at the site.\n\nFive of the engravings of rhinoceros are notable by the presence of ‘non-realistic’ features. Although the number of rhinoceros with these attributes is very small in comparison to the overall number of images of rhinoceros, it has been proposed that the placement and number of these features outweigh those found on other images. Such features are thought to convey information which related to three aspects of San shamanism, namely “shamanic transformation, gender relations and rain-making” (Ouzman, 1996:42).\n\nOne of these five images shows a part-human and part-rhinoceros figure. The posture of this therianthropic figure has its hand to its nose. When shamans are performing their medicine dance, they sometimes experience bleeding from the nose both before and after they enter a trance-like state. This posture combined with other features such as two rhinoceros-like horns, a short, thick, rhino-like tail, one back leg akin to that of a rhinoceros and the other back leg terminating in a human foot, as well as a fat pendulous body has been proposed to be a “shaman in a trance who has assumed, in part, rhinoceros form and potency” (Ouzman, 1996:46).\n\nAnother engraving shows the horns of two black rhinoceros which have been deliberately elongated and truncated respectively in order to project towards a fissure in the rock face. It has been argued that cracks or fissures in the rock face were seen as entry and exit points to the spirit world and the rock face acted as veil between these two worlds. These two horns are thus not real but are closely associated with the spirit world which the rhinoceros are entering, leaving or even guarding (Ouzman, 1996:49). \n" - sys: id: 2QFAA8hik82Y4EAIwGSiEs created_at: !ruby/object:DateTime 2017-06-14 16:49:32.079000000 Z updated_at: !ruby/object:DateTime 2017-06-14 16:49:32.079000000 Z content_type_id: image revision: 1 image: sys: id: 57dvZ6DWhiYMuwu4Ek8Uwu created_at: !ruby/object:DateTime 2017-06-14 16:48:35.967000000 Z updated_at: !ruby/object:DateTime 2017-06-14 16:48:35.968000000 Z title: 2013.2034.18583 description: url: "//images.ctfassets.net/xt8ne4gbbocd/57dvZ6DWhiYMuwu4Ek8Uwu/57c2fea0c2ab59676facefe4d3abe8a4/2013.2034.18583.jpg" caption: Black rhinoceros with elongated horns on the left and truncated horns on the right with crack in rock face above. 2013,2034.18583 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3730587&partId=1 - sys: id: 3ApAq8tLfG6wWaswQEwuaU created_at: !ruby/object:DateTime 2017-06-14 16:59:04.056000000 Z updated_at: !ruby/object:DateTime 2017-06-14 17:01:44.568000000 Z content_type_id: chapter revision: 2 title_internal: 'Rhinos: thematic, chapter 10' body: 'An additional engraving of a black rhinoceros shows three horns and has been argued to indicate a supernatural significance and possibly a transformed shaman. However, in real life female rhinoceros sometimes have a third horn as a deformity and this engraving possibly attempts to emphasise the role of the female shaman as a potent guardian and protector. Yet the message is unclear since, as black rhinoceros are known for their anti-social, unpredictable and violent behaviour it is uncertain whether engraved rhinoceros with “nuanced horns” are indicative of feminine or masculine gender and power relations, possibly containing elements of both. The shaman was a person who moved between the real and the non-real world, and is characterised by ambiguity and tension, so maintaining an indistinct gender identity in this context conforms to what we know of shamanic practices and representations (Ouzman, 1996:50). ' - sys: id: 4S5oC30EcwEUGEuEO6sa4m created_at: !ruby/object:DateTime 2017-06-14 17:05:06.739000000 Z updated_at: !ruby/object:DateTime 2017-06-14 17:05:06.739000000 Z content_type_id: image revision: 1 image: sys: id: 1sUJYfRaIUwoQ84GCiemig created_at: !ruby/object:DateTime 2017-06-14 17:04:34.914000000 Z updated_at: !ruby/object:DateTime 2017-06-14 17:04:34.914000000 Z title: 2013.2034.28582 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1sUJYfRaIUwoQ84GCiemig/fb0458a657c1b60cede2946274d6038f/2013.2034.28582.jpg" caption: Two boulders in the foreground at Thaba Sione with engraved images of rhinoceros. 2013,2034.18582 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3730567&partId=1 - sys: id: 4Y3xOdstSowoYOGOEmW6K6 created_at: !ruby/object:DateTime 2017-06-14 17:19:59.171000000 Z updated_at: !ruby/object:DateTime 2017-06-14 17:25:34.931000000 Z content_type_id: chapter revision: 2 title_internal: 'Rhinos: thematic, chapter 11' body: "San&#124;Bushman shamans were also inextricably linked with rain-making ceremonies. The ritual involved the whole of the community but it was the shaman, while in a trance-like state, that captured the rain in a perceived animal-like state. The rain animal was either seen as an ill-tempered ‘rain-bull’, characterised by thunder and lightning and harmful to life, or as a more pleasant ‘rain-cow’, which provided the temperate rains that renewed the grassland (Ouzman, 1996:51) Rain animals were not seen as a distinct species of animal, but were depicted with large bodies and were often horned; one of the few ethnographic accounts that refer to rhinoceros implicate them in rain-making (Ouzman, 1996:52). \n\nIn some contexts certain physical and behavioural characteristics of rhinoceros may have been perceived by some San&#124;Bushman as closely paralleling the perceived appearance and behaviour of a rain animal. These features include its fat and horns, its association with water and its nocturnal habits (in San&#124;Bushman accounts of rain-making, shamans capture the rain animals at night). If rhinoceros were associated with rain animals, the more gregarious white rhinoceros might have been equated with the rain-cow while the ill-tempered black rhinoceros with the angry rain-bull (Ouzman, 1996:54).\n\nAt further sites in the Free State province of South Africa and the Erongo Mountains of Namibia, painted therianthropic figures (part-human, part-rhinoceros) depicting unusual body postures reminiscent of the *Great Trance Dance* and non-realistic features such as exaggerated horn size also seem draw on the rhinoceros as an animal of potency (Hollmann and Lewis-Williams, 2006). Furthermore, a golden rhinoceros from the Iron Age site of Mapungubwe in northern South Africa is testament to the status in which these animals were held, not only by San/Bushmen, but by other cultural groups in southern Africa. Thriving between 1220-1300 AD, and inhabited by ancestors of the Shona people of Zimbabwe, Mapungubwe was the centre of the largest kingdom in the subcontinent, trading gold and ivory with China, India and Egypt. Made of gold foil wrapped around a wooden core, the rhinoceros is a symbol of leadership among the Shona.\n\nRhinos have been represented in rock art for more than 30,000 years, and have played a significant spiritual and cultural role in African societies.\n" - sys: id: 6ZjeUWwA5aCEMUiIgukK48 created_at: !ruby/object:DateTime 2017-06-14 17:29:46.863000000 Z updated_at: !ruby/object:DateTime 2017-06-14 17:31:43.613000000 Z content_type_id: image revision: 2 image: sys: id: 4VhjmP7feE4wOsawSm4cEm created_at: !ruby/object:DateTime 2017-06-14 17:28:15.706000000 Z updated_at: !ruby/object:DateTime 2017-06-14 17:28:15.706000000 Z title: goldenrhinoMapungubww description: url: "//images.ctfassets.net/xt8ne4gbbocd/4VhjmP7feE4wOsawSm4cEm/fcb3c56a141180d546baae6bec9b9022/goldenrhinoMapungubww.JPG" caption: 'The golden rhino of Mapungubwe, featured in the recent "South Africa: The Art of the Nation" Exhibition at the British Museum. ©Sian Tiley-Nel, University of Pretoria Museums /Wikimedia Commons' col_link: https://en.wikipedia.org/wiki/Golden_Rhinoceros_of_Mapungubwe citations: - sys: id: TwHxmivy8uW8mIKAkkMeA created_at: !ruby/object:DateTime 2017-06-14 17:36:04.132000000 Z updated_at: !ruby/object:DateTime 2017-06-14 17:36:04.132000000 Z content_type_id: citation revision: 1 citation_line: |- <NAME>. and <NAME>. 2006. Species and supernatural potency: an unusual rockpainting from the Motheo District, Free State province, South Africa. *South African Journal of Science*102: 509-512. <NAME>. 1996. Thaba Sione: place of rhinoceroses and rain-making. *African Studies*, 55(1):31-59. <NAME>. 1995. Spiritual and political uses of a rock engraving site and its imagery by San and Tswana-speakers. *South African Archaeological Bulletin* 50(161):55-67. <NAME>. and <NAME>. 1998. *Fragile Heritage*. Johannesburg: University of Witwatersranbd Press. <NAME>., <NAME>., and <NAME>. 2015. Pleistocene Figurative *Art Mobilier* from Apollo 11 Cave, Karas Region, Southern Namibia. *South African Archaeological Bulletin* 70 (201): 113-123. background_images: - sys: id: 2ztUAznRiwc0qiE4iUIQGc created_at: !ruby/object:DateTime 2017-05-17 11:44:42.255000000 Z updated_at: !ruby/object:DateTime 2017-05-17 11:44:42.255000000 Z title: Rhinocéros grotte Chauvet description: url: "//images.ctfassets.net/xt8ne4gbbocd/2ztUAznRiwc0qiE4iUIQGc/5958ce98b795f63e5ee49806275209b7/Rhinoc__ros_grotte_Chauvet.jpg" - sys: id: 6m2Q1HCGT6Q2cey00sKGmu created_at: !ruby/object:DateTime 2017-05-17 12:26:24.400000000 Z updated_at: !ruby/object:DateTime 2017-05-17 12:26:24.400000000 Z title: Black Rhino description: url: "//images.ctfassets.net/xt8ne4gbbocd/6m2Q1HCGT6Q2cey00sKGmu/92caad1c13d4bbefe80a5a94aef9844e/Black_Rhino.jpg" ---<file_sep>/_coll_thematic/camels-in-saharan-rock-art.md --- contentful: sys: id: 1KwPIcPzMga0YWq8ogEyCO created_at: !ruby/object:DateTime 2015-11-26 16:25:56.681000000 Z updated_at: !ruby/object:DateTime 2015-12-07 20:49:15.151000000 Z content_type_id: thematic revision: 5 title: 'Sailors on sandy seas: camels in Saharan rock art' slug: camels-in-saharan-rock-art lead_image: sys: id: 46X3vtG1faouSYYws0Aywu created_at: !ruby/object:DateTime 2015-11-26 16:07:51.521000000 Z updated_at: !ruby/object:DateTime 2019-02-12 02:30:35.572000000 Z title: View of camel salt caravan crossing the Ténéré desert. Niger. ©<NAME>/TARA description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3652083&partId=1&searchText=2013,2034.10379&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/46X3vtG1faouSYYws0Aywu/6ff8cc3f26c918c81157746e1b2b3131/Fig._1._Camel.jpg" chapters: - sys: id: 1Q7xHD856UsISuceGegaqI created_at: !ruby/object:DateTime 2015-11-26 16:19:29.618000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:19:29.618000000 Z content_type_id: chapter revision: 1 title_internal: 'Camels: thematic, chapter 1' body: 'If we were to choose a defining image for the Sahara Desert, it would probably depict an endless sea of yellow dunes under a blue sky and, off in the distance, a line of long-legged, humped animals whose profiles have become synonymous with deserts: the one-humped camel (or dromedary). Since its domestication, the camel’s resistance to heat and its ability to survive with small amounts of water and a diet of desert vegetation have made it a key animal for inhabitants of the Sahara, deeply bound to their economy, material culture and lifestyle.' - sys: id: 4p7wUbC6FyiEYsm8ukI0ES created_at: !ruby/object:DateTime 2015-11-26 16:09:23.136000000 Z updated_at: !ruby/object:DateTime 2019-02-12 02:30:19.986000000 Z content_type_id: image revision: 3 image: sys: id: 46X3vtG1faouSYYws0Aywu created_at: !ruby/object:DateTime 2015-11-26 16:07:51.521000000 Z updated_at: !ruby/object:DateTime 2019-02-12 02:30:35.572000000 Z title: View of camel salt caravan crossing the Ténéré desert. Niger. ©David Coulson/TARA description: https://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3652083&partId=1&searchText=2013,2034.10379&page=1 url: "//images.ctfassets.net/xt8ne4gbbocd/46X3vtG1faouSYYws0Aywu/6ff8cc3f26c918c81157746e1b2b3131/Fig._1._Camel.jpg" caption: Camel salt caravan crossing the Ténéré desert in Niger. 2013,2034.10487 ©<NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3652360&partId=1&searchText=2013,2034.10487&page=1 - sys: id: 1LsXHHPAZaIoUksC2US08G created_at: !ruby/object:DateTime 2015-11-26 16:19:46.820000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:19:46.820000000 Z content_type_id: chapter revision: 1 title_internal: 'Camels: thematic, chapter 2' body: Yet, surprising as it seems, the camel is a relative newcomer to the Sahara – at least when compared to other domestic animals such as cattle, sheep, horses and donkeys. Although the process is not yet fully known, camels were domesticated in the Arabian Peninsula around the third millennium BC, and spread from there to the Middle East, North Africa and Somalia from the 1st century AD onwards. The steps of this process from Egypt to the Atlantic Ocean have been documented through many different historical sources, from Roman texts to sculptures or coins, but it is especially relevant in Saharan rock art, where camels became so abundant that they have given their name to a whole period. The depictions of camels provide an incredible amount of information about the life, culture and economy of the Berber and other nomadic communities from the beginnings of the Christian era to the Muslim conquest in the late years of the 7th century. - sys: id: j3q9XWFlMOMSK6kG2UWiG created_at: !ruby/object:DateTime 2015-11-26 16:10:00.029000000 Z updated_at: !ruby/object:DateTime 2018-05-17 14:21:07.255000000 Z content_type_id: image revision: 2 image: sys: id: 6afrRs4VLUS4iEG0iwEoua created_at: !ruby/object:DateTime 2015-11-26 16:07:34.273000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:34.273000000 Z title: EA26664 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6afrRs4VLUS4iEG0iwEoua/e00bb3c81c6c9b44b5e224f5a8ce33a2/EA26664.jpg" caption: Roman terracotta camel with harness, 1st – 3rd century AD, Egypt. British Museum 1891,0403.31 © Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?museumno=1891,0430.31&objectId=118725&partId=1 - sys: id: NxdAnazJaUkeMuyoSOy68 created_at: !ruby/object:DateTime 2015-11-26 16:20:03.948000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:20:03.948000000 Z content_type_id: chapter revision: 1 title_internal: 'Camels: thematic, chapter 3' body: 'What is it that makes camels so suited to deserts? It is not only their ability to transform the fat stored in their hump into water and energy, or their capacity to eat thorny bushes, acacia leaves and even fish and bones. Camels are also able to avoid perspiration by manipulating their core temperature, enduring fluctuations of up to six degrees that could be fatal for other mammals. They rehydrate very quickly, and some of their physical features (nostrils, eyebrows) have adapted to increase water conservation and protect the animals from dust and sand. All these capacities make camels uniquely suited to hot climates: in temperatures of 30-40 °C, they can spend up to 15 days without water. In addition, they are large animals, able to carry loads of up to 300kg, over long journeys across harsh environments. The pads on their feet have evolved so as to prevent them from sinking into the sand. It is not surprising that dromedaries are considered the ‘ships of the desert’, transporting people, commodities and goods through the vast territories of the Sahara.' - sys: id: 2KjIpAzb9Kw4O82Yi6kg2y created_at: !ruby/object:DateTime 2015-11-26 16:10:36.039000000 Z updated_at: !ruby/object:DateTime 2018-05-17 14:39:34.523000000 Z content_type_id: image revision: 2 image: sys: id: 6iaMmNK91YOU00S4gcgi6W created_at: !ruby/object:DateTime 2015-11-26 16:07:51.477000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:51.477000000 Z title: Af1937,0105.16 description: url: "//images.ctfassets.net/xt8ne4gbbocd/6iaMmNK91YOU00S4gcgi6W/4a850695b34c1766d1ee5a06f61f2b36/Af1937_0105.16.jpg" caption: Clay female dromedary (possibly a toy), Somalia. British Museum Af1937,0105.16 © Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?assetId=1088379&objectId=590967&partId=1 - sys: id: 12mIwQ0wG2qWasw4wKQkO0 created_at: !ruby/object:DateTime 2015-11-26 16:11:00.578000000 Z updated_at: !ruby/object:DateTime 2018-05-17 14:45:29.810000000 Z content_type_id: image revision: 2 image: sys: id: 4jTR7LKYv6IiY8wkc2CIum created_at: !ruby/object:DateTime 2015-11-26 16:07:51.505000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:51.505000000 Z title: Fig. 4. Man description: url: "//images.ctfassets.net/xt8ne4gbbocd/4jTR7LKYv6IiY8wkc2CIum/3dbaa11c18703b33840a6cda2c2517f2/Fig._4._Man.jpg" caption: Man leading a camel train through the Ennedi Plateau, Chad. 2013,2034.6134 ©<NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3636989&partId=1&searchText=2013,2034.6134&page=1 - sys: id: 6UIdhB0rYsSQikE8Yom4G6 created_at: !ruby/object:DateTime 2015-11-26 16:20:29.219000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:20:29.219000000 Z content_type_id: chapter revision: 1 title_internal: 'Camels: thematic, chapter 4' body: As mentioned previously, camels came from the Arabian Peninsula through Egypt, where bone remains have been dated to the early 1st millennium BC. However, it took hundreds of years to move into the rest of North Africa due to the River Nile, which represented a major geographical and climatic barrier for these animals. The expansion began around the beginning of the Christian era, and probably took place both along the Mediterranean Sea and through the south of the Sahara. At this stage, it appears to have been very rapid, and during the following centuries camels became a key element in the North African societies. They were used mainly for riding, but also for transporting heavy goods and even for ploughing. Their milk, hair and meat were also used, improving the range of resources available to their herders. However, it seems that the large caravans that crossed the desert searching for gold, ivory or slaves came later, when the Muslim conquest of North Africa favoured the establishment of vast trade networks with the Sahel, the semi-arid region that lies south of the Sahara. - sys: id: YLb3uCAWcKm288oak4ukS created_at: !ruby/object:DateTime 2015-11-26 16:11:46.395000000 Z updated_at: !ruby/object:DateTime 2018-05-17 14:46:15.751000000 Z content_type_id: image revision: 2 image: sys: id: 5aJ9wYpcHe6SImauCSGoM8 created_at: !ruby/object:DateTime 2015-11-26 16:06:48.336000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:06:48.336000000 Z title: '1923,0401.850' description: url: "//images.ctfassets.net/xt8ne4gbbocd/5aJ9wYpcHe6SImauCSGoM8/74efd37612ec798fd91c2a46c65587f7/1923_0401.850.jpg" caption: Glass paste gem imitating beryl, engraved with a short, bearded man leading a camel with a pack on its hump. Roman Empire, 1st – 3rd century AD. 1923,0401.850 ©Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=434529&partId=1&museumno=1923,0401.850&page=1 - sys: id: 3uitqbkcY8s8GCcicKkcI4 created_at: !ruby/object:DateTime 2015-11-26 16:20:45.582000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:20:45.582000000 Z content_type_id: chapter revision: 1 title_internal: 'Camels: thematic, chapter 5' body: Rock art can be extremely helpful in learning about the different ways in which camels were used in the first millennium AD. Images of camels are found in both engravings and paintings in red, white or – on rare occasions – black; sometimes the colours are combined to achieve a more impressive effect. They usually appear in groups, alongside humans, cattle and, occasionally, dogs and horses. Sometimes, even palm trees and houses are included to represent the oases where the animals were watered. Several of the scenes show female camels herded or taking care of their calves, showing the importance of camel-herding and breeding for the Libyan-Berber communities. - sys: id: 5OWosKxtUASWIO6IUii0EW created_at: !ruby/object:DateTime 2015-11-26 16:12:17.552000000 Z updated_at: !ruby/object:DateTime 2018-05-17 15:11:49.775000000 Z content_type_id: image revision: 2 image: sys: id: 3mY7XFQW6QY6KekSQm6SIu created_at: !ruby/object:DateTime 2015-11-26 16:06:48.343000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:06:48.343000000 Z title: '2013,2034.383' description: url: "//images.ctfassets.net/xt8ne4gbbocd/3mY7XFQW6QY6KekSQm6SIu/85c0b70ab40ead396c695fe493081801/2013_2034.383.jpg" caption: Painted scene of a village, depicting a herd or caravan of camels guided by riders and dogs. Wadi Teshuinat, Acacus Mountains, Libya. 2013,2034.383 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3579914&partId=1&museumno=2013,2034.383&page=1 - sys: id: 2Ocb7A3ig8OOkc2AAQIEmo created_at: !ruby/object:DateTime 2015-11-26 16:12:48.147000000 Z updated_at: !ruby/object:DateTime 2018-05-17 15:12:22.249000000 Z content_type_id: image revision: 2 image: sys: id: 2xR2nZml7mQAse8CgckCa created_at: !ruby/object:DateTime 2015-11-26 16:07:51.480000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:51.480000000 Z title: '2013,2034.5117' description: url: "//images.ctfassets.net/xt8ne4gbbocd/2xR2nZml7mQAse8CgckCa/984e95b65ebdc647949d656cb08c0fc9/2013_2034.5117.jpg" caption: Engravings of a female camel with calves. Oued <NAME>. 2013,2034.5117 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3624292&partId=1&museumno=2013,2034.5117&page=1 - sys: id: 4iTHcZ38wwSyGK8UIqY2yQ created_at: !ruby/object:DateTime 2015-11-26 16:13:13.897000000 Z updated_at: !ruby/object:DateTime 2018-05-17 15:31:09.339000000 Z content_type_id: image revision: 2 image: sys: id: 1ecCbVeHUGa2CsYoYSQ4Sm created_at: !ruby/object:DateTime 2015-11-26 16:07:34.241000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:34.241000000 Z title: Fig. 8. Painted description: url: "//images.ctfassets.net/xt8ne4gbbocd/1ecCbVeHUGa2CsYoYSQ4Sm/21b2aebd215d0691482411608ad5682f/Fig._8._Painted.jpg" caption: " Painted scene of Libyan-Berber warriors riding camels, accompanied by infantry and cavalrymen. <NAME>ad. 2013,2034.7295 © <NAME>/TARA" col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3655154&partId=1&searchText=2013,2034.7295&page=1 - sys: id: 2zqiJv33OUM2eEMIK2042i created_at: !ruby/object:DateTime 2015-11-26 16:21:08.068000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:21:08.068000000 Z content_type_id: chapter revision: 1 title_internal: 'Camels: thematic, chapter 6' body: |- That camels were used to transport goods is obvious, and depictions of long lines of animals are common, sometimes with saddles on which to place the packs and ropes to tie the animals together. However, if rock art depictions are some indication of camel use, it seems that until the Muslim conquest the main function of one-humped camels was as mounts, often linked to war. The Sahara desert contains dozens of astonishingly detailed images of warriors riding camels, armed with spears, long swords and shields, sometimes accompanied by infantry soldiers and horsemen. Although camels are not as good as horses for use as war mounts (they are too tall and make insecure platforms for shooting arrows), they were undoubtedly very useful in raids – the most common type of war activity in the desert – as well as being a symbol of prestige, wealth and authority among the desert warriors, much as they still are today. Moreover, the extraordinary detail of some of the rock art paintings has provided inestimable help in understanding how (and why) camels were ridden in the 1st millennium AD. Unlike horses, donkeys or mules, one-humped camels present a major problem for riders: where to put the saddle. Although it might be assumed that the saddle should be placed over the hump, they can, in fact, also be positioned behind or in front of the hump, depending on the activity. It seems that the first saddles were placed behind the hump, but that position was unsuitable for fighting, quite uncomfortable, and unstable. Subsequently, a new saddle was invented in North Arabia around the 5th century BC: a framework of wood that rested over the hump and provided a stable platform on which to ride and fight more effectively. The North Arabian saddle led to a revolution in the domestication of one-humped camels, allowed a faster expansion of the use of these animals, and it is probably still the most used type of saddle today. - sys: id: 6dOm7ewqmA6oaM4cK4cy8c created_at: !ruby/object:DateTime 2015-11-26 16:14:25.900000000 Z updated_at: !ruby/object:DateTime 2018-05-17 15:31:33.078000000 Z content_type_id: image revision: 2 image: sys: id: 5qXuQrcnUQKm0qCqoCkuGI created_at: !ruby/object:DateTime 2015-11-26 16:06:48.345000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:06:48.345000000 Z title: As1974,29.17 description: url: "//images.ctfassets.net/xt8ne4gbbocd/5qXuQrcnUQKm0qCqoCkuGI/2b279eff2a6f42121ab0f6519d694a92/As1974_29.17.jpg" caption: North Arabian-style saddle, with a wooden framework designed to be put around the hump. Jordan. British Museum As1974,29.17 © Trustees of the British Museum col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3320111&partId=1&object=23696&page=1 - sys: id: 5jE9BeKCBUEK8Igg8kCkUO created_at: !ruby/object:DateTime 2015-11-26 16:21:27.156000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:21:27.156000000 Z content_type_id: chapter revision: 1 title_internal: 'Camels: thematic, chapter 7' body: 'Although North Arabian saddles are found throughout North Africa and are often depicted in rock art paintings, at some point a new kind of saddle was designed in North Africa: one placed in front of the hump, with the weight over the shoulders of the camel. This type of shoulder saddle allows the rider to control the camel with the feet and legs, thus improving the ride. Moreover, the rider is seated in a lower position and thus needs shorter spears and swords that can be brandished more easily, making warriors more efficient. This new kind of saddle, which is still used throughout North Africa today, appears only in the western half of the Sahara and is well represented in the rock art of Algeria, Niger and Mauritania. And it is not only saddles that are recognizable in Saharan rock art: harnesses, reins, whips or blankets are identifiable in the paintings and show astonishing similarities to those still used today by desert peoples.' - sys: id: 6yZaDQMr1Sc0sWgOG6MGQ8 created_at: !ruby/object:DateTime 2015-11-26 16:14:46.560000000 Z updated_at: !ruby/object:DateTime 2018-05-17 15:33:25.754000000 Z content_type_id: image revision: 2 image: sys: id: 40zIycUaTuIG06mgyaE20K created_at: !ruby/object:DateTime 2015-11-26 16:07:51.466000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:51.466000000 Z title: Fig. 10. Painting description: url: "//images.ctfassets.net/xt8ne4gbbocd/40zIycUaTuIG06mgyaE20K/1736927ffb5e2fc71d1f1ab04310a73f/Fig._10._Painting.jpg" caption: Painting of rider on a one-humped camel. Note the North Arabian saddle on the hump, similar to the example from Jordan above. Terkei, Ennedi plateau, Chad. 2013,2034.6568 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3640623&partId=1&searchText=2013,2034.6568&page=1 - sys: id: 5jHyVlfWXugI2acowekUGg created_at: !ruby/object:DateTime 2015-11-26 16:15:13.926000000 Z updated_at: !ruby/object:DateTime 2018-05-17 15:36:07.603000000 Z content_type_id: image revision: 2 image: sys: id: 6EvwTsiMO4qoiIY4gGCgIK created_at: !ruby/object:DateTime 2015-11-26 16:07:34.249000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:34.249000000 Z title: '2013,2034.4471' description: url: "//images.ctfassets.net/xt8ne4gbbocd/6EvwTsiMO4qoiIY4gGCgIK/1db47ae083ff605b9533898d9d9fb10d/2013_2034.4471.jpg" caption: Camel-rider using a North African saddle (in front of the hump), surrounded by warriors with spears and swords, with Libyan-Berber graffiti. <NAME>, Tassili, Algeria. 2013,2034.4471 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3602860&partId=1&museumno=2013,2034.4471&page=1 - sys: id: 57goC8PzUs6G4UqeG0AgmW created_at: !ruby/object:DateTime 2015-11-26 16:16:51.920000000 Z updated_at: !ruby/object:DateTime 2019-02-12 02:33:53.275000000 Z content_type_id: image revision: 3 image: sys: id: 5JDO7LrdKMcSEOMEG8qsS8 created_at: !ruby/object:DateTime 2015-11-26 16:07:34.250000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:34.250000000 Z title: Fig. 12. Tuaregs description: url: "//images.ctfassets.net/xt8ne4gbbocd/5JDO7LrdKMcSEOMEG8qsS8/76cbecd637724d549db8a7a101553280/Fig._12._Tuaregs.jpg" caption: Tuaregs at Cura Salee, an annual meeting of desert peoples. Note the saddles in front of the hump and the camels' harnesses, similar to the rock paintings above such as the image from Terkei. Ingal, Northern Niger. 2013,2034.10523 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3652377&partId=1&searchText=2013,2034.10523&page=1 - sys: id: 3QPr46gQP6sQWswuSA2wog created_at: !ruby/object:DateTime 2015-11-26 16:21:50.767000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:21:50.767000000 Z content_type_id: chapter revision: 1 title_internal: 'Camels: thematic, chapter 8' body: Since their introduction to the Sahara during the first centuries of the Christian era, camels have become indispensable for desert communities, providing a method of transport for people and commodities, but also for their milk, meat and hair for weaving. They allowed the improvement of wide cultural and economic networks, transforming the Sahara into a key node linking the Mediterranean Sea with Sub-Saharan Africa. A symbol of wealth and prestige, the Libyan-Berber peoples recognized camels’ importance and expressed it through paintings and engravings across the desert, leaving a wonderful document of their societies. The painted images of camel-riders crossing the desert not only have an evocative presence, they are also perfect snapshots of a history that started two thousand years ago and seems as eternal as the Sahara. - sys: id: 54fiYzKXEQw0ggSyo0mk44 created_at: !ruby/object:DateTime 2015-11-26 16:17:13.884000000 Z updated_at: !ruby/object:DateTime 2018-05-17 16:01:13.379000000 Z content_type_id: image revision: 2 image: sys: id: 3idPZkkIKAOWCiKouQ8c8i created_at: !ruby/object:DateTime 2015-11-26 16:07:34.244000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:34.244000000 Z title: Fig. 13. Camel-riders description: url: "//images.ctfassets.net/xt8ne4gbbocd/3idPZkkIKAOWCiKouQ8c8i/4527b1eebe112ef9c38da1026e7540b3/Fig._13._Camel-riders.jpg" caption: Camel-riders galloping. Butress cave, Archael Guelta, Chad. 2013,2034.6077 ©<NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3637992&partId=1&searchText=2013,2034.6077&page=1 - sys: id: 1ymik3z5wMUEway6omqKQy created_at: !ruby/object:DateTime 2015-11-26 16:17:32.501000000 Z updated_at: !ruby/object:DateTime 2018-05-17 16:02:41.679000000 Z content_type_id: image revision: 2 image: sys: id: 4Y85f5QkVGQiuYEaA2OSUC created_at: !ruby/object:DateTime 2015-11-26 16:07:06.194000000 Z updated_at: !ruby/object:DateTime 2015-11-26 16:07:06.194000000 Z title: Fig. 14. Tuareg description: url: "//images.ctfassets.net/xt8ne4gbbocd/4Y85f5QkVGQiuYEaA2OSUC/4fbca027ed170b221daefdff0ae7d754/Fig._14._Tuareg.jpg" caption: Tuareg rider galloping at the Cure Salee meeting. Ingal, northern Niger. 2013,2034.10528 © <NAME>/TARA col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3652371&partId=1&searchText=2013,2034.10528&page=1 background_images: - sys: id: 3mhr7uvrpesmaUeI4Aiwau created_at: !ruby/object:DateTime 2015-12-07 18:13:48.396000000 Z updated_at: !ruby/object:DateTime 2015-12-07 18:13:48.396000000 Z title: CHAENP0340003 description: url: "//images.ctfassets.net/xt8ne4gbbocd/3mhr7uvrpesmaUeI4Aiwau/65c691f09cd60bb7aa08457e18eaa624/CHAENP0340003_1_.JPG" - sys: id: BPzulf3QNqMC4Iqs4EoCG created_at: !ruby/object:DateTime 2015-12-07 18:13:31.094000000 Z updated_at: !ruby/object:DateTime 2015-12-07 18:13:31.094000000 Z title: CHAENP0340001 description: url: "//images.ctfassets.net/xt8ne4gbbocd/BPzulf3QNqMC4Iqs4EoCG/356b921099bfccf59008b69060d20d75/CHAENP0340001_1_.JPG" ---<file_sep>/_coll_country/somalia-somaliland/laas-geel.md --- breadcrumbs: - label: Countries url: "../../" - label: Somalia/Somaliland url: "../" layout: featured_site contentful: sys: id: c899JmsteEUGcImgK6coE created_at: !ruby/object:DateTime 2015-11-25 12:15:21.374000000 Z updated_at: !ruby/object:DateTime 2015-12-07 20:53:38.667000000 Z content_type_id: featured_site revision: 5 title: Laas Geel, Somaliland slug: laas-geel chapters: - sys: id: 1JcxOsFcCYMqGCWuu8G2Oo created_at: !ruby/object:DateTime 2015-11-25 12:40:46.141000000 Z updated_at: !ruby/object:DateTime 2017-01-12 16:51:05.773000000 Z content_type_id: chapter revision: 2 title_internal: 'Somaliland: featured site, chapter 1' body: Laas Geel, one of the most important rock art sites in the region, is located in the north-western part of the Horn of Africa, in Somaliland, in the road that links Hargeisa and Berbera. The site is placed on a granite outcrop that rises from a plateau at an altitude of 950 meters above sea level, at the confluence of two seasonal rivers, a key fact to explain the existence of rock art in the outcrop. Even today, the name of the site (“the camel’s well” in Somali) makes reference to the availability of water near the surface of the wadis. The panels are placed at three different levels and distributed mostly throughout the eastern flank of the outcrop, although isolated depictions can be found in other slopes. images_and_captions: - sys: id: 6DXjMuJy2AeE0uMuQMOiYQ created_at: !ruby/object:DateTime 2015-11-25 12:17:16.995000000 Z updated_at: !ruby/object:DateTime 2017-01-12 16:52:45.006000000 Z content_type_id: image revision: 2 image: sys: id: 31GgY4I8aIMi6wscCMaysq created_at: !ruby/object:DateTime 2015-11-25 11:48:33.941000000 Z updated_at: !ruby/object:DateTime 2015-11-25 11:48:33.941000000 Z title: '2013,2034.15841' description: url: "//images.ctfassets.net/xt8ne4gbbocd/31GgY4I8aIMi6wscCMaysq/38ee13ba0978feca8e05b9e9f6ad9ecb/SOMLAG0020021.jpg" caption: View of Laas Geel landscape seen from one of the shelters. Laas Geel, Somaliland. 2013,2034.15841 © TARA/<NAME> col_link: http://bit.ly/2ih7AbC - sys: id: 6DXjMuJy2AeE0uMuQMOiYQ created_at: !ruby/object:DateTime 2015-11-25 12:17:16.995000000 Z updated_at: !ruby/object:DateTime 2017-01-12 16:52:45.006000000 Z content_type_id: image revision: 2 image: sys: id: 31GgY4I8aIMi6wscCMaysq created_at: !ruby/object:DateTime 2015-11-25 11:48:33.941000000 Z updated_at: !ruby/object:DateTime 2015-11-25 11:48:33.941000000 Z title: '2013,2034.15841' description: url: "//images.ctfassets.net/xt8ne4gbbocd/31GgY4I8aIMi6wscCMaysq/38ee13ba0978feca8e05b9e9f6ad9ecb/SOMLAG0020021.jpg" caption: View of Laas Geel landscape seen from one of the shelters. Laas Geel, Somaliland. 2013,2034.15841 © TARA/<NAME> col_link: http://bit.ly/2ih7AbC - sys: id: 5bW01VLoU0e8MW0QA8UEIc created_at: !ruby/object:DateTime 2015-11-25 12:41:31.266000000 Z updated_at: !ruby/object:DateTime 2015-11-25 12:41:31.266000000 Z content_type_id: chapter revision: 1 title_internal: 'Somaliland: featured site, chapter 2' body: The site was discovered in 2002 by a French team led by <NAME> which studied the beginning of Pastoralism in the Horn of Africa. Along with the paintings, lithic tools were found scattered throughout the site, and tombs marked with stelae and mounds can be seen in the neighbourhood. The paintings are distributed along 20 rock shelters, the biggest being around 10 meters long. Most of them correspond to humpless cows with curved or lyre-like white horns (sometimes with reddish tips) and marked udders. Paintings are enormously colourful, including red, white, black, violet, brown and yellow both isolated and combined. However, the most distinctive feature of these cows is their necks, depicted rectangular, abnormally wide and either blank or infilled with red and white stripes, either straight or wavy. These strange necks have been interpreted as mats hanging from the actual neck, in what could be interpreted as a ceremonial ornament. images_and_captions: - sys: id: 4MkPzhKn1KcGAqsYI2KAM4 created_at: !ruby/object:DateTime 2015-11-25 12:38:47.035000000 Z updated_at: !ruby/object:DateTime 2017-01-12 16:54:21.792000000 Z content_type_id: image revision: 2 image: sys: id: 4oUCCQM2xiEaa0WIKyAoIm created_at: !ruby/object:DateTime 2015-11-25 11:48:53.979000000 Z updated_at: !ruby/object:DateTime 2015-11-25 11:48:53.979000000 Z title: '2013,2034.16068' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4oUCCQM2xiEaa0WIKyAoIm/68d05107d238d784fb598eb52c5a3f29/SOMLAG0090043.jpg" caption: View of one of the main Lass Geel main panels, taken with a fish eye lens. <NAME>, Somaliland. 2013,2034.16068 © TARA/David Coulson col_link: http://bit.ly/2iLyTXN - sys: id: 4MkPzhKn1KcGAqsYI2KAM4 created_at: !ruby/object:DateTime 2015-11-25 12:38:47.035000000 Z updated_at: !ruby/object:DateTime 2017-01-12 16:54:21.792000000 Z content_type_id: image revision: 2 image: sys: id: 4oUCCQM2xiEaa0WIKyAoIm created_at: !ruby/object:DateTime 2015-11-25 11:48:53.979000000 Z updated_at: !ruby/object:DateTime 2015-11-25 11:48:53.979000000 Z title: '2013,2034.16068' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4oUCCQM2xiEaa0WIKyAoIm/68d05107d238d784fb598eb52c5a3f29/SOMLAG0090043.jpg" caption: View of one of the main Lass Geel main panels, taken with a fish eye lens. <NAME>, Somaliland. 2013,2034.16068 © TARA/<NAME>son col_link: http://bit.ly/2iLyTXN - sys: id: 3NlNPDdYMUy2WyKIKAAyyQ created_at: !ruby/object:DateTime 2015-11-25 12:42:09.252000000 Z updated_at: !ruby/object:DateTime 2015-12-11 12:16:01.889000000 Z content_type_id: chapter revision: 2 title: title_internal: 'Somaliland: featured site, chapter 3' body: 'Cows appear isolated or in groups of up to fifteen, although no clear representation of herds can be made out, and they are often associated with human figures with a very standardized shape: frontally depicted with arms outstretched to the sides, and wearing a kind of shirt, usually white. Heads are small and sometimes surrounded by a halo of radial dashes as a crown. These figures always appear related to the cows, either under the neck, between the legs or behind the hindquarters. In some cases they carry a bow, a stick or a shield. Along with humans and cows, dogs are well represented too, usually positioned near the human figures. Other animals are much scarcer: there are some figures that could correspond to antelopes, monkeys and two lonely depictions of a giraffe. Throughout most of the panels, geometric symbols are also represented, often surrounding the cows.' images_and_captions: - sys: id: 6iWCErs5moI0koSeU4KCow created_at: !ruby/object:DateTime 2015-11-25 12:39:17.751000000 Z updated_at: !ruby/object:DateTime 2017-01-12 16:55:44.228000000 Z content_type_id: image revision: 2 image: sys: id: 4VTvKF1G52eSUicC2wuu8e created_at: !ruby/object:DateTime 2015-11-25 11:49:13.227000000 Z updated_at: !ruby/object:DateTime 2015-11-25 11:49:13.227000000 Z title: '2013,2034.15894' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4VTvKF1G52eSUicC2wuu8e/35bd5996e54375f75258f75aca92a208/SOMLAG0050018.jpg" caption: View of panel with painted depictions of cattle, antelopes and a giraffe. <NAME>. 2013,2034.15894 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3709550 - sys: id: 6iWCErs5moI0koSeU4KCow created_at: !ruby/object:DateTime 2015-11-25 12:39:17.751000000 Z updated_at: !ruby/object:DateTime 2017-01-12 16:55:44.228000000 Z content_type_id: image revision: 2 image: sys: id: 4VTvKF1G52eSUicC2wuu8e created_at: !ruby/object:DateTime 2015-11-25 11:49:13.227000000 Z updated_at: !ruby/object:DateTime 2015-11-25 11:49:13.227000000 Z title: '2013,2034.15894' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4VTvKF1G52eSUicC2wuu8e/35bd5996e54375f75258f75aca92a208/SOMLAG0050018.jpg" caption: View of panel with painted depictions of cattle, antelopes and a giraffe. <NAME>, Somaliland. 2013,2034.15894 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3709550 - sys: id: 2L6Reqb06ImeEUeKq0mI4A created_at: !ruby/object:DateTime 2015-11-25 12:42:51.276000000 Z updated_at: !ruby/object:DateTime 2015-12-11 12:16:39.344000000 Z content_type_id: chapter revision: 2 title_internal: 'Somaliland: featured site, chapter 4' body: Unlike many other rock art sites, Laas Geel has been dated quite precisely thanks to the excavations carried out in one of the shelters by the French team that documented the site. During the excavation parts of the painted rock wall were recovered, and therefore the archaeologists have proposed a chronology of mid-4th to mid-3rd millennia, being one of the oldest evidences of cattle domestication in the Horn of Africa and the oldest known rock art site in this region. Unfortunately, although bovine bones were recovered from the excavation, they were too poorly preserved to determine whether they correspond to domestic or wild animals. images_and_captions: - sys: id: 7MwGPprSpiIeQOmmuOgcYg created_at: !ruby/object:DateTime 2015-11-25 12:39:41.223000000 Z updated_at: !ruby/object:DateTime 2017-01-12 16:58:47.282000000 Z content_type_id: image revision: 2 image: sys: id: 65ttuyQSS4C4CC62kSKeaQ created_at: !ruby/object:DateTime 2015-11-25 11:49:30.632000000 Z updated_at: !ruby/object:DateTime 2015-11-25 11:49:30.632000000 Z title: '2013,2034.15821' description: url: "//images.ctfassets.net/xt8ne4gbbocd/65ttuyQSS4C4CC62kSKeaQ/b8267145843996f0f0846f54ea8a1272/SOMLAG0020001.jpg" caption: View of cow and human figure painted at the middle of the rock art panel, with other cows depicted to the lower left. <NAME>, Somaliland. 2013,2034.15821 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3691509 - sys: id: 7MwGPprSpiIeQOmmuOgcYg created_at: !ruby/object:DateTime 2015-11-25 12:39:41.223000000 Z updated_at: !ruby/object:DateTime 2017-01-12 16:58:47.282000000 Z content_type_id: image revision: 2 image: sys: id: 65ttuyQSS4C4CC62kSKeaQ created_at: !ruby/object:DateTime 2015-11-25 11:49:30.632000000 Z updated_at: !ruby/object:DateTime 2015-11-25 11:49:30.632000000 Z title: '2013,2034.15821' description: url: "//images.ctfassets.net/xt8ne4gbbocd/65ttuyQSS4C4CC62kSKeaQ/b8267145843996f0f0846f54ea8a1272/SOMLAG0020001.jpg" caption: View of cow and human figure painted at the middle of the rock art panel, with other cows depicted to the lower left. La<NAME>, Somaliland. 2013,2034.15821 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3691509 - sys: id: 5VTa7vIoIoIa2eS08ysAMU created_at: !ruby/object:DateTime 2015-11-25 12:43:38.752000000 Z updated_at: !ruby/object:DateTime 2015-11-25 12:43:38.752000000 Z content_type_id: chapter revision: 1 title_internal: 'Somaliland: featured site, chapter 5' body: When discovered, Laas Geel was considered a unique site, and although its general characteristics corresponded to the so-called Ethiopian-Arabic style, its specific stylistic features had no parallels in the rock art of the region. As research has increased, some other sites, such as Dhaga Koure, Dhambalin and Karin Hagane, have provided similar depictions to those of Laas Geel, thus reinforcing the idea of a distinctive “Laas Geel” style which nevertheless must be interpreted within the broader regional context. images_and_captions: - sys: id: YFu4EthxsG8kEsA6IIQoK created_at: !ruby/object:DateTime 2015-11-25 12:40:04.102000000 Z updated_at: !ruby/object:DateTime 2017-01-12 16:59:56.493000000 Z content_type_id: image revision: 2 image: sys: id: Le7MwhlqWA8omCGckqeC0 created_at: !ruby/object:DateTime 2015-11-25 11:49:46.453000000 Z updated_at: !ruby/object:DateTime 2015-11-25 11:49:46.453000000 Z title: '2013,2034.15446' description: url: "//images.ctfassets.net/xt8ne4gbbocd/Le7MwhlqWA8omCGckqeC0/b715080968450f4bbcde78c1186b022e/SOMGAB0010009.jpg" caption: Group of painted cows with curved horns and marked udders, superimposed by more modern, white geometric signs. <NAME>, Somaliland. 2013,2034.15446 © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3710609 - sys: id: YFu4EthxsG8kEsA6IIQoK created_at: !ruby/object:DateTime 2015-11-25 12:40:04.102000000 Z updated_at: !ruby/object:DateTime 2017-01-12 16:59:56.493000000 Z content_type_id: image revision: 2 image: sys: id: Le7MwhlqWA8omCGckqeC0 created_at: !ruby/object:DateTime 2015-11-25 11:49:46.453000000 Z updated_at: !ruby/object:DateTime 2015-11-25 11:49:46.453000000 Z title: '2013,2034.15446' description: url: "//images.ctfassets.net/xt8ne4gbbocd/Le7MwhlqWA8omCGckqeC0/b715080968450f4bbcde78c1186b022e/SOMGAB0010009.jpg" caption: Group of painted cows with curved horns and marked udders, superimposed by more modern, white geometric signs. <NAME>, Somaliland. 2013,2034.15446 © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3710609 - sys: id: 4yBgBkRUdWGgICeIMua8Am created_at: !ruby/object:DateTime 2015-11-25 12:44:09.364000000 Z updated_at: !ruby/object:DateTime 2015-12-11 12:17:05.456000000 Z content_type_id: chapter revision: 2 title_internal: 'Somaliland: featured site, chapter 6' body: 'Laas Geel is a marvellous example of the potential of African rock art still waiting to be discovered and studied. Not only the quality of the images depicted is astonishing, but the archaeological data associated with the site and the landscape itself help to reconstruct a key episode in human history elsewhere: the moment in which animals started to be domesticated. The strong symbolism which surrounds the figures of cows and humans is a permanent testimony of the reverence these communities paid to the animals that provided their sustenance.' citations: - sys: id: 5M3Fqrd5bGqyUGegSo4U84 created_at: !ruby/object:DateTime 2015-11-25 12:44:40.978000000 Z updated_at: !ruby/object:DateTime 2015-11-25 12:44:40.978000000 Z content_type_id: citation revision: 1 citation_line: |- <NAME>., <NAME>. y <NAME>. (2003b): The Discovery of New Rock Art Paintings in the Horn of Africa: The Rock Shelters of Laas Geel, Republic of Somaliland. *Journal of African Archaeology*, 1 (2): 227-236. <NAME>. and <NAME>. (eds.) (2010): The decorated shelters of Laas Geel and the rock art of Somaliland. Presses universitaires de la Méditerranée, Montpellier University background_images: - sys: id: 4VTvKF1G52eSUicC2wuu8e created_at: !ruby/object:DateTime 2015-11-25 11:49:13.227000000 Z updated_at: !ruby/object:DateTime 2015-11-25 11:49:13.227000000 Z title: '2013,2034.15894' description: url: "//images.ctfassets.net/xt8ne4gbbocd/4VTvKF1G52eSUicC2wuu8e/35bd5996e54375f75258f75aca92a208/SOMLAG0050018.jpg" - sys: id: 31GgY4I8aIMi6wscCMaysq created_at: !ruby/object:DateTime 2015-11-25 11:48:33.941000000 Z updated_at: !ruby/object:DateTime 2015-11-25 11:48:33.941000000 Z title: '2013,2034.15841' description: url: "//images.ctfassets.net/xt8ne4gbbocd/31GgY4I8aIMi6wscCMaysq/38ee13ba0978feca8e05b9e9f6ad9ecb/SOMLAG0020021.jpg" ---<file_sep>/_coll_thematic/landscapes-of-rock-art.md --- contentful: sys: id: 2ULickNOv688OaGigYCWYm created_at: !ruby/object:DateTime 2018-05-09 15:26:39.131000000 Z updated_at: !ruby/object:DateTime 2018-05-09 15:28:31.662000000 Z content_type_id: thematic revision: 2 title: Landscapes of Rock Art slug: landscapes-of-rock-art lead_image: sys: id: 62Htpy9mk8Gw28EuUE6SiG created_at: !ruby/object:DateTime 2015-11-30 16:58:24.956000000 Z updated_at: !ruby/object:DateTime 2015-11-30 16:58:24.956000000 Z title: SOADRB0050042_1 description: url: "//images.ctfassets.net/xt8ne4gbbocd/62Htpy9mk8Gw28EuUE6SiG/9cd9572ea1c079f4814104f40045cfb6/SOADRB0050042.jpg" chapters: - sys: id: Ga9XxWBfqwke88qwUKGc2 created_at: !ruby/object:DateTime 2018-01-10 15:12:02.010000000 Z updated_at: !ruby/object:DateTime 2018-01-10 15:12:02.010000000 Z content_type_id: chapter revision: 1 title_internal: 'Landscape: thematic, chapter 1' body: "“Placed within a landscape setting, rock-art becomes a more complex and expressive visual language” (Chippindale and Nash, 2004:23)\n\nApart from the quantity and diversity of rock art images in this collection, one of the most notable features is the landscapes within which they occur: vast undulating deserts; mountainous regions carved out by the wind and rain; verdant wooded environments; and lacustrine and coastal backdrops, are all testament to the diverse contexts in which rock art has been placed across the African continent. \n" - sys: id: 5NCw7svaw0IoWWK2uuYEQG created_at: !ruby/object:DateTime 2018-01-10 15:16:11.619000000 Z updated_at: !ruby/object:DateTime 2018-02-27 12:40:32.949000000 Z content_type_id: image revision: 2 image: sys: id: 1jNymQwU6K4AQaQOewgGgK created_at: !ruby/object:DateTime 2018-01-10 15:13:26.052000000 Z updated_at: !ruby/object:DateTime 2018-01-10 15:13:26.052000000 Z title: ALGTAF0010004 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1jNymQwU6K4AQaQOewgGgK/dea01f956f299e95a78e9aa1a0665e54/ALGTAF0010004.jpg" caption: 'View of the Afara Plain in Algeria. 2013,2034.3958 ©TARA/<NAME> ' col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3636442 - sys: id: 7ng9hfsvLi2A0eWU6A0gWe created_at: !ruby/object:DateTime 2018-01-10 15:20:20.533000000 Z updated_at: !ruby/object:DateTime 2018-02-27 12:24:25.304000000 Z content_type_id: image revision: 2 image: sys: id: 4JUCLGscOcGSS8SMCq06og created_at: !ruby/object:DateTime 2018-01-10 15:19:25.206000000 Z updated_at: !ruby/object:DateTime 2018-01-10 15:19:25.206000000 Z title: KENVIC0010032 description: url: "//images.ctfassets.net/xt8ne4gbbocd/4JUCLGscOcGSS8SMCq06og/802ce4c698c5ecc540ecce7be9bd8a1b/KENVIC0010032.jpg" caption: View of Lake Victoria, Kenya. 2013,2034.14266 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3692066 - sys: id: 4ptu3L494cEYqk6KaY40o4 created_at: !ruby/object:DateTime 2018-02-27 12:27:10.888000000 Z updated_at: !ruby/object:DateTime 2018-02-27 12:27:10.888000000 Z content_type_id: image revision: 1 image: sys: id: 2w9QtfzuOAuEsWmSC6MweQ created_at: !ruby/object:DateTime 2018-02-27 12:23:48.106000000 Z updated_at: !ruby/object:DateTime 2018-02-27 12:23:48.106000000 Z title: SOADRB0050003 description: url: "//images.ctfassets.net/xt8ne4gbbocd/2w9QtfzuOAuEsWmSC6MweQ/68bb49fc2a6a8fc62d889cd22b7b3f74/SOADRB0050003.jpg" caption: Looking down the Didima River in the Drakensberg Mountains, South Africa. 2013,2034.18280 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3738721&partId=1&searchText=2013,2034.18280&page=1 - sys: id: 5C3yAo4w24egO2O46UCCQg created_at: !ruby/object:DateTime 2018-02-27 12:37:03.943000000 Z updated_at: !ruby/object:DateTime 2018-02-27 12:37:03.943000000 Z content_type_id: chapter revision: 1 title_internal: 'Landscape: thematic, chapter 2' body: "Indeed, the defining characteristic of rock art beyond its association with rock surfaces, is its placement within the geographical landscape. Landscapes can be social, cultural, economic, political, ritual, or sacred – but more than anything the geology of the landscape has to be favourable in order for rock art to be placed within it in the first place. \n\nIn archaeology, context is everything, and we may assume that the positioning of images in the landscape is equally important. But what exactly is the relationship between rock art and the landscape? Any connection between the placement of images and the environment, if indeed there is a correlation to be made, varies depending on cultural group, belief systems, economic and social structures, geology, topography and climate. While we cannot make any overarching theories, as Chippindale and Nash observe, “All rock art was initially created or caused to be created by someone, for someone; its landscape position would have been important” (2004:21) \n" - sys: id: 5FmuBPI2k0o6aCs8immMWQ created_at: !ruby/object:DateTime 2018-02-27 12:41:25.070000000 Z updated_at: !ruby/object:DateTime 2018-02-27 12:41:25.070000000 Z content_type_id: image revision: 1 image: sys: id: 4mC1G2fnJ6uKEmoUWsWq0u created_at: !ruby/object:DateTime 2018-02-27 12:39:33.471000000 Z updated_at: !ruby/object:DateTime 2018-02-27 12:39:33.471000000 Z title: SOADRB0050008 description: url: "//images.ctfassets.net/xt8ne4gbbocd/4mC1G2fnJ6uKEmoUWsWq0u/cf4d370ea6f240ce296ea830dba06406/SOADRB0050008.jpg" caption: View from painted rock art shelter looking over the Drakensberg Mountains, South Africa. 2013,2034.18282 ©TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3738722&partId=1&searchText=2013,2034.18282&page=1 - sys: id: 6cU5WF1xaEUIiEEkyoWaoq created_at: !ruby/object:DateTime 2018-02-27 15:57:49.267000000 Z updated_at: !ruby/object:DateTime 2018-02-27 16:38:09.121000000 Z content_type_id: chapter revision: 2 title_internal: 'Landscape: thematic, chapter 3' body: "However, a major concern for archaeologists is the concept of \"landscape\" itself. The conception or notion of “landscape” is genenerally a cultural construct - how people perceive a landscape is certainly not a universal perception and this potentially influences and problematizes our understanding of how cultural groups in the past conceived of their environments. For example, Western cultures often focus on large-scale topographical features in the landscape, whereas often indigenous group, such as !Kung San who inhabit the Kalahari, their frame of reference is more nuanced, such as “where a certain veld food may grow, even if that place is only a few yards in diameter, or where there is only a patch of tall arrow grass or a bee tree…” (Smith and Blundell, 2004:248). Archaeologists tend to concentrate on prominent features of the landscape, but indigenous groups may be more concerned with the minutiae of the environment, pebbles, holes, flora and features less likely to survive in the archaeological record. \n\nOur perceptions of landscapes also differ. For example, the Sahara may appear to Western eyes as flat, featureless, austere and demanding, but for those who live in the desert it can be filled with meaningful reference points and relationships. It has been noted that in the Sahara the “Tuareg rely heavily on the most prevalent of global navigation methods: landmark recognition. They have learned to read what appear to the foreigner as featureless plains in the same way that we come to recognize our own home environments, albeit swapping shifts in relief, rock and sand colour for road signs etc...” (Gooley, 2010). This makes a landscape approach challenging because it will always be from the perspective of what *we perceive*.\n" - sys: id: 1YZyNsFTHWIoYegcigYaik created_at: !ruby/object:DateTime 2018-02-27 16:11:16.467000000 Z updated_at: !ruby/object:DateTime 2018-02-27 16:11:16.467000000 Z content_type_id: image revision: 1 image: sys: id: 5hZt83Mv4cu6UcWuAKyMg4 created_at: !ruby/object:DateTime 2018-02-27 15:59:28.364000000 Z updated_at: !ruby/object:DateTime 2018-02-27 16:00:20.852000000 Z title: NIGNAS0113 description: Desert landscape, Temet, Niger. 2013,2034.10407 ©TARA/<NAME> url: "//images.ctfassets.net/xt8ne4gbbocd/5hZt83Mv4cu6UcWuAKyMg4/be4780e70e88df213da498b5f100f1cc/NIGNAS0113.jpg" caption: Desert landscape, Temet, Niger. 2013,2034.10407 ©TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3738722&partId=1&searchText=2013,2034.10407&page=1 - sys: id: 6fhRJ1NiO4wSwSmqmSGEQA created_at: !ruby/object:DateTime 2018-02-27 16:13:22.652000000 Z updated_at: !ruby/object:DateTime 2018-02-27 16:16:10.141000000 Z content_type_id: image revision: 2 image: sys: id: 4BGLzXecpqKOsuwwiIaM6K created_at: !ruby/object:DateTime 2015-12-07 20:31:44.334000000 Z updated_at: !ruby/object:DateTime 2015-12-07 20:31:44.334000000 Z title: CHANAS0103 description: url: "//images.ctfassets.net/xt8ne4gbbocd/4BGLzXecpqKOsuwwiIaM6K/a4318baa413e590cc6fb087d62888382/CHANAS0103.jpg" caption: Desert landscape, <NAME>. 2013,2034.8309 ©TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3738722&partId=1&searchText=2013,2034.8309&page=1 - sys: id: 6EhIOeplUA6ouw2kiOcmWe created_at: !ruby/object:DateTime 2018-02-27 16:37:41.994000000 Z updated_at: !ruby/object:DateTime 2018-02-27 16:37:41.994000000 Z content_type_id: chapter revision: 1 title_internal: 'Landscape: thematic, chapter 4' body: | This idea that the landscape is not a passive backdrop but an experiential one took hold in archaeology in the early 1990s with an interest in the *Phenomenology of Landscape* (Tilley,1994). The basic premise of this philosophical approach is how humans’ experience ‘being’ in their worlds, whereby the idea of landscape comprises sets of relational places linked by pathways, movements and narratives. Tilley proposed that phenomenology provides a useful tool to think about how people in the past interacted sensorially with the landscape in which they lived. So how might we see the importance of landscape, or perhaps not, in the rock art of Africa? It is interesting to note that out of the hundreds of thousands of rock art images across the Continent, not a single depiction from this Collection is an unambiguous representation of a landscape as we understand it in a Western sense. There are tableaux which may include trees, shrubs, huts or features in the landscape such as bees’ nests, but there is nothing that represents a landscape scene in the modern artistic sense. And yet, we might assume that features in the landscape would have been important. For example, particular rock formations might have acted as way markers and permanent or seasonal rivers and springs would have been important places utilised by pastoralists and traders. - sys: id: 2g0O5GIiaESIIGC2OOMeuC created_at: !ruby/object:DateTime 2018-02-27 16:46:29.400000000 Z updated_at: !ruby/object:DateTime 2018-05-08 15:06:31.365000000 Z content_type_id: image revision: 2 image: sys: id: XUV6CjD6QouOWCoI8OoSq created_at: !ruby/object:DateTime 2018-02-27 16:39:42.859000000 Z updated_at: !ruby/object:DateTime 2018-02-27 16:39:42.859000000 Z title: ALGTDR0080001 description: url: "//images.ctfassets.net/xt8ne4gbbocd/XUV6CjD6QouOWCoI8OoSq/f3f968e869e63fc59eb186a2d6c9a4c3/ALGTDR0080001.jpg" caption: 'A unique sandstone inselberg over 17 metres high, resembling a hedgehog standing on a pedestal in the Tadrart Acacus Mountains, Algeria. 2013,2034.4750 ©TARA/<NAME> ' col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3605250&partId=1&searchText=2013,2034.4750+&page=1 - sys: id: 4Zj7sd5KJW4Eq2i4aSmQSS created_at: !ruby/object:DateTime 2018-02-27 16:48:08.048000000 Z updated_at: !ruby/object:DateTime 2018-05-08 15:07:07.463000000 Z content_type_id: image revision: 2 image: sys: id: 7eyjgnirUkqiwIQmwc8uoe created_at: !ruby/object:DateTime 2016-09-26 14:56:40.370000000 Z updated_at: !ruby/object:DateTime 2016-09-26 14:56:40.370000000 Z title: NAMDMT0010062 description: url: "//images.ctfassets.net/xt8ne4gbbocd/7eyjgnirUkqiwIQmwc8uoe/827acd6affabc436c4124be861493437/NAMDMT0010062.jpg" caption: A rock formation named the “lion’s mouth” at Twyfelfontein in Namibia. 2013,2034.22084 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3763124&partId=1&searchText=2013,2034.22084&page=1 - sys: id: 5I9qkMsO5iqI0s6wqQkisk created_at: !ruby/object:DateTime 2018-02-27 16:53:04.584000000 Z updated_at: !ruby/object:DateTime 2018-05-08 15:08:04.758000000 Z content_type_id: image revision: 2 image: sys: id: Wmt1hBD2MwmGYUQccaIuW created_at: !ruby/object:DateTime 2018-02-27 16:50:31.783000000 Z updated_at: !ruby/object:DateTime 2018-02-27 16:50:31.783000000 Z title: SOANTC0020004 description: url: "//images.ctfassets.net/xt8ne4gbbocd/Wmt1hBD2MwmGYUQccaIuW/118e2f905481c14f6a1abb2119d564bc/SOANTC0020004.jpg" caption: 160 metres of glaciated andesite bedrock of the Riet River covered with more than 3500 engravings of different geometric motifs, seasonally exposed as the river rises and falls. Driekops Eiland, South Africa. 2013,2034.18616. © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3730621&partId=1&searchText=2013,2034.18616&page=1 - sys: id: 6WsItqVm8wawokCiCgE4Gu created_at: !ruby/object:DateTime 2018-02-27 17:27:42.253000000 Z updated_at: !ruby/object:DateTime 2018-02-27 17:27:42.253000000 Z content_type_id: chapter revision: 1 title_internal: 'Landscape: thematic, chapter 5' body: "The following rock art studies demonstrate both the advantages of a landscape approach in thinking about the placement of images and the creation of special places, but also the role of cultural subjectivity in understanding the importance of landscape.\n\nA study of the Brandberg Mountain in Namibia has shown the decision making processes involved in the placement of rock art images. The Brandberg is Nambia’s highest mountain and is located in the north-western Namib Desert. Although rainfall is low in the region, the granite composition of the massif means that water can be stored in “pans, crevices and pot holes from one rainy season to another”, making this an advantageous resource in an arid landscape (Lenssen-Erz, 2004:132). \n" - sys: id: 1631tf7fv4QUwei0IIEk6I created_at: !ruby/object:DateTime 2018-02-27 17:28:59.999000000 Z updated_at: !ruby/object:DateTime 2018-05-08 14:45:43.402000000 Z content_type_id: image revision: 2 image: sys: id: 1hXbvhDSf2CmOss6ec0CsS created_at: !ruby/object:DateTime 2016-09-13 13:02:59.339000000 Z updated_at: !ruby/object:DateTime 2016-09-13 13:02:59.339000000 Z title: NAMBRG0030001 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1hXbvhDSf2CmOss6ec0CsS/0bb079e491ac899abae435773c74fcf4/NAMBRG0030001.jpg" caption: Looking out of rock shelter from the Brandberg Mountain over the Namib Desert. © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?partId=1&objectId=3729901 - sys: id: 6ycsEOIb0AgkqoQ4MUOMQi created_at: !ruby/object:DateTime 2018-05-08 15:15:59.100000000 Z updated_at: !ruby/object:DateTime 2018-05-08 15:15:59.100000000 Z content_type_id: image revision: 1 image: sys: id: rt6DZs4Zs4Ei8GIEQcGaI created_at: !ruby/object:DateTime 2018-05-08 15:11:08.119000000 Z updated_at: !ruby/object:DateTime 2018-05-08 15:11:08.119000000 Z title: NAMDMB0010003 description: url: "//images.ctfassets.net/xt8ne4gbbocd/rt6DZs4Zs4Ei8GIEQcGaI/42bd3971573897d602df6c6025365dd5/NAMDMB0010003.jpg" caption: View looking towards the Tsisab Ravine, Brandberg Mountain, Namibia. 2013,2034.21327 © TARA/David Coulson col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3771005&partId=1&searchText=2013,2034.21327&page=1 - sys: id: 2aa2jzRtPqwK8egGek6G6 created_at: !ruby/object:DateTime 2018-05-08 15:18:58.887000000 Z updated_at: !ruby/object:DateTime 2018-05-08 15:18:58.887000000 Z content_type_id: image revision: 1 image: sys: id: 5y7VeXhwTCMYQAGWIEaYiq created_at: !ruby/object:DateTime 2018-05-08 15:17:33.726000000 Z updated_at: !ruby/object:DateTime 2018-05-08 15:17:33.726000000 Z title: NAMDMB0010027 description: url: "//images.ctfassets.net/xt8ne4gbbocd/5y7VeXhwTCMYQAGWIEaYiq/2bc68cb72aa349891621fcb10179eb7a/NAMDMB0010027.jpg" caption: " View of Tsisab Ravine, Brandberg Mountain, Namibia. 2013,2034.21351 © TARA/<NAME>" col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3771053&partId=1&searchText=2013,2034.21351&page=1 - sys: id: 47L9Y10YHmWY04QWCmI4qe created_at: !ruby/object:DateTime 2018-05-08 15:23:52.878000000 Z updated_at: !ruby/object:DateTime 2018-05-08 15:23:52.878000000 Z content_type_id: image revision: 1 image: sys: id: 5gAJaqtkRUI4Ie0KCEYemk created_at: !ruby/object:DateTime 2018-05-08 15:22:31.706000000 Z updated_at: !ruby/object:DateTime 2018-05-08 15:22:31.706000000 Z title: NAMDMB0030001 description: url: "//images.ctfassets.net/xt8ne4gbbocd/5gAJaqtkRUI4Ie0KCEYemk/c097408c698e89d7aea8d02fc8573453/NAMDMB0030001.jpg" caption: View of a water stained granite boulder outside the rock art site at <NAME>helter, Namibia. 2013,2034.21385 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3771034&partId=1&searchText=2013,2034.21385&page=1 - sys: id: 175X82dwJgqGAqkqCu4CkQ created_at: !ruby/object:DateTime 2018-05-09 15:11:55.103000000 Z updated_at: !ruby/object:DateTime 2018-05-09 15:11:55.103000000 Z content_type_id: chapter revision: 1 title_internal: 'Landscape: thematic, chapter 6' body: "There are approximately 1000 rock art sites in the Brandberg, made by San&#124;Bushmen, and human occupation dates back at least 6000 years through to the 20th century. \ Depictions predominantly comprise human figures closely followed by large game animals, and the number of paintings at a site ranges widely from just one to more than 1000 images (Lenssen-Erz, 2004:138). San&#124;Bushmen used the mountain for economic and subsistence purposes such as food, water, shelter and raw material. The landscape was categorised based on certain characteristics,although each site could have served more than one purpose. For example, sites that were associated with conspicuous landmarks in the landscape; short or long-term living sites; aggregation sites; and casual or deliberate ritual sites. The majority of sites are casual ritual sites with long-term living and aggregation sites quite rare (Lenssen-Erz, 2004:147). For the most part San&#124;Bushmen visited infrequently, in small groups and for short term durations, and the placement of rock art sites seem to be at these locations. Although the choice of place may have been initially motivated by practical concerns, once at a spot, the place was often used for ritual activities. It has been proposed that ritual activity “increases in frequency if a group is facing more than ordinary problems” (Lenssen-Erz, 2004:148), and although the San&#124;Bushmen went to the Brandberg because of an advantageous ecosystem, they often seem to have been in a state of crisis, for example in times of drought (Lenssen-Erz, 2004:148). The strategies chosen to mitigate such crises, was the recurring performance of rituals, including the creation of rock art, to cope with the critical environmental circumstances, thus maintaining some semblance of social stability. \n\nIn an insightful study in South Africa, Smith and Blundell (2004) attempted to interpret northern South African rock art from a landscape approach to identify its relevance in this context. Southern African rock art has benefitted from many years of intensive and systematic research as well as valuable ethnographic and ethnohistorical records. As such, the meaning of rock art in this region is well understood in comparison to other parts of the continent and as a result makes a useful test case.\n\nThe study area focused on the northern province of South Africa, where three types of rock art traditions are found. The oldest, that of the San&#124;Bushmen is characterised by fine brushwork of humans and animals, typically in red pigment (Smith and Blundell, 2004:254). Concurrent with the San tradition are finger painted geometric designs, although the authorship is unknown. Finally, superimposing these are a variety of images, that include quadrupeds, spread-eagled designs, people, locomotives, wagons and guns that stylistically are attributable to Bantu-speaking farmer peoples who inhabited parts of eastern, central and southern Africa (Smith and Blundell, 2004:255). Of the more than 300 sites in the study area, there appeared to be no clear pattern between the placement of San&#124;Bushmen rock art or geometric art and features in the landscape (Smith and Blundell, 2004:255). In fact, San&#124;Bushmen rock art relates to “the power and experiences of San religious specialists with the other world – the realm of god, the spirits and mythical creatures … (and) it is argued that paintings sites were places of negotiation” (Smith and Blundell, 2004:256). The power of place for San&#124;Bushmen was mediated through the physical rock face upon which the images were inscribed, which acted as a veil between the physical world and the spiritual world. As such, landscape is conceptual for San&#124;Bushmen and in the absence of the ethnographic records explaining this phenomenon, a landscape approach provides no insightful observations in this context (Smith and Blundell, 2004:256). \n\nIn contrast, farmer art is more closely tied to the landscape. It is confined to hilly areas only, with a significant number located in shaded valleys near perennial water sources, which from a pastoralist perspective would make sense (Smith and Blundell, 2004:257). The composition of the images, the vivid white imagery and the seemingly aggressive subject matter might suggest that the art demonstrated territories, warning away other herding groups with evidence of conflict between groups. However, ethnography indicates that farmer art in this region actually is inextricably linked with boys’ initiation ceremonies. The sites are close to water so that boys can bathe after circumcision. Sheep and cows are painted not because people herded them but for important instructional educational purposes. And what may be perceived as images of aggression actually reflect the upheavals of the 19th century Ddebel and Swazi raiders (Smith and Blundell, 2004:258).\n" - sys: id: 5CGHVFKSUEA0oqY0cS2Cgo created_at: !ruby/object:DateTime 2018-05-09 15:15:54.601000000 Z updated_at: !ruby/object:DateTime 2018-05-09 15:15:54.601000000 Z content_type_id: image revision: 1 image: sys: id: 1rRAJpaj6UMCs6qMKsGm8K created_at: !ruby/object:DateTime 2018-05-09 15:14:41.480000000 Z updated_at: !ruby/object:DateTime 2018-05-09 15:14:41.480000000 Z title: SOANTC0050054 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1rRAJpaj6UMCs6qMKsGm8K/f92d2174d4c5109237ab00379c2088b7/SOANTC0050054.jpg" caption: Engraved boulder in the landscape northern Cape Namakwa District Municipality, South Africa. 2013,2034.18803 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?assetId=1613144248&objectId=3731055&partId=1 - sys: id: 60mUuKWzEkUMUeg4MEUO68 created_at: !ruby/object:DateTime 2018-05-09 15:17:50.584000000 Z updated_at: !ruby/object:DateTime 2018-05-09 15:17:59.757000000 Z content_type_id: image revision: 2 image: sys: id: 1yhBeyGEMYkuay2osswcyg created_at: !ruby/object:DateTime 2018-05-09 15:16:49.135000000 Z updated_at: !ruby/object:DateTime 2018-05-09 15:16:49.135000000 Z title: SOANTC0030004 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1yhBeyGEMYkuay2osswcyg/7cab20823cbc01ae24ae6456d6518dbd/SOANTC0030004.jpg" caption: View from the looking towards ponds or kuils. Wildebeest Kuil, South Africa. 2013,2034.18668 © TARA/<NAME> col_link: http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3730725&partId=1&searchText=2013,2034.18668&page=1 - sys: id: 5AvLn9pvKoeYW2OKqwkUgQ created_at: !ruby/object:DateTime 2018-05-09 15:20:22.816000000 Z updated_at: !ruby/object:DateTime 2018-05-09 15:20:22.816000000 Z content_type_id: chapter revision: 1 title_internal: 'Landscape: thematic, chapter 7' body: | As Smith and Blundell have shown, a landscape approach to rock art in northern South Africa would have been “embarrassingly far off the mark” (2004:258) without being able to draw on ethnographic and ethnohistorical information. This does not negate the validity of a landscape approach as a legitimate and rational method of analysis, what is of concern for Smith and Blundell is “those arguments that treat landscape as an unproblematic given” (2004:259). The physical nature of rock art, its immovability, means that it is fixed in a landscape. Those landscapes can be expansive or confined; they can be conspicuously visually arresting and subtly nuanced. The rationale behind the siting of rock art are varied, but ultimately these are “pictures in place” (Chippindale and Nash, 2004:1) and the importance of place is socially and culturally constructed. citations: - sys: id: 5z9VWU8t2MeaiAeQWa0Ake created_at: !ruby/object:DateTime 2018-05-09 15:25:02.891000000 Z updated_at: !ruby/object:DateTime 2018-05-09 15:25:02.891000000 Z content_type_id: citation revision: 1 citation_line: "<NAME>. 2004. ‘The landscape setting of rock-painting sites in the Brandberg (Namibia): infrastructure, Gestaltung, use and meaning’, in Christopher Chippindale and George Nash (eds), The Figured Landscapes of Rock Art: Looking at Pictures in Place. Cambridge: Cambridge University Press.\n\nChippindale, C. and <NAME>. (Eds) (2004) The Figured Landscapes of Rock-Art: Looking at pictures in place. Cambridge: Cambridge University Press.\n\nGooley, Tristan. 2010. ‘Natural Navigation with the Tuareg in the Libyan Sahara', in Navigation News, March 2010. [http://www.naturalnavigator.com/the-library/navigating-with-the-tuareg](http://www.naturalnavigator.com/the-library/navigating-with-the-tuareg) \n\n<NAME>. and <NAME>. 2004. 'Dangerous ground: a critique of landscape in rock art-studies', in Christopher Chippindale and George Nash (eds), The Figured Landscapes of Rock Art: Looking at Pictures in Place. Cambridge: Cambridge University Press.\n\nTilley, C. 1994. A Phenomenology of Landscape: Places, Paths and Monuments. Oxford: Berg.\n" background_images: - sys: id: 1yhBeyGEMYkuay2osswcyg created_at: !ruby/object:DateTime 2018-05-09 15:16:49.135000000 Z updated_at: !ruby/object:DateTime 2018-05-09 15:16:49.135000000 Z title: SOANTC0030004 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1yhBeyGEMYkuay2osswcyg/7cab20823cbc01ae24ae6456d6518dbd/SOANTC0030004.jpg" - sys: id: 1rRAJpaj6UMCs6qMKsGm8K created_at: !ruby/object:DateTime 2018-05-09 15:14:41.480000000 Z updated_at: !ruby/object:DateTime 2018-05-09 15:14:41.480000000 Z title: SOANTC0050054 description: url: "//images.ctfassets.net/xt8ne4gbbocd/1rRAJpaj6UMCs6qMKsGm8K/f92d2174d4c5109237ab00379c2088b7/SOANTC0050054.jpg" ---
f571653138f299532bd382356bfab0542ac95d08
[ "Ruby", "HTML", "Markdown", "JavaScript", "Shell" ]
89
Markdown
kingsdigitallab/african-rock-art
1407a7d0bec811cec6a1cd6702f4bcbfbd6f2100
cfb10b9de2d328a139e042f988eb2d54fac0c3bc
refs/heads/master
<repo_name>natalia-guedes/DigitalHouse_FrontEnd<file_sep>/exercicio_06/images/Color _ FCFBE3 _ vanilla cream __ COLOURlovers_files/ModalWindow.class.js.download var ModalWindow = new Class.create({ initialize: function(options) { this.options = Object.isString(options) ? options.evalJSON(true) : options; if ($("cl-modal-window") === null) { var body = document.getElementsByTagName("body")[0]; body.appendChild(Builder.node("div",{id: "cl-modal-window",style: "display: none;"})) body.appendChild(Builder.node("div",{id: "cl-modal-window-background",style: "display: none;"})) } this.isVisible = false; this.modalWindow = $("cl-modal-window"); this.modalBackground = $("cl-modal-window-background"); this.options.width = this.options.width || 400; this.options.body = this.options.body || ""; this.options.showHr = this.options.showHr || true; this.options.btns = this.options.btns || []; this.options.btnAlign = this.options.btnAlign || "right"; this.drawContent(); // preload media content in cache Event.observe(window,"resize",function(event) { if (this.isVisible) { this.show(false); } }.bind(this)); }, drawContent: function() { this.modalWindow.style.width = (this.options.width.toString() + "px"); // Build content var content = ""; if (this.options.body !== "") { content += this.options.body; } if (this.options.showHr) { content += "<div class=\"hr\"></div>"; } if (this.options.btns.length !== 0) { if (this.options.btnAlign === "right") { this.options.btns = this.options.btns.reverse(); } var btn = {}, formID = "", style = "",closeBtnIDs = [], href = ""; for (var i=0,numBtns=this.options.btns.length;i<numBtns;i++) { btn = this.options.btns[i]; btn.method = btn.method || "get"; btn.closeModal = btn.closeModal || false; btn.onClick = btn.onClick || ""; formID = ""; style = ""; btnID = "cl-modal-btn-" + i.toString(); if (btn.method === "post") { formID = "cl-modal-form-" + i.toString(); content += "<form action=\"" + btn.href + "\" method=\"post\" id=\"" + formID + "\" class=\"hidden-form\"></form>"; btn.onClick = "if ($('" + formID + "').hasClassName('submitted') === false) { $('" + formID + "').addClassName('submitted'); $('" + formID + "').submit(); } return false;"; } if (btn.closeModal) { btn.href = "#"; btn.onClick += "return false;"; closeBtnIDs.push(btnID); } if (this.options.btnAlign === "left") { style = " mr-10"; } else { style = " ml-10"; } href = btn.href; if (btn.method === "post") { href = "#"; } content += "<a href=\"" + href + "\" id=\"" + btnID + "\" class=\"short-modal-pill " + this.options.btnAlign + style + "\"" + ((btn.onClick !== "") ? " onclick=\"" + btn.onClick + "\"" : "") + "><span></span>" + btn.title + "</a>"; } content += "<div class=\"clear\"></div>"; } // Build window this.modalWindow.innerHTML = ""; if (this.options.title !== undefined) { this.modalWindow.innerHTML += "<h2>" + this.options.title + "</h2>"; } if (content !== "") { this.modalWindow.innerHTML += "<div class=\"modal-content\">" + content + "</div>"; } // Assign events to close btns for (var i=0,numCloseBtns=closeBtnIDs.length;i<numCloseBtns;i++) { Event.observe(closeBtnIDs[i],"click",this.hide.bind(this)); } }, show: function(draw) { this.isVisible = true; if (draw) { this.drawContent(); } var dimensions = this.modalWindow.getDimensions(); var pageSize = getPageSize(); var left = ((pageSize[0] - dimensions.width) / 2); var top = ((pageSize[3] - dimensions.height) / 2); this.modalWindow.style.top = "100px"; this.modalWindow.style.left = (left < 0) ? 0 : left.toString() + "px"; this.modalWindow.style.top = (top < 0) ? 0 : top.toString() + "px"; this.modalBackground.setOpacity(0.6); this.modalBackground.show(); this.modalWindow.show(); }, hide: function() { this.isVisible = false; this.modalBackground.hide(); this.modalWindow.hide(); } });<file_sep>/Aula_07/js/funcao.js /*function dizerOi (nome) { console.log("oi "+ nome); } dizerOi("Natalia"); */ //Função anonima /* var dizerOla = function (nome) { return "Olá " + nome; } console.log(dizerOla("natalia")); */ // falar sobre hoisting da função da normal /* function circunferencia (raio){ function diametro (){ return 2*raio; } return Math.PI * diametro(); } console.log(circunferencia(2)); */ /* function a(callback){ setTimeout( function()){ console.log('a vem primeiro'); callback(); } 3000; } function b(){ console.log('b vem depois'); } a(b); */ /* let teste =(number)=> { let primo = "O número " + number + " é primo"; let noPrimo = "O número " + number + " não é primo"; let result = noPrimo; for (i = 2; i < number; i++) { result = primo if (number % i === 0) { result = noPrimo; break; } } if (number === 2) { result = primo; } return console.log(result); }; teste(3); */ function a(callback){ for (var i=10;i>=0;i--){ console.log(i); setTimeout( function(){ callback(); }, 10000 ); } } function b(){ console.log("feliz ano novo"); } a( b ); <file_sep>/exercicio_06/images/Color _ FCFBE3 _ vanilla cream __ COLOURlovers_files/global.js.download var _domIsLoaded = false, _j = 0, _angle = 0, _width = 0, _height = 0, _paletteIsCPW = false, _timeOut = 0; var _currentPage = "", _timeout = {}, _cookieDomain = location.hostname.toLowerCase().match(/^[^.]+(.+)/)[1]; var _monthNames = ["January","February","March","April","May","June","July","August","September","October","November","December"]; var _cl_timeouts = {_checkForUserNameAvailability: 0,_hideAllNavItems :0,_autoGrowingRow: 0}, _lastUserNameChecked = "", _currentPosition = 0, _originalValues = {}; /* // This should work in IE, Firefox and Chrome. window.onerror = function() { $$("input.javascript-errors").each(function(_element) { _element.value += (Object.toJSON(this) + "\n"); }.bind(arguments)); return false; // Pass error to browser }; // Bring Opera up to speed... -- http://stackoverflow.com/questions/645840/mimic-window-onerror-in-opera-using-javascript/6342356#6342356 if (window.opera !== undefined) { (function () { var _oldToString = Error.prototype.toString; Error.prototype.toString = function () { var _msg = ""; try { _msg = _oldToString.apply(this,arguments); window.onerror(_msg,(typeof (this) === "object") ? this.stack : "",""); } catch (e) {} return _msg; }; }()); } */ jQuery.noConflict()(function($) { $('a[rel=tipsy]').tipsy({live: true, html: true, gravity: 's'}); }); Event.observe(window,"resize",function(_event) { positionLogInDropDown(); }); function intval(n,radix) { n = parseInt(n,radix || 10); return isNaN(n) ? 0 : n; } function floatval(n) { n = parseFloat(n); return isNaN(n) ? 0.0 : n; } function positionLogInDropDown() { if (($("log-in-drop-down") !== null) && ($("log-in-drop-down").className === "selected")) { $("log-in-drop-down-contents").style.visibility = "hidden"; $("log-in-drop-down-contents").style.display = "block"; var position = $("log-in-drop-down").cumulativeOffset(); var logInBtnDimmensions = $("log-in-drop-down").getDimensions(); var logInDivWidth = $("log-in-drop-down-contents").getWidth(); $("log-in-drop-down-contents").style.left = ((position.left - logInDivWidth + logInBtnDimmensions.width).toString() + "px"); $("log-in-drop-down-contents").style.top = ((position.top + logInBtnDimmensions.height - 1).toString() + "px"); // - 1 to hide it under the btn $("log-in-drop-down-contents").style.visibility = "visible"; } } function loadLogInDropDownContents() { window.headerLogInFormExists = true; $("log-in-drop-down-contents").update('<iframe src="https://' + location.hostname + '/ajax/header-log-in-form?r=' + encodeURIComponent(location.href) + '" frameborder="0" height="110" width="270" marginheight="0" marginwidth="0" scrolling="no" auto="no" style="background-color: #ffffff;"></iframe>'); } document.observe("dom:loaded",function(_event) { var _body = document.getElementsByTagName("body")[0]; _body.appendChild(Builder.node("div",{id: "cl-overlay-content",className: "cl-overlay-content",style: "display: none;"})); _body.appendChild(Builder.node("div",{id: "cl-overlay",className: "cl-overlay",style: "display: none;"})); $("cl-overlay").setOpacity(0.8); /* Label Overlay */ $$('div.label-overlay label').each(function(label) { label.observe('click', function() { this.hide(); }.bind(label)); }); $$('div.label-overlay input').each(function(input) { input.observe('focus', function() { this.previous('label').hide(); }.bind(input)); input.observe('blur', function() { if (this.value === '') { this.previous('label').show(); } }.bind(input)); if (input.value !== '') { input.previous('label').hide(); } else { input.previous('label').show(); } }); /* Log In Drop Down */ if ($("log-in-drop-down") !== null) { Event.observe("log-in-drop-down","mouseenter",function(_event) { if (window.headerLogInFormExists !== true) { loadLogInDropDownContents(); } }); Event.observe("log-in-drop-down","click",function(_event) { if (window.headerLogInFormExists !== true) { loadLogInDropDownContents(); } if ($("log-in-drop-down").className === "selected") { showObtrusiveElements(); $("log-in-drop-down").className = ""; $("log-in-drop-down-contents").style.display = "none"; } else { hideObtrusiveElements(); $("log-in-drop-down").className = "selected"; positionLogInDropDown(); } }); } /* Account Drop Down */ if ($("account-drop-down") !== null) { Event.observe("account-drop-down","mouseover",function(_event) { $("account-drop-down-contents").style.visibility = "visible"; $("account-drop-down-contents").style.height = "auto"; this.setStyle({border: '1px solid #cccccc'}); this.style.border = '1px solid #cccccc;'; }); Event.observe("account-drop-down","mouseout",function(_event) { $("account-drop-down-contents").style.visibility = "hidden"; $("account-drop-down-contents").style.height = "0"; this.setStyle({border: 'none'}); this.style.border = 'none'; }); } /* Online Users */ if ($('online-users-pop-up') !== null) { var onlineUsersScrollBar = new Control.ScrollBar('online-users-scroll-content', 'online-users-scroll-track'); var OnlineUsersPopUp = new Class.create({ initialize: function() { this.timeout = 0; if ($("online-users-pop-up") !== null) { Event.observe(window, "resize", function(_event) { this.resetPosition(); }.bind(this)); $("online-users-pop-up").observe("mouseover", function() { this.show(); }.bind(this)); $("online-users-pop-up").observe("mouseout",function() { this.delayHide(); }.bind(this)); if ($("online-users-trigger") !== null) { this.resetPosition(); $("online-users-trigger").observe("mouseover", function() { this.show(); }.bind(this)); $("online-users-trigger").observe("mouseout", function() { this.delayHide(); }.bind(this)); } if ($("hide-online-users-pop-up") !== null) { $("hide-online-users-pop-up").observe("click", function(e) { e.stop(); }.bind(this)); } } }, hide: function() { $("online-users-pop-up").hide(); $("online-users-trigger").removeClassName('hover'); }, delayHide: function() { this.timeout = this.hide.delay(0.1); }, show: function() { onlineUsersScrollBar.recalculateLayout(); clearTimeout(this.timeout); $("online-users-trigger").addClassName('hover'); $("online-users-pop-up").show(); }, resetPosition: function() { $("online-users-pop-up").clonePosition($("online-users-trigger"), { setTop: false, setWidth: false, setHeight: false, offsetLeft: $("online-users-trigger").getWidth() / 2 - $("online-users-pop-up").getWidth() / 2 + 1 }); } }); window.OnlineUsersPopUp = new OnlineUsersPopUp(); } /* Tour Pop Up */ var TourPopUp = new Class.create({ initialize: function() { this.timeout = 0; if ($("tour-pop-up") !== null) { Event.observe(window, "resize", function(_event) { this.resetPosition(); }.bind(this)); $("tour-pop-up").observe("mouseover", function() { this.show(); }.bind(this)); $("tour-pop-up").observe("mouseout",function() { this.delayHide(); }.bind(this)); if ($("tour-btn") !== null) { this.resetPosition(); $("tour-btn").observe("mouseover", function() { this.show(); }.bind(this)); $("tour-btn").observe("mouseout", function() { this.delayHide(); }.bind(this)); } if ($("hide-tour-pop-up") !== null) { $("hide-tour-pop-up").observe("click", function(e) { this.unstick(); e.stop(); }.bind(this)); } } }, hide: function() { $("tour-pop-up").hide(); $("tour-btn").removeClassName('hover'); }, delayHide: function() { if (this.isSticky() === false) { this.timeout = this.hide.delay(0.1); } }, show: function() { if (this.isSticky() === false) { clearTimeout(this.timeout); } $("tour-btn").addClassName('hover'); $("tour-pop-up").show(); }, resetPosition: function() { $("tour-pop-up").clonePosition($("tour-btn"), { setTop: false, setWidth: false, setHeight: false, offsetLeft: $("tour-btn").getWidth() / 2 - $("tour-pop-up").getWidth() / 2 }); }, stick: function() { $("tour-pop-up").addClassName("sticky"); this.show(); }, unstick: function() { this.hide(); $("tour-pop-up").removeClassName("sticky"); }, isSticky: function() { return $("tour-pop-up").hasClassName("sticky"); }, setTitle: function(title) { $("tour-title").update(title); }, setMessage: function(message) { $("tour-message").update(message); }, setButtonText: function(buttonText) { $("tour-button-text").update(buttonText); }, setBarWidth: function(barWidth) { $$("a#tour-btn span.bar")[0].setStyle({width: barWidth + 'px'}); } }); window.tourPopUp = new TourPopUp(); // - - - window._numNavItems = 0; window._lastNavItem = false; for (var _i=0;;_i++) { _element = $("nav_" + _i.toString()); if (_element === null) { break; } window._numNavItems++; Event.observe(_element,"mouseover",function(_event) { clearTimeout(_cl_timeouts._hideAllNavItems); var _element = Event.element(_event); var _index = getNumericIDFromElementID(_element.id); var _position = _element.cumulativeOffset(); if ((window._lastNavItem !== false) && (window._lastNavItem !== _index)) { hideAllNavItems(); } $("nav_" + _index.toString()).className = "hover"; window._lastNavItem = _index; var _subNav = $("sub-nav_" + _index.toString()); if(_index.toString() != '4'){ //try to fix google webcache browse ul/li _subNav.style.left = (_position.left.toString() + "px"); _subNav.style.top = ((_position.top + _element.getHeight()+15).toString() + "px"); } _subNav.show(); }); Event.observe(_element,"mouseout",function(_event) { _cl_timeouts._hideAllNavItems = hideAllNavItems.delay(0.5); }); Event.observe(("sub-nav_" + _i.toString()),"mouseover",function(_event) { clearTimeout(_cl_timeouts._hideAllNavItems); }); Event.observe(("sub-nav_" + _i.toString()),"mouseout",function(_event) { _cl_timeouts._hideAllNavItems = hideAllNavItems.delay(0.5); }); $$("#sub-nav_" + _i.toString() + " span").each(function(_element) { Event.observe(_element,"mouseover",function(_event) { this.className = "active"; }.bind(_element)); Event.observe(_element,"mouseout",function(_event) { this.className = ""; }.bind(_element)); }); } function hideAllNavItems() { for (var _i=0;_i<window._numNavItems;_i++) { $("sub-nav_" + _i.toString()).hide(); $("nav_" + _i.toString()).className = ""; } }; /* Global Search Type */ if ($('global-search-type') !== null) { function globalSearchDocumentHandler(e) { var element = Event.element(e); if (element.descendantOf('global-search-type') === false) { $('global-search-type-menu').hide(); $('global-search-type-trigger').removeClassName('active'); document.stopObserving('click', globalSearchDocumentHandler); } } var globalsearch_offsetleft = 40; if(isMobile()){ globalsearch_offsetleft = -55; } Event.observe('global-search-type-trigger', 'click', function(_event) { $('global-search-type-menu').clonePosition($('global-search-type-trigger'), { setWidth: false, setHeight: false, offsetTop: 26, offsetLeft: globalsearch_offsetleft }); $('global-search-type-trigger').toggleClassName('active'); $('global-search-type-menu').toggle(); if ($('global-search-type-menu').visible()) { document.observe('click', globalSearchDocumentHandler); } else { document.stopObserving('click', globalSearchDocumentHandler); } }); $$('#global-search-type-menu a').each(function(a) { a.observe('click', function(e) { $('global-search-type-menu').hide(); $('global-search-type-trigger').className = a.classNames(); $('global-search-query-label').update(a.readAttribute('data-label')); $('global-search-form').writeAttribute('action', a.readAttribute('data-action')); document.stopObserving('click', globalSearchDocumentHandler); e.stop(); }); }); } /* Global Create Button */ if ($('global-create') !== null) { function globalCreateDocumentHandler(e) { var element = Event.element(e); if (element.descendantOf('global-create') === false) { $('global-create-menu').hide(); $('global-create-trigger').removeClassName('active'); document.stopObserving('click', globalCreateDocumentHandler); } } var globalcreate_offsetleft = 0; if(isMobile()){ globalcreate_offsetleft = -98; } Event.observe('global-create-trigger', 'click', function(_event) { $('global-create-menu').clonePosition($('global-create-trigger'), { setWidth: false, setHeight: false, offsetTop: 29, offsetLeft: globalcreate_offsetleft/*-($('global-search').getWidth()) + $('global-search-type').getWidth()*/ }); $('global-create-trigger').toggleClassName('active'); $('global-create-menu').toggle(); if ($('global-create-menu').visible()) { document.observe('click', globalCreateDocumentHandler); } else { document.stopObserving('click', globalCreateDocumentHandler); } }); } // - - - ["trend-search-query","blog-search-query"].each(function(_element) { if ($(_element) !== null) { _originalValues[_element] = $(_element).value; Event.observe(_element,"click",function() { if (this.value === _originalValues[_element]) { this.value = ""; this.className = "active"; } }); Event.observe(_element,"focus",function() { if (this.value === _originalValues[_element]) { this.value = ""; this.className = "active"; } }); Event.observe(_element,"blur",function() { if (this.value.strip() === "") { this.value = _originalValues[_element]; this.className = ""; } }); } }); // - - - if ($("channel-chooser_0") !== null) { var _element; window._numChannelTabs = 0; for (var _i=0;;_i++) { _element = $("channel-chooser_" + _i.toString()); if (_element === null) { break; } window._numChannelTabs++; Event.observe(_element,"click",function(_event) { var _index = getNumericIDFromElementID(Event.element(_event).id); for (var _i=0;_i<window._numChannelTabs;_i++) { $("channel-chooser_" + _i.toString()).className = ""; } $("channel-chooser_" + _index.toString()).className = "selected"; new Ajax.Request("/ajax/index-channels",{ method: "get", parameters: "channelID=" + _index.toString(), onSuccess: function(_transport) { $("channel-content").update(_transport.responseText); } }); }); } } // - - - if (($("feature-followers_followers-btn") !== null) && ($("feature-followers_following-btn") !== null)) { featureFollowerHandler = function(_event) { var _element = Event.element(_event); ["followers","following"].each(function(_element) { $("feature-followers_" + _element + "-btn").removeClassName("selected"); $("feature-followers_" + _element).style.display = "none"; }); $(_element).addClassName("selected"); $(_element.id.replace(/-btn$/,"")).style.display = "block"; }; Event.observe("feature-followers_followers-btn","click",featureFollowerHandler); Event.observe("feature-followers_following-btn","click",featureFollowerHandler); } // - - - if ($("userName_register") !== null) { Event.observe("userName_register","keyup",userName_registerOnChange); // Typing Event.observe("userName_register","blur",userName_registerOnChange); // Mouse right-click + paste } _domIsLoaded = true; }); // - - - function setAutoGrowFeatures() { if (window._autoGrowIsAnimating === undefined) { window._autoGrowIsAnimating = {}; } if (window._autoGrowCloseWhenOpened === undefined) { window._autoGrowCloseWhenOpened = {}; } $A(arguments).each(function (_argument) { if (Object.isArray(_argument)) { setAutoGrowFeatures(_argument); } else { Event.observe(_argument + "-overlay","mousemove",function(_event) { window._autoGrowCloseWhenOpened[this.toString()] = false; }.bind(_argument)); Event.observe(_argument + "-item","mouseenter",function(_event) { clearTimeout(_cl_timeouts._autoGrowingRow); window._autoGrowCloseWhenOpened[this.toString()] = false; _cl_timeouts._autoGrowingRow = (function() { var _type = (/([a-z]+)-/).exec(this.toString())[1]; var _elementID = (this.toString() + "-overlay"); var _height = 115; var _duration = 0.3; var _effects = []; if ($(_elementID).getHeight() === _height) { return; } if (window._autoGrowIsAnimating[this.toString()]) { return; } _effects.push("new Effect.Morph(\"" + _elementID + "\",{sync: true,style: \"margin-top: 0; height: " + _height.toString() + "px;\"})"); _effects.push("new Effect.Opacity(\"" + _elementID + "\",{to: 1.0,duration: 0.0})"); if (_type === "p") { var _colorElements = $$("#" + _elementID + " a.palette span.c"); var _shadowElements = $$("#" + _elementID + " a.palette span.c span.s"); _effects.push("new Effect.Morph(\"" + $$("#" + _elementID + " a.palette")[0].identify() + "\",{sync: true,style: \"height: " + _height.toString() + "px;\"})"); for (var _i=0,_rows=_colorElements.length;_i<_rows;_i++) { _effects.push("new Effect.Morph(\"" + _colorElements[_i].identify() + "\",{sync: true,style: \"height: " + _height.toString() + "px;\"})"); } for (var _i=0,_rows=_shadowElements.length;_i<_rows;_i++) { _effects.push("new Effect.Morph(\"" + _shadowElements[_i].identify() + "\",{sync: true,style: \"margin-top: " + (_height - 5).toString() + "px;\"})"); } } else if (_type === "c") { _effects.push("new Effect.Morph(\"" + $$("#" + _elementID + " a.color")[0].identify() + "\",{sync: true,style: \"height: " + _height.toString() + "px;\"})"); _effects.push("new Effect.Morph(\"" + $$("#" + _elementID + " a.color span")[0].identify() + "\",{sync: true,style: \"margin-top: " + (_height - 5).toString() + "px;\"})"); } else if ((_type === "n") || (_type === "pd") || (_type === "h")) { _effects.push("new Effect.Morph(\"" + $$("#" + _elementID + " a.pattern")[0].identify() + "\",{sync: true,style: \"height: " + _height.toString() + "px;\"})"); _effects.push("new Effect.Morph(\"" + $$("#" + _elementID + " a.pattern span")[0].identify() + "\",{sync: true,style: \"margin-top: " + (_height - 5).toString() + "px;\"})"); } else if (_type === "s") { _effects.push("new Effect.Morph(\"" + $$("#" + _elementID + " a.shape")[0].identify() + "\",{sync: true,style: \"height: " + _height.toString() + "px;\"})"); _effects.push("new Effect.Morph(\"" + $$("#" + _elementID + " a.shape span.image")[0].identify() + "\",{sync: true,style: \"height: " + _height.toString() + "px;\"})"); _effects.push("new Effect.Morph(\"" + $$("#" + _elementID + " a.shape span.image span")[0].identify() + "\",{sync: true,style: \"margin-top: " + (_height - 5).toString() + "px;\"})"); } $(_elementID).show(); eval("new Effect.Parallel([" + _effects.join(",") + "],{duration: " + _duration.toString() + ",transition: Effect.Transitions.easeOutCubic});"); window._autoGrowIsAnimating[this.toString()] = true; (function() { delete window._autoGrowIsAnimating[this.toString()]; if (window._autoGrowCloseWhenOpened[this.toString()]) { hideAutoGrowFeature(_argument); } }.bind(this)).delay(_duration); }.bind(this)).delay(0.5); }.bind(_argument)); Event.observe(_argument + "-item","mouseleave",function(_event) { clearTimeout(_cl_timeouts._autoGrowingRow); }); Event.observe(_argument + "-overlay","mouseleave",hideAutoGrowFeature.bind(_argument)); } }); } function hideAutoGrowFeature(_argument) { clearTimeout(_cl_timeouts._autoGrowingRow); if (_argument instanceof Event) { _argument = this.toString(); } window._autoGrowCloseWhenOpened[_argument] = true; var _type = (/([a-z]+)-/).exec(_argument)[1]; var _elementID = (_argument + "-overlay"); var _height = 50; var _duration = 0.3; var _effects = []; if ($(_elementID).getHeight() === _height) { return; } if (window._autoGrowIsAnimating[_argument]) { return; } _effects.push("new Effect.Morph(\"" + _elementID + "\",{sync: true,style: \"margin-top: 20px; height: " + _height.toString() + "px;\"})"); if (_type === "p") { var _colorElements = $$("#" + _elementID + " a.palette span.c"); var _shadowElements = $$("#" + _elementID + " a.palette span.c span.s"); _effects.push("new Effect.Morph(\"" + $$("#" + _elementID + " a.palette")[0].identify() + "\",{sync: true,style: \"height: " + _height.toString() + "px;\"})"); for (var _i=0,_rows=_colorElements.length;_i<_rows;_i++) { _effects.push("new Effect.Morph(\"" + _colorElements[_i].identify() + "\",{sync: true,style: \"height: " + _height.toString() + "px;\"})"); } for (var _i=0,_rows=_shadowElements.length;_i<_rows;_i++) { _effects.push("new Effect.Morph(\"" + _shadowElements[_i].identify() + "\",{sync: true,style: \"margin-top: " + (_height - 5).toString() + "px;\"})"); } } else if (_type === "c") { _effects.push("new Effect.Morph(\"" + $$("#" + _elementID + " a.color")[0].identify() + "\",{sync: true,style: \"height: " + _height.toString() + "px;\"})"); _effects.push("new Effect.Morph(\"" + $$("#" + _elementID + " a.color span")[0].identify() + "\",{sync: true,style: \"margin-top: " + (_height - 5).toString() + "px;\"})"); } else if ((_type === "n") || (_type === "pd") || (_type === "h")) { _effects.push("new Effect.Morph(\"" + $$("#" + _elementID + " a.pattern")[0].identify() + "\",{sync: true,style: \"height: " + _height.toString() + "px;\"})"); _effects.push("new Effect.Morph(\"" + $$("#" + _elementID + " a.pattern span")[0].identify() + "\",{sync: true,style: \"margin-top: " + (_height - 5).toString() + "px;\"})"); } else if (_type === "s") { _effects.push("new Effect.Morph(\"" + $$("#" + _elementID + " a.shape")[0].identify() + "\",{sync: true,style: \"height: " + _height.toString() + "px;\"})"); _effects.push("new Effect.Morph(\"" + $$("#" + _elementID + " a.shape span.image")[0].identify() + "\",{sync: true,style: \"height: " + _height.toString() + "px;\"})"); _effects.push("new Effect.Morph(\"" + $$("#" + _elementID + " a.shape span.image span")[0].identify() + "\",{sync: true,style: \"margin-top: " + (_height - 5).toString() + "px;\"})"); } eval("new Effect.Parallel([" + _effects.join(",") + "],{duration: " + _duration.toString() + ",transition: Effect.Transitions.easeOutCubic});"); window._autoGrowIsAnimating[this.toString()] = true; (function() { delete window._autoGrowIsAnimating[_argument]; $(_elementID).hide(); }).delay(_duration); (function () { new Effect.Opacity(_elementID,{to: 0.0,duration: 0.2}); }).delay(0.1); } registerAccountSettingsOverlay = function() { Event.observe(window,"load",function(_event) { var _h = ($("sponsored-user-settings").getHeight().toString() + "px"); $("non-sponsored-user-settings-overlay").setOpacity(0.8).setStyle({height: _h}); $("non-sponsored-user-settings-container").setStyle({height: _h,marginTop: "-" + _h,display: "none"}).appear({duration: 0.6}); }); }; CheckboxRangeCheck = Class.create({ initialize: function(_formID,_checkboxIdPrefix,_checkboxIdRegex) { this._lastCheckboxClickedID = ""; this._checkboxIdPrefix = _checkboxIdPrefix; this._checkboxIdRegex = _checkboxIdRegex; var _elements = $$("#" + _formID + " input[type=checkbox]").findAll(function(_element) { return this.test(_element.id); }.bind(this._checkboxIdRegex)); if (_elements.length !== 0) { _elements.each(function (_element) { Event.observe(_element,"click",function(_event) { var _element = Event.element(_event); if (_event.shiftKey) { if (this._lastCheckboxClickedID !== "") { if ((_element.checked) && ($(this._lastCheckboxClickedID).checked)) { var _startIndex = parseInt(this._checkboxIdRegex.exec(this._lastCheckboxClickedID)[1],10); var _endIndex = parseInt(this._checkboxIdRegex.exec(_element.id)[1],10); if (_endIndex < _startIndex) { var _tmp = _startIndex; _startIndex = _endIndex; _endIndex = _tmp; } var _i = _startIndex; while (true) { ++_i; if (_i > _endIndex) { break; } $(this._checkboxIdPrefix + _i.toString()).checked = true; } } } } this._lastCheckboxClickedID = _element.id; }.bind(this)); }.bind(this)); } } }); // Stolen from Lightbox: getPageSize = function() { var xScroll, yScroll; if (window.innerHeight && window.scrollMaxY) { xScroll = window.innerWidth + window.scrollMaxX; yScroll = window.innerHeight + window.scrollMaxY; } else if (document.body.scrollHeight > document.body.offsetHeight){ xScroll = document.body.scrollWidth; yScroll = document.body.scrollHeight; } else { xScroll = document.body.offsetWidth; yScroll = document.body.offsetHeight; } var windowWidth, windowHeight; if (self.innerHeight) { if(document.documentElement.clientWidth){ windowWidth = document.documentElement.clientWidth; } else { windowWidth = self.innerWidth; } windowHeight = self.innerHeight; } else if (document.documentElement && document.documentElement.clientHeight) { windowWidth = document.documentElement.clientWidth; windowHeight = document.documentElement.clientHeight; } else if (document.body) { windowWidth = document.body.clientWidth; windowHeight = document.body.clientHeight; } if(yScroll < windowHeight){ pageHeight = windowHeight; } else { pageHeight = yScroll; } if(xScroll < windowWidth){ pageWidth = xScroll; } else { pageWidth = windowWidth; } return [pageWidth,pageHeight,windowWidth,windowHeight]; }; function getPageScroll() { var yScroll; if (self.pageYOffset) { yScroll = self.pageYOffset; } else if (document.documentElement && document.documentElement.scrollTop) { yScroll = document.documentElement.scrollTop; } else if (document.body) { yScroll = document.body.scrollTop; } return ['',yScroll]; }; // / Stolen from Lightbox closeSiteBanner = function(_elementID,_ts) { Effect.BlindUp(_elementID,{duration: 0.5}); if ($("header-colors") !== null) { (function() { $("header-colors").appear({duration: 0.3}); }).delay(0.5); } setCookie("hide-site-banner-" + _ts.toString(),1,(3600 * 24 * 365)); }; setCookie = function(_name,_value,_expiresFromNow) { _expiresFromNow = parseInt(_expiresFromNow,10); _expires = new Date(); if ((isNaN(_expiresFromNow) === false) && (_expiresFromNow !== 0)) { _expires.setTime((new Date()).getTime() + (_expiresFromNow * 1000)); // Convert to microseconds } document.cookie = (_name + "=" + escape(_value) + "; expires=" + _expires.toGMTString() + "; path=/; domain=" + _cookieDomain); }; getRandStr = function(_length) { var _chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890"; var _numChars = _chars.length; var _return = ""; _length = parseInt(_length,10); for (var _i=0;_i<_length;_i++) { _return += _chars.substr(Math.floor(Math.random() * _numChars),1); } return _return; }; userName_registerOnChange = function(_event) { clearTimeout(_cl_timeouts._checkForUserNameAvailability); _cl_timeouts._checkForUserNameAvailability = checkForUserNameAvailability.bind(this,_event).delay(0.7); }; checkForUserNameAvailability = function(_event) { if (this.value !== _lastUserNameChecked) { new Ajax.Request("/ajax/check-username-availability",{ sanitizeJSON: true, method: "post", parameters: "userName=" + encodeURIComponent(this.value), onSuccess: function(_transport) { var _text = "Uh oh, that Username is taken."; var _class = "message-error"; if (_transport.responseJSON._status === "available") { _text = "Nice Username, suits you well."; _class = "message-success"; } else if (_transport.responseJSON._status === "invalid-email") { _text = "Username must not be email addresses."; _class = "message-error"; } $("userName_registerIndicator").update(_text); $("userName_registerIndicator").className = _class; $("userName_registerIndicator").appear({duration: 0.4}); } }); _lastUserNameChecked = this.value; } }; getS3URL = function(_url) { return "http://static.colourlovers.com" + _url; }; getStaticURL = function(_url) { return "http://static.colourlovers.com" + _url; }; returnEmptyStringIfUndefinedOrNull = function(_value) { return ((_value === undefined) || (_value === null)) ? "" : _value; }; getImgURL = function(_uri,_userLang) { var _userLang = (_userLang === undefined) ? _lang : _userLang; return getStaticURL("/images/" + _cSV + "/" + _userLang + _uri); }; getNumericallyShardedDirectory = function(_path,_id,_levels) { var _dir = ""; _levels = parseInt(_levels,10); if (_levels === 1) { // id = 1234567: /1234 _dir = _path.replace((/%s/),Math.floor(_id / 1000)); } else if (_levels === 2) { // id = 1234567: /123/1234 _dir = _path.replace((/%s/),Math.floor(_id / 10000) + "/" + Math.floor(_id / 1000)); } else if (_levels === 3) { // id = 1234567: /123/1234/1234567 _dir = _path.replace((/%s/),Math.floor(_id / 10000) + "/" + Math.floor(_id / 1000) + "/" + _id); } return _dir; } getNumericIDFromElementID = function(_elementID) { // Expects something like: someID_123 return parseInt((/^[^\s]+_([0-9]+)$/).exec(_elementID)[1],10); }; within=function(_val,_low,_high){alert("use isWithinRange()");}; isHex=function(_hex){alert("use isValidHex()");}; Array.prototype.implode=function(_char){alert("implode deprecated, use join()");}; isWithinRange = function(_val,_low,_high) { return ((_val >= _low) && (_val <= _high)); }; isValidHex = function(_hex) { return (/^[a-fA-F0-9]{6}$/).test(_hex); }; dec2hex = function(_dec) { var _hexChars = "0123456789ABCDEF", _hex = ""; while (_dec > 15) { _hex = (_hexChars.charAt((_dec - (Math.floor(_dec / 16)) * 16)) + _hex); _dec = Math.floor(_dec / 16); } return (_hexChars.charAt(_dec) + _hex); }; hex2dec = function(_hex) { return parseInt(_hex,16); }; // copaso, FCP addEvent = function(_function,_event) { if ((document.all) && (window.attachEvent)) { window.attachEvent("on" + _event,_function); } else if (window.addEventListener) { window.addEventListener(_event,_function,false); } }; //Used by FCP domEvent = function(_event) { _event = (_event) ? _event : window.event; // Opera hates this for some reason: if (!window.opera && _event.srcElement) { _event.target = _event.srcElement; } if (_event.keyCode) { _event.code = _event.keyCode; } else if (_event.which) { _event.code = _event.which; } else { _event.code = _event.charCode; } return _event; }; forumPollRadioOnClick = function(_this) { if ($("pollAnswerOther") !== null) { $("pollAnswerOther").disabled = !(_this.id === "pollOptionID_1"); } $("addACommentSubmitBtn").value = "Post Comment and Cast Vote"; $("pollOptionID_comment").value = _this.value; if ($("forumCastVoteSubmitBtnDiv").style.display === "none") { Effect.BlindDown("forumCastVoteSubmitBtnDiv",{duration: 0.4}); } }; togglePollDisplay = function(_area,_element) { if (_area === "forums") { if (_element.checked) { $("discussion-comment-required").className = ""; Effect.BlindDown("add-poll-div",{duration: 0.4}); } else { $("discussion-comment-required").className = "required"; Effect.BlindUp("add-poll-div",{duration: 0.4}); } for (var _i=0;_i<10;_i++) { $("pollOptions_" + _i).disabled = !_element.checked; $("pollOptionURLs_" + _i).disabled = !_element.checked; } $("pollTitle").disabled = !_element.checked; $("pollEndDate_day").disabled = !_element.checked; $("pollEndDate_month").disabled = !_element.checked; $("pollEndDate_year").disabled = !_element.checked; $("pollDesc").disabled = !_element.checked; $("commentBox").disabled = _element.checked; } }; // Check teatarea length // checkTALen = function(_elementID,_length) { var _taLength = $(_elementID).value.length; var _numLeft = (_length - _taLength); _numLeft = (_numLeft < 0) ? 0 : _numLeft; $(_elementID + "count").update(_numLeft + " Characters Left"); if (_taLength > _length) { $(_elementID).value = $(_elementID).value.substr(0,_length); $(_elementID + "count").innerText = "0 Characters Left"; } }; // prototype absPos = function(_object) { var r = {x: _object.offsetLeft,y: _object.offsetTop}; if (_object.offsetParent) { var v = absPos(_object.offsetParent); r.x += v.x; r.y += v.y; } return r; }; paletteDetail = function() { if (_paletteColorsUI === undefined) { return; } var _widths = [], _heights = [], _elements = []; var _pageSize = getPageSize(); var _numColors = _paletteColorsUI._colors.length; var _width = (_pageSize[2] - 150); var _height = (_pageSize[3] - 150); _angle = (_angle === 4) ? 0 : _angle; if ((_angle % 2) === 1) { // Laying down _heights = palette_getConstraintWidths(_height); for (var _i=0;_i<_numColors;_i++) { _elements.push(Builder.node("a",{className: "block",href: "#",onclick: "return false;",style: "width: " + _width.toString() + "px; height: " + _heights[_i] + "px; background-color: #" + _paletteColorsUI._colors[_i] + ";"})); } } else { // Standing up _widths = palette_getConstraintWidths(_width); for (var _i=0;_i<_numColors;_i++) { _elements.push(Builder.node("a",{className: "left block",onclick: "return false;",style: "width: " + _widths[_i] + "px; height: " + _height.toString() + "px; background-color: #" + _paletteColorsUI._colors[_i] + ";"})); } } if (_angle >= 2) { _elements.reverse(); } $("cl-overlay-content").update(); $("cl-overlay-content").appendChild(Builder.node("span",{className: "block",style: "height: " + (_paletteColorsUI._y.toString() + "px")},_elements)); $("cl-overlay-content").appendChild(Builder.node("span",{className: "clear"})); $("cl-overlay-content").style.width = (_width) + "px"; $("cl-overlay-content").style.height = (_height) + "px"; $("cl-overlay-content").onclick = hideOverlay; showOverlay([_width,_height]); }; colorDetail = function() { if (_colorUiHex === undefined) { return; } var _pageSize = getPageSize(); var _width = (_pageSize[2] - 150); var _height = (_pageSize[3] - 150); $("cl-overlay-content").style.backgroundColor = ("#" + _colorUiHex);; $("cl-overlay-content").style.width = (_width) + "px"; $("cl-overlay-content").style.height = (_height) + "px"; $("cl-overlay-content").onclick = hideOverlay; showOverlay([_width,_height]); }; patternImgDetail = function(_patternID,_location,_ts) { if (_patternID === 0) { _url = _location; } else { _url = getS3URL("/images/patterns/" + parseInt(_patternID / 1000,10) + "/" + _patternID + ".png?" + _ts.toString()); } var _pageSize = getPageSize(); $("cl-overlay-content").style.background = "transparent url(" + _url + ") center center"; $("cl-overlay-content").style.width = (_pageSize[2] - 150) + "px"; $("cl-overlay-content").style.height = (_pageSize[3] - 150) + "px"; $("cl-overlay-content").onclick = hideOverlay; showOverlay([(_pageSize[2] - 150),(_pageSize[3] - 150)]); }; function patternDefinitionDetail(_patternDefinitionID,_ts) { _url = getStaticURL("/images/patternDefinitions/" + parseInt(_patternDefinitionID / 10000,10) + "/" + parseInt(_patternDefinitionID / 1000,10) + "/" + _patternDefinitionID + ".png?" + _ts.toString()); var _pageSize = getPageSize(); $("cl-overlay-content").style.background = "transparent url(" + _url + ") center center"; $("cl-overlay-content").style.width = (_pageSize[2] - 150) + "px"; $("cl-overlay-content").style.height = (_pageSize[3] - 150) + "px"; $("cl-overlay-content").onclick = hideOverlay; showOverlay([(_pageSize[2] - 150),(_pageSize[3] - 150)]); } hideObtrusiveElements = function() { // Hide all object / embed elements - Thanks, lightbox $$("select","object","embed").each(function(_element) { _element.style.visibility = "hidden"; }); }; showObtrusiveElements = function() { // Show all object / embed elements - Thanks, lightbox $$("select","object","embed").each(function(_element) { _element.style.visibility = "visible"; }); }; // Overlay // showOverlay = function(_overlayContentDimensions) { var _pageSize = getPageSize(); _lastOverlayDimensions = _overlayContentDimensions; hideObtrusiveElements(); $("cl-overlay").style.height = (_pageSize[1] + "px"); $("cl-overlay").show(); var _overlayContentTop = (getPageScroll()[1] + ((_pageSize[3] - _overlayContentDimensions[1] - 20) / 2)); // -20 for border var _overlayContentLeft = ((_pageSize[0] - _overlayContentDimensions[0] - 20) / 2); // -20 for border $("cl-overlay-content").style.top = (_overlayContentTop < 0) ? 0 : _overlayContentTop.toString() + "px"; $("cl-overlay-content").style.left = (_overlayContentLeft < 0) ? 0 : _overlayContentLeft.toString() + "px"; $("cl-overlay-content").show(); $("cl-overlay").style.height = (getPageSize()[1] + "px"); }; hideOverlay = function() { $("cl-overlay").hide(); $("cl-overlay-content").hide(); showObtrusiveElements(); }; modComment = function(_commentType,_commentID,_commentI) { if (_domIsLoaded) { var _modDiv = $(_commentType + "_cm_" + _commentID); var _modDivHeight = $(_commentI).getHeight() + 31; // OB31E var _comment = _modDiv.innerHTML.base64_decode(); var _textareaID = ("comments" + _commentType + _commentID + _commentI); _modDiv.update(); var _modCommentForm = document.createElement("form"); _modCommentForm.setAttribute("action","/op/mod/comment/" + _commentType + "/" + _commentID.toString()); _modCommentForm.setAttribute("method","post"); _modDiv.insertBefore(_modCommentForm,_modDiv.firstChild); var _submitBtn = document.createElement("input"); _submitBtn.setAttribute("type","image"); _submitBtn.setAttribute("class","outline"); _submitBtn.setAttribute("src",getImgURL("/btn/submit.png")); _modCommentForm.insertBefore(_submitBtn,_modCommentForm.firstChild); var _commentTextarea = document.createElement("textarea"); _commentTextarea.setAttribute("name","comments"); _commentTextarea.setAttribute("id",_textareaID); _commentTextarea.onselect = new Function("storeCaret($('" + _textareaID + "'));"); _commentTextarea.onclick = new Function("storeCaret($('" + _textareaID + "'));"); _commentTextarea.onkeyup = new Function("storeCaret($('" + _textareaID + "'));"); _commentTextarea.onchange = new Function("storeCaret($('" + _textareaID + "'));"); _commentTextarea.className = "formElement"; _commentTextarea.style.width = "440px"; _commentTextarea.style.border = "0 none"; _commentTextarea.style.backgroundColor = "#FFF5F5"; _commentTextarea.style.height = (_modDivHeight.toString() + "px"); _commentTextarea.style.marginBottom = "10px"; _modCommentForm.insertBefore(_commentTextarea,_modCommentForm.firstChild); _commentTextarea.value = _comment; var _htmlBtns = document.createElement("div"); _htmlBtns.className = "html-btns"; _htmlBtns.innerHTML = "<a href=\"#\" onclick=\"fmtTxt('" + _textareaID + "','<strong>','</strong>'); return false;\" class=\"bold\" title=\"Bold\" /><span></span></a>"; _htmlBtns.innerHTML += "<a href=\"#\" onclick=\"fmtTxt('" + _textareaID + "','<em>','</em>'); return false;\" class=\"italic\" title=\"Italic\" /><span></span></a>"; _htmlBtns.innerHTML += "<a href=\"#\" onclick=\"fmtTxtUnderline('" + _textareaID + "'); return false;\" class=\"underline\" title=\"Underline\" /><span></span></a>"; /*_htmlBtns.innerHTML += "<a href=\"#\" onclick=\"fmtTxtImage('" + _textareaID + "'); return false;\" class=\"image\" title=\"Insert Image\" /><span></span></a>"; _htmlBtns.innerHTML += "<a href=\"#\" onclick=\"fmtTxtURL('" + _textareaID + "'); return false;\" class=\"url\" title=\"Insert Link\" /><span></span></a>";*/ _htmlBtns.innerHTML += "<a href=\"#\" onclick=\"fmtTxt('" + _textareaID + "','<blockquote>','</blockquote>'); return false;\" class=\"blockquote\" title=\"Quote\" /><span></span></a>"; _htmlBtns.innerHTML += "<span class=\"notice\">Some HTML OK</span>\n"; _modCommentForm.insertBefore(_htmlBtns,_modCommentForm.firstChild); $(_commentType + "_mc_" + _commentID).update("Options Disabled While Editing"); $(_commentI).style.display = "none"; _modDiv.style.display = "block"; _commentTextarea.focus(); } }; buildAjaxRequest = function(_uri,_args,_callback) { var _parameters = ((_args !== undefined) ? "args=" + encodeURIComponent(_args) : ""); if (Object.isFunction(_callback) === false) { _callback = function(_transport) { var _responseArray = _transport.responseText.split("|"); if (_responseArray[0] === "redirect") { window.location.href = _responseArray[1]; } }; } new Ajax.Request("/ajax/" + _uri,{ parameters: _parameters, onSuccess: function(_transport) { this(_transport); }.bind(_callback) }); }; buildAjaxUpdaterRequest = function(_file,_args,_page,_parameters,_showLoadingFlash,_updateElementID,_anchor) { // Only use this for get requests which will return HTML // _file needs to also be the elementID of the update()able HTML container, unless _updateElementID is set // _args is optional, NEEDS TO LOOK LIKE THIS: p/12/223 // _page is optional, needs to be an integer // _parameters is optional, needs to be a JSON string // _showLoadingFlash is optional, needs to be bool // _updateElementID is optional, needs to be a string // _anchor is optional, needs to be a string _args = Object.isString(_args) ? ("/" + _args) : ""; _page = (Object.isString(_page) || Object.isNumber(_page)) ? parseInt(_page,10) : 1; _page = ("/_page_" + _page.toString()); _parameters = Object.isString(_parameters) ? _parameters.evalJSON(true) : ""; if (Object.isString(_updateElementID)) { if (_parameters === "") { _parameters = {"contentElementID": _updateElementID}; } else { _parameters["contentElementID"] = _updateElementID } } else { _updateElementID = _file; } if ($(_updateElementID) === null) { alert("ERROR: Cannot find element: " + _updateElementID); } new Ajax.Request("/ajax/" + _file + _args + _page,{ method: "get", parameters: _parameters, onSuccess: function(_transport) { $(this._updateElementID).update(_transport.responseText); if (this._anchor !== undefined) { goToAnchor(_anchor); } }.bind({_updateElementID: _updateElementID,_anchor: _anchor}) // Otherwise the string will bind as an Object }); }; goToAnchor = function(_anchor) { if (_anchor.strip() !== "") { var _element = $$("a[name=" + _anchor + "]")[0]; if (_element !== undefined) { Effect.ScrollTo(_element,{duration: 0.5}); } else { // JIC window.location.href = (window.location.href.replace((/#.+/),"") + "#" + _anchor); } } }; palette_getConstraintWidths = function(_constraint) { if (_paletteColorsUI._widths === undefined) { return palette_getEvenWidths(_constraint); } _constraint = parseInt(_constraint,10); var _return = []; var _tmp = 0; var _total = 0; var _numColors = _paletteColorsUI._colors.length; if (_numColors !== 0) { for (var _i=0;_i<_numColors;_i++) { _tmp = Math.round(_constraint * _paletteColorsUI._widths[_i]); _return[_i] = _tmp; _total += _tmp; } var _offset = parseFloat(_constraint - _total); if (_offset !== 0.0) { _return[_numColors - 1] = parseInt(_return[_numColors - 1] + _offset,10); } } return _return; }; function palette_getEvenWidths(_constraint,_numColors) { _constraint = parseInt(_constraint,10); _numColors = (_numColors === undefined) ? _paletteColorsUI._colors.length : _numColors; var _return = []; if (_numColors !== 0) { var _fill = Math.floor(_constraint / _numColors); for (var _i=0;_i<_numColors;_i++) { _return.push(_fill); } var _total = (_fill * _numColors); var _i = 0; while (_constraint !== _total) { _return[_i++]++; ++_total; } } return _return; }; function palette_getUniversalColorsUI(_width,_height,_url,_hexs,_widths,_showbottomShadow,_includeLink) { _width = parseInt(_width,10); _height = parseInt(_height,10); _widths = (_widths === undefined) ? false : _widths; _showbottomShadow = (_showbottomShadow === undefined) ? true : _showbottomShadow; _includeLink = (_includeLink === undefined) ? true : _includeLink; var _numColors = _hexs.length; var _return = ""; if (_widths === false) { _widths = palette_getEvenWidths(_width,_numColors); } _marginTop = (_height - 5); _return += _includeLink ? "<a href=\"" + _url + "\" class=\"palette\" style=\"width: " + _width.toString() + "px; height: " + _height.toString() + "px;\">" : ""; for (_i=0;_i<_numColors;_i++) { _return += "<span class=\"c\" style=\"width: " + _widths[_i].toString() + "px; height: " + _height.toString() + "px; background-color: #" + _hexs[_i] + ";\">" + (_showbottomShadow ? "<span class=\"s\" style=\"margin-top: " + _marginTop.toString() + "px;\"></span>" : "") + "</span>\n"; } _return += _includeLink ? "</a>" : ""; return _return; } updatePaletteColorsUI = function() { if (_paletteColorsUI === undefined) { return; } var _widths = [], _heights = [], _elements = []; var _pageSize = getPageSize(); var _numColors = _paletteColorsUI._colors.length; var _url = "/paletteImgDetail/" + _pageSize[0] + "/" + _pageSize[1] + "/" + _paletteColorsUI._colors.join("/") + "/" + _paletteColorsUI._title + ".png"; if (_paletteColorsUI._widths !== undefined) { _url += "?cPW=" + _paletteColorsUI._widths.join(",").base64_encode(); } _angle = (_angle === 4) ? 0 : _angle; if ((_angle % 2) === 1) { // Laying down _heights = palette_getConstraintWidths(_paletteColorsUI._y); for (var _i=0;_i<_numColors;_i++) { _elements.push(Builder.node("a",{className: "pointer block",href: "#",onclick: "paletteDetail(); return false;",style: "width: " + _paletteColorsUI._x.toString() + "px; height: " + _heights[_i] + "px; background-color: #" + _paletteColorsUI._colors[_i] + ";"})); } } else { // Standing up _widths = palette_getConstraintWidths(_paletteColorsUI._x); for (var _i=0;_i<_numColors;_i++) { _elements.push(Builder.node("a",{className: "left pointer block",href: "#",onclick: "paletteDetail(); return false;",style: "width: " + _widths[_i] + "px; height: " + _paletteColorsUI._y.toString() + "px; background-color: #" + _paletteColorsUI._colors[_i] + ";"})); } } if (_angle >= 2) { _elements.reverse(); } $("palette-colors-ui").update(); $("palette-colors-ui").appendChild(Builder.node("span",{className: "block",style: "height: " + (_paletteColorsUI._y.toString() + "px")},_elements)); $("palette-colors-ui").appendChild(Builder.node("span",{className: "clear"})); $("palette-colors-ui").style.width = (_paletteColorsUI._x.toString() + "px"); }; rotatePaletteUI = function() { ++_angle; updatePaletteColorsUI(); }; rmLoveNoteConf = function(_amt) { _amt = parseInt(_amt,10); var _go = false; if (_amt === 1) { _go = confirm("Are you sure you want to Delete this Love Note?"); } else { _go = confirm("Are you sure you want to Delete these Love Notes?"); } if (_go) { $("rm-love-notes-form").submit(); } }; toggleAll = function(_className,_element) { if (_domIsLoaded) { $$("." + _className).each(function (_element) { _element.checked = this.checked; }.bind(_element)); } }; setCaret = function(_elementID,_position) { if ($(_elementID).createTextRange) { var _range = $(_elementID).createTextRange(); _range.move("character",_position); _range.select(); } else if ($(_elementID).selectionStart) { $(_elementID).setSelectionRange(_position,_position); } }; prepareNextAddRmScoreState = function () { if (window._nextAddRmScoreState === undefined) { window._nextAddRmScoreState = {}; } }; addScore = function (_contextType,_contextID,_signature,_btnID,_unloveThisBtnID,_loveNumDiv) { _contextID = parseInt(_contextID,10); if (isNaN(_contextID) === false) { prepareNextAddRmScoreState(); if (window._nextAddRmScoreState[_contextType + _contextID.toString()] === "rm") { return false; } window._nextAddRmScoreState[_contextType + _contextID.toString()] = "rm"; new Ajax.Request("/ajax/add/score/" + _contextType + "/" + _contextID.toString() + "/" + _signature,{ method: "post", onSuccess: function(_transport) { if ($(this._btnID) !== null) { $(this._btnID).fade({duration: 0.4}); } if ($(this._unloveThisBtnID) !== null) { (function() { $(this).appear({duration: 0.4}); }.bind(this._unloveThisBtnID)).delay(0.5); } if ($(this._loveNumDiv) !== null) { $(this._loveNumDiv).innerHTML = (parseInt($(this._loveNumDiv).innerHTML.replace((/,/),""),10) + 1).toString().formatNumber(); } if (_transport.responseJSON.showTourPopUp) { window.tourPopUp.setTitle(_transport.responseJSON.tourTitle); window.tourPopUp.setMessage(_transport.responseJSON.tourMessage); window.tourPopUp.setButtonText(_transport.responseJSON.tourButtonText); window.tourPopUp.setBarWidth(_transport.responseJSON.tourBarWidth); window.tourPopUp.stick(); } }.bind({_btnID: _btnID,_unloveThisBtnID: _unloveThisBtnID,_loveNumDiv: _loveNumDiv}) }); } return false; }; rmScore = function (_contextType,_contextID,_signature,_btnID,_unloveThisBtnID,_loveNumDiv) { _contextID = parseInt(_contextID,10); if (isNaN(_contextID) === false) { prepareNextAddRmScoreState(); if (window._nextAddRmScoreState[_contextType + _contextID.toString()] === "add") { return false; } window._nextAddRmScoreState[_contextType + _contextID.toString()] = "add"; new Ajax.Request("/ajax/rm/score/" + _contextType + "/" + _contextID.toString() + "/" + _signature,{ method: "post", onSuccess: function(_transport) { if ($(this._unloveThisBtnID) !== null) { $(this._unloveThisBtnID).fade({duration: 0.4}); } if ($(this._btnID) !== null) { (function() { $(this).appear({duration: 0.4}); }.bind(this._btnID)).delay(0.5); } if ($(this._loveNumDiv) !== null) { $(this._loveNumDiv).innerHTML = (parseInt($(this._loveNumDiv).innerHTML.replace((/,/),""),10) - 1).toString().formatNumber(); } }.bind({_btnID: _btnID,_unloveThisBtnID: _unloveThisBtnID,_loveNumDiv: _loveNumDiv}) }); } return false; }; function muteNotification(contextType,contextID,state,settings) { if (confirm("Are you sure you want to " + (state ? "" : "un-") + "mute this conversation?")) { jQuery.post("/ajax/" + (state ? "add" : "rm") + "/muted-notification/" + contextType + "/" + contextID.toString(),settings,function (data) { var tmp = "mute-" + contextType + "-" + contextID.toString(); jQuery("#" + (state ? "" : "un") + tmp).hide(); jQuery("#" + (state ? "un" : "") + tmp).show(); }); } } addAjaxComment = function (_contextType,_contextID,_miscVerification) { _contextID = parseInt(_contextID,10); if (isNaN(_contextID) === false) { if (_miscVerification !== undefined) { var _Verify = new Verify(); var _numFields = _miscVerification.length; for (var _i=0;_i<_numFields;_i++) { _Verify.addElement(_miscVerification[_i]); } if (_Verify_poll.verify() === false) { return false; } } var _comments = $("ajax-comments").value.stripLowerASCII().strip(); if (_comments !== "") { $("ajax-comments").value = ""; var _parameters = "comments=" + encodeURIComponent(_comments); /*by waleed*/ var recaptcha = $("g-recaptcha-response").value; _parameters += ("&g-recaptcha-response=" + encodeURIComponent(recaptcha)); /*end by waleed*/ if ($("pollID") !== null) { _parameters += ("&pollID=" + encodeURIComponent($("pollID").value)); } if ($("pollOptionID_comment") !== null) { _parameters += ("&pollOptionID=" + encodeURIComponent($("pollOptionID_comment").value)); } if ($("pollAnswerOther_comment") !== null) { _parameters += ("&pollAnswerOther=" + encodeURIComponent($("pollAnswerOther_comment").value)); } if ($("comment-loading-indicator") !== null) { $("comment-loading-indicator").show(); } new Ajax.Request("/ajax/add/comment/" + _contextType + "/" + _contextID.toString(),{ method: "post", parameters: _parameters, onSuccess: function(_transport) { var _responseArray = _transport.responseText.split("|"); if (_responseArray[0] === "login") { window.location.href = "/login?r=" + encodeURIComponent(_responseArray[1]); } location.reload(); } }); } else { alert("Please add some comments"); $("ajax-comments").activate(); } } return false; }; initModLinkCountdown = function(_elementID,_timeout,_containerElementID) { _containerElementID = (_containerElementID === undefined) ? _elementID : _containerElementID; var _args = {_elementID: _elementID,_timeout: _timeout,_containerElementID: _containerElementID}; new PeriodicalExecuter(function(_pe) { var _secondsLeft = Math.round(((this._timeout * 1000) - (new Date()).valueOf()) / 1000); var _minutesLeft = Math.floor(_secondsLeft / 60); if (_secondsLeft > 0) { _secondsLeft = Math.floor(_secondsLeft % 60); $(this._elementID).update(_minutesLeft.toString() + ":" + _secondsLeft.toString().padLeft("0",1) + " Left"); } else { $(this._elementID).update("0:00 Left"); $(this._containerElementID).fade({duration: 0.4}); _pe.stop(); } }.bindAsEventListener(_args),1); }; showDatePicker = function(_elementID,_date) { var _days = [], _daysClasses = [], _dates = []; _date = new Date((_date === undefined) ? Date.parse($(_elementID).value) : Date.parse(_date)); _date = (isNaN(_date)) ? new Date() : _date; var _numDaysInThisMonth = parseInt(32 - (new Date(_date.getFullYear(),_date.getMonth(),32).getDate()),10); var _firstDayOffset = (new Date(_date.getFullYear(),_date.getMonth(),1)).getDay(); var _numDaysInLastMonth = parseInt(32 - (new Date(_date.getFullYear(),_date.getMonth() - 1,32).getDate()),10); var _numWeeksInThisMonth = Math.ceil((_numDaysInThisMonth + _firstDayOffset) / 7); var _numDaysTrailing = parseInt((_numWeeksInThisMonth * 7) - _numDaysInThisMonth - _firstDayOffset,10); var _offset = absPos($(_elementID)); var _lastMonth = new Date(_date.getFullYear(),_date.getMonth() - 1,_date.getDate()); var _nextMonth = new Date(_date.getFullYear(),_date.getMonth() + 1,_date.getDate()); var _lastMonthURL = (_lastMonth.getMonth() + 1).toString() + "/" + _lastMonth.getDate().toString() + "/" + _lastMonth.getFullYear().toString(); var _nextMonthURL = (_nextMonth.getMonth() + 1).toString() + "/" + _nextMonth.getDate().toString() + "/" + _nextMonth.getFullYear().toString(); _lastMonth = (_monthNames[_lastMonth.getMonth()] + " " + _lastMonth.getFullYear().toString()); _nextMonth = (_monthNames[_nextMonth.getMonth()] + " " + _nextMonth.getFullYear().toString()); if (_firstDayOffset !== 0) { _days = _days.concat($A($R(_numDaysInLastMonth - _firstDayOffset + 1,_numDaysInLastMonth))); _daysClasses = _daysClasses.concat([].fill(0,_firstDayOffset," class=\"darkTD\"")); for (var _i=_firstDayOffset - 1;_i>=0;_i--) { _dates.push(new Date(_date.getFullYear(),_date.getMonth() - 1,_numDaysInLastMonth - _i)); } } _days = _days.concat($A($R(1,_numDaysInThisMonth))); _daysClasses = _daysClasses.concat([].fill(0,_numDaysInThisMonth,"")); for (var _i=1;_i<=_numDaysInThisMonth;_i++) { _dates.push(new Date(_date.getFullYear(),_date.getMonth(),_i)); } if (_numDaysTrailing !== 0) { _days = _days.concat($A($R(1,_numDaysTrailing))); _daysClasses = _daysClasses.concat([].fill(0,_numDaysTrailing," class=\"darkTD\"")); for (var _i=1;_i<=_numDaysTrailing;_i++) { _dates.push(new Date(_date.getFullYear(),_date.getMonth() + 1,_i)); } } var _buffer = ""; _buffer += "<div class=\"calendarDiv\">\n"; _buffer += "<form action=\"#\" method=\"get\" onsubmit=\"showDatePicker('" + _elementID + "',new Date($('datePicker_year').value,$('datePicker_month').value,$('datePicker_day').value)); return false;\">\n"; _buffer += "<input type=\"hidden\" id=\"datePicker_day\" value=\"" + _date.getDate() + "\" />\n"; _buffer += "<select id=\"datePicker_month\" class=\"formElement\" style=\"width: 100px;\">\n"; // In JS's 0-based format for (var _i=0;_i<_monthNames.length;_i++) { _buffer += "<option value=\"" + _i + "\"" + ((_date.getMonth() === _i) ? " selected=\"selected\"" : "") + ">" + _monthNames[_i] + "</option>"; } _buffer += "</select>"; _buffer += "<select id=\"datePicker_year\" class=\"formElement\" style=\"margin: 0 8px; width: 55px;\">\n"; for (var _i=2004;_i<(new Date()).getFullYear() + 1;_i++) { _buffer += "<option value=\"" + _i + "\"" + ((_date.getFullYear() === _i) ? " selected=\"selected\"" : "") + ">" + _i + "</option>"; } _buffer += "</select>"; _buffer += "<input type=\"submit\" class=\"formBtn\" style=\"padding: 0;\" value=\"GO\" />"; _buffer += "</form>\n"; _buffer += "<a href=\"#\" onclick=\"showDatePicker('" + _elementID + "','" + _lastMonthURL + "'); return false;\" class=\"block left\" style=\"margin: 5px 0;\">&lt;&lt; " + _lastMonth + "</a>\n"; _buffer += "<a href=\"#\" onclick=\"showDatePicker('" + _elementID + "','" + _nextMonthURL + "'); return false;\" class=\"block right\" style=\"margin: 5px 0;\">" + _nextMonth + " &gt;&gt;</a>\n"; _buffer += "<div class=\"clear\"></div>\n"; _buffer += "<table cellpadding=\"0\">\n"; _buffer += "<tr><td>S</td><td>M</td><td>T</td><td>W</td><td>T</td><td>F</td><td>S</td></td>\n"; _buffer += "</table>\n"; _buffer += "<table cellpadding=\"0\" class=\"calendarTable\">\n"; var _l = 0, _dateStr = ""; for (var _i=0;_i<_numWeeksInThisMonth;_i++) { _buffer += "<tr>\n"; for (var _j=0;_j<7;_j++) { _dateStr = _dates[_l].getDate() + "," + _dates[_l].getMonth() + "," + _dates[_l].getFullYear(); _buffer += "<td" + _daysClasses[_l] + "" + ((_date.valueOf() === _dates[_l].valueOf()) ? " style=\"background-color: #ccaaaa;\"" : "") + "><a href=\"#\" onclick=\"datePickerSetDate('" + _elementID + "'," + _dateStr + "); return false;\">" + _days[_l] + "</a></td>\n"; _l++; } _buffer += "</tr>\n"; } _buffer += "</table>\n"; _buffer += "</div>\n"; if ($("datePickerDiv") === null) { $$("body")[0].appendChild(Builder.node("div",{id: "datePickerDiv",style: "display: none; position: absolute; top: 0; left: 0; zindex: 10;"})); } $("datePickerDiv").update(_buffer); $("datePickerDiv").style.left = (_offset.x.toString() + "px"); $("datePickerDiv").style.top = ((_offset.y + 33).toString() + "px"); $("datePickerDiv").show(); document.observe("mousedown",datePickerMouseClick); }; datePickerMouseClick = function(_event) { var _element = Event.element(_event); if ((_element.descendantOf("datePickerDiv") === false) && (_element.id !== "datePickerDiv")) { datePickerHide(); } }; datePickerSetDate = function(_elementID,_day,_month,_year) { var _date = new Date(_year,_month,_day); _month = (_date.getMonth() + 1).toString(); _day = _date.getDate().toString(); $(_elementID).value = ((_month.length === 1) ? ("0" + _month) : _month) + "/" + ((_day.length === 1) ? "0" + _day : _day) + "/" + _date.getFullYear(); datePickerHide(); }; datePickerHide = function() { document.stopObserving("mousedown",datePickerMouseClick); //$("datePickerDiv").fade({duration: 0.2}); $("datePickerDiv").hide(); }; hsvSearchOnSubmit = function() { if ($("hsv") !== null) { $("hsv").value = (_hSliders.values.toString() + "|" + _sSliders.values.toString() + "|" + _bSliders.values.toString()); } }; hSliderOnSlide = function(_val,_leftSliderID,_rightSliderID) { _leftSliderID = (_leftSliderID === undefined) ? "hue1O" : _leftSliderID; _rightSliderID = (_rightSliderID === undefined) ? "hue2O" : _rightSliderID; $(_leftSliderID).style.width = (parseInt((_val[0] * 390) / 360,10) + 1) + "px"; $(_rightSliderID).style.width = ((390 - parseInt((_val[1] * 390) / 360,10)) - 1) + "px"; }; sSliderOnSlide = function(_val,_leftSliderID,_rightSliderID) { _leftSliderID = (_leftSliderID === undefined) ? "sat1O" : _leftSliderID; _rightSliderID = (_rightSliderID === undefined) ? "sat2O" : _rightSliderID; $(_leftSliderID).style.width = (parseInt((_val[0] * 390) / 100,10) + 1) + "px"; $(_rightSliderID).style.width = ((390 - parseInt((_val[1] * 390) / 100,10)) - 1) + "px"; }; bSliderOnSlide = function(_val,_leftSliderID,_rightSliderID) { _leftSliderID = (_leftSliderID === undefined) ? "bri1O" : _leftSliderID; _rightSliderID = (_rightSliderID === undefined) ? "bri2O" : _rightSliderID; $(_leftSliderID).style.width = (parseInt((_val[0] * 390) / 100,10) + 1) + "px"; $(_rightSliderID).style.width = ((390 - parseInt((_val[1] * 390) / 100,10)) - 1) + "px"; }; replyTo = function(_divID,_inputID,_userName) { var _value = (_userName.base64_decode() + " wrote:\n<blockquote>" + $(_divID).innerHTML.replace((/<br( \/)?>/gm),"").replace((/<!-- " -->$/gm),"") + "</blockquote>") if ($(_inputID).value === "") { $(_inputID).value = _value; } else { $(_inputID).value += ("\n" + _value); } $(_inputID).focus(); }; confirmRedirect = function(_question,_url) { if (confirm(_question)) { window.location.href = _url; return true; } return false; }; rmAvatar = function(_checkStr,_sex) { if (confirm("Are you sure you want to delete your Avatar?") === false) { return; } if ((_checkStr !== undefined) && (_checkStr !== null)) { var _defaultAvatar; switch (_sex) { case "f": _defaultAvatar = "noAvatarFemale"; break; case "m": _defaultAvatar = "noAvatarMale"; break; default: _defaultAvatar = "noAvatarPat"; } (new Image()).src = getImgURL("/lover/" + _defaultAvatar + ".png","_"); new Ajax.Request("/ajax/rm/avatar/" + _checkStr,{ onSuccess: function(_transport) { if (_transport.responseText === "1") { // Fade my other avatars on the screen $$(".user-avatar-5504").each(function(_element) { if (_element.tagName.toLowerCase() === "img") { _element.fade({duration: 0.6}); new Effect.Tween(_element,1.0,0.0,{duration: 0.6,afterFinish: function() { _element.src = getImgURL("/lover/" + this._defaultAvatar + ".png","_"); _element.show(); new Effect.Tween(_element,0.0,1.0,{duration: 0.4},function (_value) { $(this).setOpacity(_value); }.bind(this._element)); }.bind({_element: _element,_defaultAvatar: _defaultAvatar})},function (_value) { $(this).setOpacity(_value); }.bind(_element)); } }); // Fade element I clicked on $("avatar-container").childElements().each(function(_element) { _element.fade({duration: 0.6}); }); (function() { $("avatar-container").update("<img src=\"" + getImgURL("/lover/" + this + ".png","_") + "\" id=\"tmp-user-avatar\" class=\"mt-0\" style=\"display: none;\" alt=\"Avatar\" />"); $("tmp-user-avatar").setOpacity(0.0); $("tmp-user-avatar").appear({duration: 0.4}); }.bind(_defaultAvatar)).delay(0.6); } else { alert("Something went wrong! We were not able to remove your Avatar."); } } }); } else { alert("Something went wrong! We were not able to remove your Avatar."); } }; rmPicture = function(_checkStr) { if (confirm("Are you sure you want to delete your Picture?") === false) { return; } if ((_checkStr !== undefined) && (_checkStr !== null)) { (new Image()).src = getImgURL("/lover/noPicture.jpg","_"); new Ajax.Request("/ajax/rm/picture/" + _checkStr,{ onSuccess: function(_transport) { if (_transport.responseText === "1") { $("picture-container").childElements().each(function(_element) { _element.fade({duration: 0.6}); }); (function() { $("picture-container").update("<img src=\"" + getImgURL("/lover/noPicture.jpg","_") + "\" id=\"tmp-user-picture\" class=\"mt-0\" style=\"display: none;\" alt=\"Picture\" />"); $("tmp-user-picture").setOpacity(0.0); $("tmp-user-picture").appear({duration: 0.4}); }).delay(0.6); } else { alert("Something went wrong! We were not able to remove your Picture."); } } }); } else { alert("Something went wrong! We were not able to remove your Picture."); } }; // http://stackoverflow.com/questions/7477/autosizing-textarea#answer-948445 var AutoResizeTextarea = Class.create({ initialize: function(_elementID,_minHeight,_maxHeight,_elementWidth) { this._textarea = $(_elementID); this._minHeight = parseInt(_minHeight,10); this._maxHeight = parseInt(_maxHeight,10); this._elementWidth = parseInt(_elementWidth || this._textarea.getWidth(),10); this._textarea.observe("keyup",this.refresh.bind(this)); this._textarea.observe("input",this.refresh.bind(this)); this._textarea.observe("change",this.refresh.bind(this)); this._textarea.observe("beforepaste",this.refresh.bind(this)); this._textarea.observe("blur",this.refresh.bind(this)); this._textarea.observe("focus",this.refresh.bind(this)); this._shadow = new Element("div").setStyle({ lineHeight: this._textarea.getStyle("lineHeight"), fontSize: this._textarea.getStyle("fontSize"), fontFamily: this._textarea.getStyle("fontFamily"), textTransform: this._textarea.getStyle("textTransform"), letterSpacing: this._textarea.getStyle("letterSpacing"), textIndent: this._textarea.getStyle("textIndent"), wordSpacing: this._textarea.getStyle("wordSpacing"), position: "absolute", top: "-999999em", left: "-999999em", width: (this._elementWidth.toString() + "px") }); this._textarea.insert({after: this._shadow}); this.refresh(); }, refresh: function() { this._shadow.update($F(this._textarea).replace((/</gm),"&lt;").replace((/>/gm),"&gt;").replace((/(\r\n|\n|\r)/gm),"<br />") + "&nbsp;"); var _height = Math.min(Math.max(parseInt(this._shadow.getHeight(),10),this._minHeight),this._maxHeight); this._textarea.style.height = (_height.toString() + "px") this._textarea.style.overflow = ((_height === this._maxHeight) && (this._maxHeight !== -1)) ? "auto" : "hidden"; } }); var Verify = new Class.create({ initialize: function(_args) { this._submitBtnText = "Please wait ..."; this._submitBtnID = "submitBtn"; this._elements = []; if (_args !== undefined) { this._submitBtnText = _args._submitBtnText; this._submitBtnID = _args._submitBtnID; } }, addElement: function(_elementIDs,_verificationArgs) { if (Object.isArray(_elementIDs) === false) { _elementIDs = [_elementIDs]; } this._elements.push({_elementIDs: _elementIDs,_verificationArgs: _verificationArgs}); }, verify: function() { var _submitForm = true, _elementID = "", _type = "", _errMsg = "", _msgs = ["Whoops! Looks like we need your help fixing your information.\n---------------------------------------------------------"], _shownDefaultMsg = false; for (var _i=0;_i<this._elements.length;_i++) { if ((this._elements[_i]._elementIDs !== null) && (this._elements[_i]._elementIDs.length > 0)) { _elementID = this._elements[_i]._elementIDs[0]; if ($(_elementID) === null) { alert("'" + _elementID + "' doesn't exist in the DOM"); return false; } if (($(_elementID).hasClassName("disabled") === false) && ($(_elementID).disabled === false)) { _type = _errMsg = ""; if (this._elements[_i]._verificationArgs !== undefined) { if (this._elements[_i]._verificationArgs._type !== undefined) { _type = this._elements[_i]._verificationArgs._type; } if (this._elements[_i]._verificationArgs._errMsg !== undefined) { _errMsg = this._elements[_i]._verificationArgs._errMsg; } } this._elements[_i]._elementIDs.each(function(_field) { $(_field).removeClassName("error"); }); var val = $(_elementID).value; switch (_type) { case "url": if ((/^https?:\/\/[\-a-zA-Z0-9+&@#\/%?=~_|!:,.;]*[\-a-zA-Z0-9+&@#\/%=~_|]$/).test(val) === false) { _submitForm = false; $(_elementID).addClassName("error"); _msgs.push("URL must be valid\nex: http://www.domain.com"); } break; case "email": if ((/^[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[a-z]{2,4}|museum)\b$/i).test(val.strip()) === false) { // Used on themeleon reg page, too _submitForm = false; $(_elementID).addClassName("error"); _msgs.push("Email Address must be valid\nex: <EMAIL>"); } break; case "zip": if ((val.strip() === "") || (val.match(/[0-9]{5}/) === null)) { _submitForm = false; $(_elementID).addClassName("error"); _msgs.push("Zip Code must be valid\nex: 97216"); } break; case "checked": if ($(_elementID).checked === false) { _submitForm = false; _msgs.push(_errMsg); } break; case "numeric": if (isNaN(val) || (val === "")) { _submitForm = false; $(_elementID).addClassName("error"); _msgs.push("Value must be a Number\nex: 1234"); } break; case "select": if ($(_elementID).options[$(_elementID).selectedIndex].value === "") { _submitForm = false; $(_elementID).addClassName("error"); _msgs.push(_errMsg); } break; case "password": _badPasswd = false; _badPasswd = (val !== $(this._elements[_i]._elementIDs[1]).value) ? true : _badPasswd; // Are they the same? _badPasswd = (val.length < this._elements[_i]._verificationArgs._minLength) ? true : _badPasswd; // Length? _badPasswd = (val === "") ? true : _badPasswd; // Is it blank? if (_badPasswd) { _submitForm = false; this._elements[_i]._elementIDs.each(function(_field) { $(_field).addClassName("error"); }); _msgs.push("The passwords you entered are blank, too short or aren't the same"); } else { this._elements[_i]._elementIDs.each(function(_field) { $(_elementID).style.border = ""; }); } break; case "userName": if ((val.replace((/["#$%&')(,\/:;=>\?<{}[+^`|\]\n\r\t\\]/gm),"") !== val) || (val === "")) { // Used on themeleon reg page, too $(_elementID).addClassName("error"); _submitForm = false; _msgs.push("Usernames must NOT contain any of the following characters:\n\" # $ % & ' ) ( , / : ; = > ? < { } [ + ^ ` | ] \\\nor any new lines or tabs"); } if (/.+@.+\..+/.test(val)) { $(_elementID).addClassName("error"); _submitForm = false; _msgs.push("Usernames must not be an email address"); } break; case "groupTitle": if ((val.match(/[\\><\t\r\n]/g) !== null) || (val === "")) { $(_elementID).addClassName("error"); _submitForm = false; _msgs.push((_errMsg !== "") ? _errMsg : "The Group's Name must NOT contain any of the following characters:\n> < \\ tabs or new line characters\nPlease correct and re-submit."); } break; case "radio": var _checkCount = 0; for (var _j=0;_j<this._elements[_i]._elementIDs.length;_j++) { if ($(this._elements[_i]._elementIDs[_j]).checked) { _checkCount++; } } if (_checkCount === 0) { _submitForm = false; _msgs.push(_errMsg); } break; case "colorHex": if (isValidHex(val) === false) { $(_elementID).addClassName("error"); _submitForm = false; _msgs.push("Value must be a valid Hex value\nex: FF33CC"); } break; case "flickrID": if ((val !== "") && (val.match(/^\w+?@\w+$/) === null)) { $(_elementID).addClassName("error"); _submitForm = false; _msgs.push("Value must be a valid Flickr ID\nex: 41434087@N00"); } break; default: if (val === "") { _submitForm = false; $(_elementID).addClassName("error"); if (_errMsg !== "") { _msgs.push(_errMsg); } if (_shownDefaultMsg === false) { _msgs.push("Please Fill out all required fields. [They now have a red border]"); _shownDefaultMsg = true; } } break; } } } } if (_submitForm) { var _submitBtn = $(this._submitBtnID); if (_submitBtn !== null) { _submitBtn.disabled = true; _submitBtn.value = this._submitBtnText; } } else { alert(_msgs.join("\n\n") + "\n\n---------------------------------------------------------"); } return _submitForm; } }); // html.js storeCaret = function(_input) { if (_input.createTextRange !== undefined) { _input._caretPos = document.selection.createRange().duplicate(); } }; fmtTxt = function(_commentBoxID,_leftStr,_rightStr,_midStr) { _input = $(_commentBoxID); _input.focus(); var _selection; if ((_input._caretPos !== undefined) && (_input.createTextRange)) { // IE var _caretPos = _input._caretPos; _selection = ((_midStr === "") || (_midStr === undefined)) ? _caretPos.text : _midStr; var _length = _selection.length; var _bias = 0; if (_selection.charAt(_selection.length - 1) === " ") { // There's a trailing space: _caretPos.text = (_leftStr + _selection.substring(0,(_selection.length - 1)) + _rightStr + " "); _bias = 1; } else { // No trailing space... _caretPos.text = (_leftStr + _selection + _rightStr); } if (_length === 0) { _caretPos.moveStart("character",(_rightStr.length * -1)); _caretPos.moveEnd("character",(_rightStr.length * -1)); } else { _caretPos.moveStart("character",((_rightStr.length + _length) * -1)); _caretPos.moveEnd("character",((_rightStr.length + _bias) * -1)); } _caretPos.select(); } else if (_input.selectionStart !== undefined) { // FF var _begin = _input.value.substr(0,_input.selectionStart); if ((_midStr === "") || (_midStr === undefined)) { _selection = _input.value.substr(_input.selectionStart,(_input.selectionEnd - _input.selectionStart)); } else { _selection = _midStr; } var _end = _input.value.substr(_input.selectionEnd); var _newCursorPos = _input.selectionStart; var _scrollPos = _input.scrollTop; if (_selection.charAt(_selection.length - 1) === " ") { // There's a trailing space: _selection = _selection.substring(0,(_selection.length - 1)); _rightStr += " "; } _input.value = (_begin + _leftStr + _selection + _rightStr + _end); if (_input.setSelectionRange) { if (_selection.length === 0) { _input.setSelectionRange((_newCursorPos + _leftStr.length),(_newCursorPos + _leftStr.length)); } else { _input.setSelectionRange((_newCursorPos + _leftStr.length),(_newCursorPos + _leftStr.length + _selection.length)); } _input.focus(); } _input.scrollTop = _scrollPos; } else { _input.value += (_leftStr + _rightStr); _input.focus(); } }; fmtTxtURL = function(_commentBoxID) { var _input = $(_commentBoxID); var _insText = ""; if ((_input._caretPos !== undefined) && (_input.createTextRange)) { _insText = _input._caretPos.text; } else if (_input.selectionStart !== undefined) { _insText = _input.value.substr(_input.selectionStart,(_input.selectionEnd - _input.selectionStart)); } _url = prompt("Input the destination for this Link","http://"); if ((_url !== null) && (_url !== "")) { _text = prompt("Input the Title of this Link",_insText); if ((_url.indexOf("http://") !== 0) && (_url.indexOf("https://") !== 0)) { _url = ("http://" + _url); } if (_text === "") { _text = _url; } if ((_url !== "http://") && (_url !== null) && (_url !== undefined)) { fmtTxt(_commentBoxID,"<a href=\"" + _url + "\" target=\"_blank\">","</a>",_text); } } else { _input.focus(); } }; fmtTxtImage = function(_commentBoxID) { var _input = $(_commentBoxID); var _imgSrc = ""; _imgSrc = prompt("Input the link where the image is hosted:","http://"); if ((_imgSrc !== null) && (_imgSrc !== "")) { if ((_imgSrc.indexOf("http://") !== 0) && (_imgSrc.indexOf("https://") !== 0)) { _imgSrc = ("http://" + _imgSrc); } if ((_imgSrc !== "http://") && (_imgSrc !== null) && (_imgSrc !== undefined)) { fmtTxt(_commentBoxID,"<img src=\"","\" />",_imgSrc); } } else { _input.focus(); } }; fmtTxtUnderline = function(_commentBoxID) { // Because nesting 3 sets of quotes in HTML is unpossible: fmtTxt(_commentBoxID,"<span style=\"text-decoration: underline;\">","</span>"); }; // /html.js // Prototypes // Array.prototype.in_array = function(_needle) { for (var _i=0;_i<=this.length;_i++) { if (this[_i] === _needle) { return true; } } return false; }; Array.prototype.fill = function(_beginIndex,_end,_value) { var _array = []; for (var _i=_beginIndex;_i<_end;_i++) { _array[_i] = _value; } return _array; }; Array.prototype.sum = function() { var _sum = 0.0, _length = this.length; if (_length === 0) { return false; } for (var _i=0;_i<_length;_i++) { if (isNaN(this[_i])) { return false; } _sum += this[_i]; } return _sum; }; String.prototype.formatNumber = function(_thousandsSeparator,_decimalSeparator) { _thousandsSeparator = ((_thousandsSeparator === undefined) ? "," : _thousandsSeparator); _decimalSeparator = ((_decimalSeparator === undefined) ? "." : _decimalSeparator); var _parts = this.split(_decimalSeparator); var _whole = _parts[0]; var _decimal = ((_parts.length > 1) ? (_decimalSeparator + _parts[1]) : ""); var _regEx = (/(\d+)(\d{3})/); while (_regEx.test(_whole)) { _whole = _whole.replace(_regEx,'$1' + _thousandsSeparator + '$2'); } return (_whole + _decimal); }; String.prototype.stripLowerASCII = function() { return this.replace((/([\x00-\x08\x0b-\x0c\x0e-\x19])/g),""); }; String.prototype.padHex = function() { var _str = ("000000".toString() + this.toString()); return _str.substring((_str.length - 6),_str.length); // THANKS IE!!!! }; String.prototype.padLeft = function(_padStr,_amount) { var _finalPadStr = "", _str = ""; _amount++; for (var _i=0;_i<_amount;_i++) { _finalPadStr += _padStr.toString(); } _str = (_finalPadStr + this.toString()); return _str.substring((_str.length - _amount),_str.length); // THANKS IE!!!! }; String.prototype.base64_encode = function() { var _buffer = "", _keyStr = "<KEY>; var _char1, _char2, _char3, _enc1, _enc2, _enc3, _enc4, _i = 0; var _this = this.utf8_encode(); while (_i < _this.length) { _char1 = _this.charCodeAt(_i++); _char2 = _this.charCodeAt(_i++); _char3 = _this.charCodeAt(_i++); _enc1 = (_char1 >> 2); _enc2 = ((_char1 & 3) << 4) | (_char2 >> 4); _enc3 = ((_char2 & 15) << 2) | (_char3 >> 6); _enc4 = (_char3 & 63); if (isNaN(_char2)) { _enc3 = _enc4 = 64; } else if (isNaN(_char3)) { _enc4 = 64; } _buffer += _keyStr.charAt(_enc1) + _keyStr.charAt(_enc2) + _keyStr.charAt(_enc3) + _keyStr.charAt(_enc4); } return _buffer; }; String.prototype.base64_decode = function() { var _buffer = "", _keyStr = "<KEY>; var _char1, _char2, _char3, _enc1, _enc2, _enc3, _enc4, _i = 0; var _this = this.replace(/[^A-Za-z0-9\+\/\=]/g,""); while (_i < _this.length) { _enc1 = _keyStr.indexOf(_this.charAt(_i++)); _enc2 = _keyStr.indexOf(_this.charAt(_i++)); _enc3 = _keyStr.indexOf(_this.charAt(_i++)); _enc4 = _keyStr.indexOf(_this.charAt(_i++)); _char1 = ((_enc1 << 2) | (_enc2 >> 4)); _char2 = (((_enc2 & 15) << 4) | (_enc3 >> 2)); _char3 = (((_enc3 & 3) << 6) | _enc4); _buffer += String.fromCharCode(_char1); if (_enc3 != 64) { _buffer += String.fromCharCode(_char2); } if (_enc4 != 64) { _buffer += String.fromCharCode(_char3); } } return _buffer.utf8_decode(); }; String.prototype.utf8_encode = function() { var _this = this;//.replace(/\r\n/g,"\n"); var _buffer = "", _char = ""; for (var _i=0;_i<_this.length;_i++) { _char = _this.charCodeAt(_i); if (_char < 128) { _buffer += String.fromCharCode(_char); } else if ((_char > 127) && (_char < 2048)) { _buffer += String.fromCharCode((_char >> 6) | 192); _buffer += String.fromCharCode((_char & 63) | 128); } else { _buffer += String.fromCharCode((_char >> 12) | 224); _buffer += String.fromCharCode(((_char >> 6) & 63) | 128); _buffer += String.fromCharCode((_char & 63) | 128); } } return _buffer; }; String.prototype.utf8_decode = function() { var _buffer = "", _i = 0, _char1 = 0, _char2 = 0, _char3 = 0, _this = this; while (_i < this.length) { _char1 = _this.charCodeAt(_i); if (_char1 < 128) { _buffer += String.fromCharCode(_char1); _i++; } else if ((_char1 > 191) && (_char1 < 224)) { _char2 = _this.charCodeAt(_i + 1); _buffer += String.fromCharCode(((_char1 & 31) << 6) | (_char2 & 63)); _i += 2; } else { _char2 = _this.charCodeAt(_i + 1); _char3 = _this.charCodeAt(_i + 2); _buffer += String.fromCharCode(((_char1 & 15) << 12) | ((_char2 & 63) << 6) | (_char3 & 63)); _i += 3; } } return _buffer; }; // Custom // addEngine = function() { if ((typeof window.sidebar === "object") && (typeof window.sidebar.addSearchEngine === "function")) { window.sidebar.addSearchEngine("http://www.colourlovers.com/firefox/COLOURlovers.src",getStaticURL("/firefox/COLOURlovers.png"),"COLOURlovers","COLOURlovers Palette Search"); } else { alert("The Firefox browser is required to install this plugin."); } }; addEngine2 = function() { if ((typeof window.sidebar === "object") && (typeof window.sidebar.addSearchEngine === "function")) { window.sidebar.addSearchEngine("http://www.colourlovers.com/firefox/COLOURlovers_hex.src",getStaticURL("/firefox/COLOURlovers.png"),"COLOURlovers hex","COLOURlovers Palette HEX Search"); } else { alert("The Firefox browser is required to install this plugin."); } }; function isMobile(){try{return/Android|webOS|iPhone|iPad|iPod|pocket|psp|kindle|avantgo|blazer|midori|Tablet|Palm|maemo|plucker|phone|BlackBerry|symbian|IEMobile|mobile|ZuneWP7|Windows Phone|Opera Mini/i.test(navigator.userAgent)?!0:!1}catch(e){}}
5830f1c687c5c49c0e8176902a02aca001f0316b
[ "JavaScript" ]
3
JavaScript
natalia-guedes/DigitalHouse_FrontEnd
e411d6dfd7f7c2e7460ae608573afe498072b26a
294b0088f85a2a454adacb0896256892091cddb2
refs/heads/master
<repo_name>gt-cs2340-nongshim-shinramen/M10<file_sep>/app/src/main/java/com/example/m6/model/Player.java package com.example.m6.model; import java.io.Serializable; import java.util.Arrays; import java.util.List; import java.util.Map; @SuppressWarnings("ALL") public class Player implements Serializable { private static final long serialVersionUID= 1L; public static List<String> validDifficulty = Arrays.asList("Beginner", "Easy", "Normal", "Hard", "Impossible"); private boolean warped; private String name; private String difficulty; private Spaceship spaceship; private int pilot; private int fighter; private int trader; private int engineer; private int credit; private int cargo; private int fuel; private Map<String, Integer> inven; private Universe system; private Planet currentplanet; public Player(String name, int pilot, int fighter, int trader, int engineer, String difficulty, Universe universe, Map<String, Integer> map) { this.name = name; this.pilot = pilot; this.fighter = fighter; this.trader = trader; this.engineer = engineer; this.difficulty = difficulty; this.system = universe; inven = map; //this will be acamar solarsystem with acamar planet. currentplanet = system.getSystem().get(0).getPlanet(); credit = 1000; spaceship = Spaceship.GNAT; cargo = 0; fuel = 80; } public void setFuel(int fuel){ this.fuel = fuel; } public int getFuel(){return fuel;} public String getName() { return name; } public Universe getUniverse(){return system;} public void setCurrentplanet(Planet planet){ currentplanet = planet; } public Planet getCurrentplanet(){return currentplanet;} public void setName(String name) { this.name = name; } public String getDifficulty() { return difficulty; } public void setDifficulty(String difficulty) { this.difficulty = difficulty; } public int getPilot() { return pilot; } public void setPilot(int pilot) { this.pilot = pilot; } public int getFighter() { return fighter; } public void setFighter(int fighter) { this.fighter = fighter; } public int getTrader() { return trader; } public void setTrader(int trader) { this.trader = trader; } public int getEngineer() { return engineer; } public void setEngineer(int engineer) { this.engineer = engineer; } public int getCredit() { return credit; } public void setCredit(int credit) { this.credit = credit; } public Spaceship getSpaceship() { return spaceship; } public void setSpaceship(Spaceship spaceship) { this.spaceship = spaceship; } public int getCargo(){ return cargo; } public void setCargo(int cargo){ this.cargo = cargo; } public Map<String, Integer> getInven(){ return inven; } public boolean getWarped() { return warped; } public void setWarped(boolean warped) { this.warped = warped; } } <file_sep>/app/src/main/java/com/example/m6/model/Planet.java package com.example.m6.model; import android.util.Log; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import java.util.Random; @SuppressWarnings("ALL") public class Planet implements Serializable { private String name; private double goodsPrice; private int coordinateX; private int coordinateY; private int techLevel; private int resource; private Map<String, Integer> stock = new HashMap<>(); public Planet(String name, int coordinateX, int coordinateY, int techLevel, int resource) { this(name, 0, coordinateX, coordinateY, techLevel, resource); } public Planet(String name, double goodsPrice, int coordinateX, int coordinateY, int techLevel, int resource) { this.name = name; this.goodsPrice = goodsPrice; this.coordinateX = coordinateX; this.coordinateY = coordinateY; this.techLevel = techLevel; this.resource = resource; setStock(stock); } public Planet(String name, double goodsPrice, int coordinateX, int coordinateY, int techLevel, int resource, Map<String, Integer> stock) { this.name = name; this.goodsPrice = goodsPrice; this.coordinateX = coordinateX; this.coordinateY = coordinateY; this.techLevel = techLevel; this.resource = resource; this.stock = stock; } private void setStock(Map<String, Integer> map) { for(Goods g : Goods.values()) { final int min = 5; final int max = 30; map.put(g.toString().toLowerCase(), randInt(min, max)); Log.d("stock", String.valueOf(stock.get(g.toString().toLowerCase()))+" " +g.toString().toLowerCase()+" IN "+getName()); } } private int randInt(int min, int max) { Random rand = new Random(); return rand.nextInt((max - min) + 1) + min; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getCoordinateX() { return coordinateX; } public void setCoordinateX(int coordinateX) { this.coordinateX = coordinateX; } public int getCoordinateY() { return coordinateY; } public void setCoordinateY(int coordinateY) { this.coordinateY = coordinateY; } public int getTechLevel() { return techLevel; } public void setTechLevel(int techLevel) { this.techLevel = techLevel; } public int getResource() { return resource; } public void setResource(int resource) { this.resource = resource; } public Map <String, Integer> getStock(){return stock;} } <file_sep>/app/src/main/java/com/example/m6/views/MenuActivity.java package com.example.m6.views; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import android.widget.Button; import com.example.m6.R; import com.example.m6.model.Player; /** * Class for the MenuActivity */ @SuppressWarnings("ALL") public class MenuActivity extends AppCompatActivity implements View.OnClickListener{ private Player player; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_menu); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); player = (Player)getIntent().getSerializableExtra("player"); //this log checks whether player instance import successfully Button buyButton = findViewById(R.id.buy_button); buyButton.setOnClickListener(this); Button sellButton = findViewById(R.id.sell_button); sellButton.setOnClickListener(this); Button infoButton = findViewById(R.id.system_info_button); infoButton.setOnClickListener(this); Button playerButton = findViewById(R.id.player_info_button); playerButton.setOnClickListener(this); } /** * This method accesses the Buy goods option tab. */ public void openBuyGoods() { Intent intent = new Intent(this, BuyGoodsActivity.class); intent.putExtra("player", player); startActivity(intent); } /** * This method accesses the Sell goods option tab. */ public void openSellGoods() { Intent intent = new Intent(this, SellGoodsActivity.class); intent.putExtra("player", player); startActivity(intent); } /** * This method opens the System Information page. */ public void openSystem(){ Intent intent = new Intent(this, CurrentPlanetActivity.class); intent.putExtra("player", player); startActivity(intent); } /** * This method opens the Player Information page. */ public void openPlayerInformation(){ Intent intent = new Intent(this, player_information.class); intent.putExtra("player", player); startActivity(intent); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.buy_button: openBuyGoods(); break; case R.id.sell_button: openSellGoods(); break; case R.id.system_info_button: Log.d("test", "system_info_button is clicked"); openSystem(); break; case R.id.player_info_button: openPlayerInformation(); break; } } }
aa41d34ab5b57ef076976f9250e325f82cfb8479
[ "Java" ]
3
Java
gt-cs2340-nongshim-shinramen/M10
094b55a9c8718012d0bf71af175f468299978377
82924c557ba91d03edd19bcc7a566f3a57b94eda
refs/heads/master
<file_sep>"""Provide a simple CLI for testing the flights_search.py module""" import sys import datetime import flights_search def perform_search(): """Find requested flights and print them""" args_len = len(sys.argv) if args_len == 4 or args_len == 5: from_iata = sys.argv[1] to_iata = sys.argv[2] try: outbound_date = datetime.datetime.strptime(sys.argv[3], '%Y-%m-%d').date() return_date = None if args_len == 5: return_date = datetime.datetime.strptime(sys.argv[4], '%Y-%m-%d').date() except ValueError: print_usage() quit() fls = flights_search.FlightsSearcher() fls.do_search(from_iata, to_iata, outbound_date, return_date) else: print_usage() def print_usage(): """Print the usage hint to the console""" print('Usage: {0} IATA-from IATA-to date-outbound [date-return]\n' 'Dates must be formatted as YYYY-MM-DD'.format(sys.argv[0]) ) if __name__ == "__main__": perform_search() <file_sep>"""Find the flights matching given criteria on flyniki.com or other specified website This module exports: - FlightsSearcher class - SearchError exception type - IATANotFoundError exception type """ import re import datetime import json import io import urllib.parse import parse import requests import lxml.etree class SearchError(RuntimeError): """Indicate that the website sent an error""" pass class IATANotFoundError(RuntimeError): """Indicate that given IATA-code is not found on the website""" pass class FlightsSearcher: """This class provides the 'do_search' method It's implemented with a class (instead of a single function) since we should keep some cached data and the Session object between several calls of the 'do_search' function for increasing performance and reducing the traffic consumption. """ def __init__(self, domain_name='flyniki.com'): self.req_ses = requests.Session() self.airports = None self.vacancy_url = None self.domain_name = domain_name def do_search(self, from_iata, to_iata, outbound_date, return_date=None): """ Do several requests to the website (flyniki.com by default) and print found flights :param from_iata: IATA-code of a 'from' airport :param to_iata: IATA-code of a 'to' airport :param outbound_date: a date object :param return_date: a date object (None for a oneway search) :return: None """ # Check the 'from_iata' format try: self._check_iata_code(from_iata) except ValueError as exception: raise ValueError('Wrong value of the \'from_iata\' argument: ' + str(exception)) # Check the 'to_iata' format try: self._check_iata_code(to_iata) except ValueError as exception: raise ValueError('Wrong value of the \'to_iata\' argument: ' + str(exception)) # Check the input dates and convert them to strings if not isinstance(outbound_date, datetime.date): raise ValueError('The outbound_date argument must be of the date type') outbound_date_str = outbound_date.isoformat() if return_date is None: return_date_str = None else: if not isinstance(return_date, datetime.date): raise ValueError( 'The return_date argument must be of the date or the NoneType type' ) return_date_str = return_date.isoformat() # Convert the IATA-codes into flyniki.com's format from_city = self._iata_to_city_name(from_iata, 'departure') to_city = self._iata_to_city_name(to_iata, 'destination') # Perform search search_reply = self._request_flights(from_city, to_city, outbound_date_str, return_date_str) # Check that the website gave exactly what we've asked if not self._verify_search_results( search_reply, from_iata, to_iata, outbound_date, return_date ): raise RuntimeError('Mismatched sent search criteria and received ones') # Print search results self._print_flights(search_reply) @staticmethod def _check_iata_code(iata_code): """Check the given IATA-code If it's valid, return True. If not, raise ValueError. Warning: this function doesn't guarantee that the given IATA-code exists, it just checks its format.""" # 1. Check for the letter count if len(iata_code) != 3: raise ValueError('IATA-code must be exactly 3 characters long') # 2. Check that only english 26 letters are used # 3. Check that all letters are in upper case if re.match("^[A-Z]*$", iata_code) is None: raise ValueError('IATA-code must contain only A-Z letters in the upper case') return True def _request_airports(self): """Make an HTTP request to the website and return lists of airports""" req_departures = self.req_ses.get( 'http://www.'+self.domain_name+'/en/site/json/suggestAirport.php' '?searchfor=departures' '&searchflightid=0' '&departures%5B%5D=' '&destinations%5B%5D=City%2C+airport' '&suggestsource%5B0%5D=activeairports' '&withcountries=0' '&withoutroutings=0' '&promotion%5Bid%5D=' '&promotion%5Btype%5D=' '&get_full_suggest_list=false' '&routesource%5B0%5D=airberlin' '&routesource%5B1%5D=partner' ) req_destinations = self.req_ses.get( 'http://www.' + self.domain_name + '/en/site/json/suggestAirport.php' '?searchfor=destinations' '&searchflightid=0' '&departures%5B%5D=City%2C+airport' '&destinations%5B%5D=' '&suggestsource%5B0%5D=activeairports' '&withcountries=0' '&withoutroutings=0' '&promotion%5Bid%5D=' '&promotion%5Btype%5D=' '&get_full_suggest_list=false' '&routesource%5B0%5D=airberlin' '&routesource%5B1%5D=partner' ) # warning: these requests don't get all known airports. It seems that # flyniki.com doesn't work with some of them # or there is no planned flights for the remaining airports try: airports = {} # Please note: these lists are different in about 20 airports, # but they have a lot of common airports['departures'] = tuple(req_departures.json()['suggestList']) airports['destinations'] = tuple(req_destinations.json()['suggestList']) except (json.decoder.JSONDecodeError, IndexError): raise RuntimeError('Bad data format from the website') return airports def _iata_to_city_name(self, iata_code, airport_type): # Request the airport lists if we don't have them yet if self.airports is None: self.airports = self._request_airports() # Get a list for the requested direction if airport_type == 'departure': airports = self.airports['departures'] elif airport_type == 'destination': airports = self.airports['destinations'] else: raise ValueError('Wrong airport type is supplied to the function') # Perform search iata_match = list(filter(lambda x: x['code'] == iata_code, airports)) found_count = len(iata_match) if found_count == 0: raise IATANotFoundError( 'The requested IATA-code \''+ iata_code +'\' was not found on ' + self.domain_name ) elif found_count == 1: ret = iata_match[0]['name'] return ret else: raise RuntimeError( self.domain_name + ' provided at least two airports with the same IATA-code' ) def _request_flights(self, from_city, to_city, outbound_date, return_date): if self.vacancy_url is None: # Get a 'sid' parameter. # If we try to ask the website for a search without this parameter, # it fails due to some 'security reasons'. # So, we do a request, then it sends a Location header with a new 'sid' parameter req = self.req_ses.get( 'http://www.'+self.domain_name+'/en/booking/flight/vacancy.php', allow_redirects=False ) self.vacancy_url = "http://www." + self.domain_name + req.headers['Location'] if return_date is None: oneway_search = True return_date = '' oneway = '1' else: oneway_search = False oneway = '' headers = { 'Content-Type': 'application/x-www-form-urlencoded' } post_data = ('_ajax[templates][]=main' '&_ajax[templates][]=priceoverview' '&_ajax[templates][]=infos' '&_ajax[templates][]=flightinfo' '&_ajax[requestParams][departure]='+from_city+ '&_ajax[requestParams][destination]='+to_city+ '&_ajax[requestParams][returnDeparture]=' '&_ajax[requestParams][returnDestination]=' '&_ajax[requestParams][outboundDate]='+outbound_date+ '&_ajax[requestParams][returnDate]='+return_date+ '&_ajax[requestParams][adultCount]=1' '&_ajax[requestParams][childCount]=0' '&_ajax[requestParams][infantCount]=0' '&_ajax[requestParams][openDateOverview]=' '&_ajax[requestParams][oneway]='+oneway ) # This conversion is not only for [] symbols. # Some cities contain some non-latin symbols that are needed to be percent-encoded post_data = urllib.parse.quote(post_data, safe='=&_+') req = self.req_ses.post(self.vacancy_url, data=post_data, headers=headers) got_data = req.json() if 'error' in got_data: error_text = self._parse_a_website_error(got_data['error']) if 'No connections found for the entered data.' in error_text: # Nothing's bad. We just have an empty result found_flights = {} else: raise SearchError('The website reported the following error: ' + error_text) else: main_html = got_data['templates']['main'] found_flights = self._parse_html_flight_tables(main_html, oneway_search) return found_flights @staticmethod def _parse_a_website_error(error_html): parser = lxml.etree.HTMLParser(recover=True) html_etree = lxml.etree.parse(io.StringIO("<html>" + error_html + "</html>"), parser) error_text = html_etree.xpath('/html/body/div/div/p/text()') try: error_text = error_text[0] except IndexError: error_text = 'Unknown website error' return error_text @classmethod def _parse_html_flight_tables(cls, raw_html, oneway_flights): result = {} # Yes, the site's reply has broken tags (like <img></a>). # So, we need to use a recover mode parser = lxml.etree.HTMLParser(recover=True) html_etree = lxml.etree.parse(io.StringIO("<html>" + raw_html + "</html>"), parser) check_for_results = html_etree.xpath(''' //table[@class='flighttable'] ''') if len(list(check_for_results)) < 1: # Nothing's found or an error occurred return result html_flighttables = html_etree.xpath(''' /html/body /div[@id='vacancy_flighttable'] /div[@class='wrapper'] /div[@id='flighttables'] ''')[0] html_outbound_table = html_flighttables.xpath(''' div[@class=\'outbound block\'] /div[@class='tablebackground'] /table[@class='flighttable'] ''')[0] html_outbound_table_title = html_flighttables.xpath(''' div[@class=\'outbound block\'] /div[@class='row'] /div[@class='flight-data-date'] /div[@class='outboundicon'] ''')[0] result['outbound_flights_details'] = cls._parse_flight_table_details( html_outbound_table_title ) result['outbound_flights'] = cls._parse_flight_table(html_outbound_table) if oneway_flights is False: html_return_table = html_flighttables.xpath(''' div[@class=\'return block\'] /div[@class='tablebackground'] /table[@class='flighttable'] ''')[0] html_return_table_title = html_flighttables.xpath(''' div[@class=\'return block\'] /div[@class='row'] /div[@class='flight-data-date'] /div[@class='returnicon'] ''')[0] result['return_flights_details'] = cls._parse_flight_table_details( html_return_table_title ) result['return_flights'] = cls._parse_flight_table(html_return_table) return result @classmethod def _parse_flight_table(cls, table_element): result = {} result['flights'] = [] fare_types = cls._parse_fare_types(table_element) # Extract the flights from rows html_rows = table_element.xpath(''' tbody/tr[@class='flightrow selected'] | tbody/tr[@class='flightrow'] ''') for row in html_rows: cols = row.xpath('td') row_result = {} # Extract the start time tmp = cols[1].xpath('span/time[1]/text()')[0] tmp = tmp.split(':') row_result['start_time'] = datetime.time(int(tmp[0]), int(tmp[1])) # Extract the end time tmp = cols[1].xpath('span/time[2]/text()')[0] tmp = tmp.split(':') row_result['end_time'] = datetime.time(int(tmp[0]), int(tmp[1])) # Extract the end time days days_strong = list(cols[1].xpath('span/strong[1]/text()')) if len(days_strong) > 0: row_result['end_time_days'] = int(days_strong[0][1:]) else: row_result['end_time_days'] = 0 # Extract the duration tmp = cols[3].xpath('span[1]/text()')[0].strip() tmp = tmp.split('h') tmp_hours = int(tmp[0].strip()) tmp = tmp[1].split('min') tmp_mins = int(tmp[0].strip()) row_result['duration'] = datetime.timedelta(hours=tmp_hours, minutes=tmp_mins) # Extract the prices row_result['prices'] = cls._parse_prices(fare_types, cols) result['flights'].append(row_result) return result @staticmethod def _parse_prices(fare_types, cols): result = [] for fare_type in fare_types: price_row = {} if len(cols[fare_type['column_no']].xpath('span[@class="notbookable"]')) == 0: price_row['name'] = fare_type['name'] price_row['currency'] = fare_type['currency'] # These prices are really complicated. # The website usually sends two equal prices: 'lowest' and 'current'. # Some script on this page hides the 'lowest' one. # The situation is easy, we should only use the 'current' value. # But... sometimes there is no a 'current' value. # In this case script shows the 'lowest' one. # The solution is pretty simple: use 'lowest' in absence of 'current'. # But rarely, the website sends both these prices, # but the 'lowest' one is a bit smaller than the 'current'. # In this case script shows the 'current' one. # This code do the same things, but it also ensures that 'lowest' <= 'current'. lowest_tmp = cols[fare_type['column_no']].xpath( 'label[1]/div[@class="lowest"]/span[1]/text()' ) current_tmp = price_row['current'] = cols[fare_type['column_no']].xpath( 'label[1]/div[@class="current"]/span[1]/text()' ) if len(lowest_tmp) > 0: lowest_tmp = lowest_tmp[0] else: raise RuntimeError('The website didn\'t send the \'lowest\' price value') if len(current_tmp) > 0: current_tmp = current_tmp[0] else: current_tmp = None if lowest_tmp is None and current_tmp is None: raise RuntimeError( 'The website didn\'t send both the \'lowest\' and \'current\' price values' ) elif lowest_tmp is not None and current_tmp is None: price_row['value'] = lowest_tmp elif lowest_tmp is not None and current_tmp is not None: price_row['value'] = current_tmp if float(lowest_tmp.replace(',', '')) > float(current_tmp.replace(',', '')): raise RuntimeError('The website sent wrong prices') else: raise RuntimeError('Unexpected condition') result.append(price_row) return result @staticmethod def _parse_fare_types(table_element): # Extract the fare types and currency symbols from the table's head # This code finds all given fare types regardless of their order and count fare_types_cols_offset = int(table_element.xpath('thead/tr[1]/td[1]/@colspan')[0]) fare_types = [] fare_types_columns = table_element.xpath('thead/tr[1]/td') cnt = fare_types_cols_offset for column in fare_types_columns[1:]: # the first column is not related to the fare types fare_type = {} # Extract name fare_type['name'] = column.xpath('div[1]/label/p/text()')[0] if len(fare_type['name']) == 0: raise RuntimeError('Wrong table head format') # Extract currency sign fare_type['currency'] = table_element.xpath( 'thead/tr[2]/th[$col]/text()', col=cnt )[0].strip() if len(fare_type['currency']) == 0: raise RuntimeError('Wrong table head format') fare_type['column_no'] = cnt fare_types.append(fare_type) cnt += 1 return fare_types @staticmethod def _parse_flight_table_details(html_element): result = {} # Parse direction title = html_element.xpath('h2/text()')[0] # title example: ' outbound flight ' title = title.strip().split(' ') if title[0] == 'outbound': result['direction'] = 'outbound' elif title[0] == 'return': result['direction'] = 'return' else: raise RuntimeError('Can\'t parse flight direction from the table\'s title') # Parse details details = html_element.xpath('div[@class=\'vacancy_route\']/text()')[0] # details string example: 'Berlin (BER) – London (LON), Thursday, 27/10/16' parsed_data = parse.parse('{0} ({1}) – {2} ({3}),  {4}, {5}', details.strip()) result['city_from'] = parsed_data[0] result['iata_from'] = parsed_data[1] result['city_to'] = parsed_data[2] result['iata_to'] = parsed_data[3] result['date'] = datetime.datetime.strptime(parsed_data[5], '%d/%m/%y').date() return result @staticmethod def _verify_search_results(search_reply, from_iata, to_iata, outbound_date, return_date=None): result = True if len(search_reply) == 0: # We just have no results. It's OK. return True if search_reply['outbound_flights_details']['direction'] != 'outbound': result = False if search_reply['outbound_flights_details']['iata_from'] != from_iata: result = False if search_reply['outbound_flights_details']['iata_to'] != to_iata: result = False if search_reply['outbound_flights_details']['date'] != outbound_date: result = False if return_date is None: if 'return_flight_details' in search_reply: # we were performing a one-way search and should not have any return flights result = False else: if search_reply['return_flights_details']['direction'] != 'return': result = False if search_reply['return_flights_details']['iata_from'] != to_iata: result = False if search_reply['return_flights_details']['iata_to'] != from_iata: result = False if search_reply['return_flights_details']['date'] != return_date: result = False return result @staticmethod def _print_flights(flights): for direction in ( {'key': 'outbound_flights', 'name': 'Outbound flight'}, {'key': 'return_flights', 'name': 'Return flight'} ): if direction['key'] in flights: for flight in flights[direction['key']]['flights']: print('{0}:'.format(direction['name'])) # Print information about start and end times end_days_text = '' if flight['end_time_days'] == 1: end_days_text = ' +1 day' elif flight['end_time_days'] > 1: end_days_text = ' +' + str(flight['end_time_days']) + ' days' print('\tStarts at {0} , ends at {1}{2}'.format( flight['start_time'].strftime('%H:%M'), flight['end_time'].strftime('%H:%M'), end_days_text )) # Print information about duration print('\tDuration: {0}'.format(flight['duration'])) # Print the information about prices print('\tFare options:') for price in flight['prices']: print('\t\t{0:<17}: {1}{2}'.format( price['name'], price['currency'], price['value'] )) <file_sep>"""Perform a lot of simple random tests for the flights_search.py module The aim of this test is to find failures that occurs only on rare conditions. It doesn't check for any parsing mismatches. """ import datetime import time import random import requests import flights_search def perform_test(): """Perform the random test""" fls = flights_search.FlightsSearcher() airports = fls._request_airports() now = time.time() print('Starting a crash test.\n' '{0} departure airports found.\n' '{1} destination airports found.' ''.format( len(airports['departures']), len(airports['destinations']) ) ) print('Now: {0}\n'.format(datetime.datetime.fromtimestamp(now))) search_errors = 0 network_errors = 0 total_checks = 1000 for i in range(0, total_checks): from_iata = random.choice(airports['departures'])['code'] to_iata = random.choice(airports['destinations'])['code'] outbound_ts = now+random.randint(0, 3600*24*15) return_ts = outbound_ts + random.randint(0, 3600*24*5) outbound_date = datetime.date.fromtimestamp(outbound_ts) return_date = datetime.date.fromtimestamp(return_ts) if random.randint(0, 2) == 0: return_date = None print('{0:03d}/{1:03d} {2}->{3} {4} {5}'.format( i, total_checks-1, from_iata, to_iata, str(outbound_date), str(return_date) )) while True: try: fls.do_search(from_iata, to_iata, outbound_date, return_date) except flights_search.SearchError as err: print('SearchError: ' + str(err)) search_errors += 1 except requests.exceptions.ConnectionError: print('Network error. Trying again...') network_errors += 1 time.sleep(1) continue break print('\nThe crash test successfully passed.\n' '{0} SearchErrors, {1} NetworkErrors' ''.format(search_errors, network_errors) ) if __name__ == "__main__": perform_test() <file_sep># flights_search Flights Search is a Python module for retrieving information about flights from flyniki.com according to user-specified search criteria. # Dependencies ``` pip install requests pip install lxml pip install parse ``` # Using a command line interface ``` python3 src/flights_search_cli.py IATA_from IATA_to date_outbound [date_return] ``` Dates must be formatted as YYYY-MM-DD. date_return is optional, leave it for an oneway search. See UsageExamples.txt for usage examples.
4b4217b16dec00dff9f0a783962db0bcadaca984
[ "Markdown", "Python" ]
4
Python
dam52nn/flights_search
d9bd04985dc72626102c7efe40c4f7efb04b7ee6
204a365834ce633ce3bea1ca31f5b0bc5a5e5882
refs/heads/master
<repo_name>IPRIT/typescript-misis-books-recommender-system<file_sep>/src/internal/RecommenderSystem/Factors/FactorsComputation.ts import {IRate, RatesFetcher} from "./RatesFetcher"; var Promise = require('es6-promise').Promise; /** * Created by Александр on 12.06.2016. */ export class FactorsComputation { learnEps = 1e-6; minLearnIterations = 10000; dataSetUsers = {}; dataSetItems = {}; dataSetMatrix = {}; itemsInfo = {}; debug: boolean = true; features: number = 50; lambda: number = 0.05; eta: number = 0.01; mu: number = 0; usersBasePredictor = {}; itemsBasePredictor = {}; usersFeatureVectors = {}; itemsFeatureVectors = {}; iterationNumber: number = 0; error: number = 0; rmse: number = 1; rmseOld: number = 0; threshold: number = 0.01; startUserFactorValue: number = 0.1; startItemFactorValue: number = 0.05; static indexPrefix: string = '_index_'; rates: IRate[] = []; initialize() { let fetcher = new RatesFetcher(); return fetcher.initialize() .then((rates: Array<IRate>) => { this.rates = rates; this.createDataSet(); this.initializeFactors(); }); } private createDataSet() { this.rates.forEach((rate: IRate) => { this.setRate(rate); }); } private initializeFactors() { Object.keys(this.dataSetUsers).forEach(userKey => { this.usersBasePredictor[ userKey ] = 0; for (var f = 0; f < this.features; f++) { if (!this.usersFeatureVectors[ userKey ]) { this.usersFeatureVectors[ userKey ] = []; } this.usersFeatureVectors[ userKey ].push( this.startUserFactorValue ); } }); Object.keys(this.dataSetItems).forEach(itemKey => { this.itemsBasePredictor[ itemKey ] = 0; for (var f = 0; f < this.features; f++) { if (!this.itemsFeatureVectors[ itemKey ]) { this.itemsFeatureVectors[ itemKey ] = []; } this.itemsFeatureVectors[ itemKey ].push( this.startItemFactorValue * f ); } }); } private getUserKeyById(userId) { return FactorsComputation.indexPrefix + 'user_' + userId; } private getItemKeyById(itemId) { return FactorsComputation.indexPrefix + 'item_' + itemId; } private addRateForUser(rate: IRate) { let userKey = this.getUserKeyById(rate.user_id); if (!this.dataSetUsers[ userKey ]) { this.dataSetUsers[ userKey ] = []; } this.dataSetUsers[ userKey ].push(rate); } private addRateForItem(rate: IRate) { let itemKey = this.getItemKeyById(rate.item_id); if (!this.dataSetItems[ itemKey ]) { this.dataSetItems[ itemKey ] = []; } this.dataSetItems[ itemKey ].push(rate); } private getUserRatesVectorById(userId) { let userKey = this.getUserKeyById(userId); return this.dataSetUsers[ userKey ] || []; } private getItemRatesVectorById(itemId) { let itemKey = this.getItemKeyById(itemId); return this.dataSetItems[ itemKey ] || []; } private setRate(rate: IRate) { let userKey = this.getUserKeyById(rate.user_id), itemKey = this.getItemKeyById(rate.item_id); if (!this.dataSetMatrix[ userKey ]) { this.dataSetMatrix[ userKey ] = {}; } if (!this.itemsInfo[ itemKey ]) { this.itemsInfo[ itemKey ] = { id: rate.item_id, category: rate.category }; } this.dataSetMatrix[ userKey ][ itemKey ] = rate; this.addRateForUser(rate); this.addRateForItem(rate); } learn() { return new Promise((resolve, reject) => { while (Math.abs(this.rmseOld - this.rmse) > this.learnEps || this.iterationNumber < this.minLearnIterations) { this.rmseOld = this.rmse; this.rmse = 0; Object.keys(this.dataSetMatrix).forEach(userKey => { Object.keys(this.dataSetMatrix[ userKey ]).forEach(itemKey => { let forecastRate = this.computeForecast(userKey, itemKey); this.error = this.dataSetMatrix[ userKey ][ itemKey ].rate - forecastRate; this.rmse += this.error * this.error; // computing root mean square deviation (error) this.mu += this.eta * this.error; // reducing error effect this.usersBasePredictor[ userKey ] += this.eta * (this.error - this.lambda * this.usersBasePredictor[ userKey ]); this.itemsBasePredictor[ itemKey ] += this.eta * (this.error - this.lambda * this.itemsBasePredictor[ itemKey ]); for (var f = 0; f < this.features; f++) { this.usersFeatureVectors[ userKey ][f] += this.eta * ( this.error * this.itemsFeatureVectors[ itemKey ][f] - this.lambda * this.usersFeatureVectors[ userKey ][f] ); this.itemsFeatureVectors[ itemKey ][f] += this.eta * ( this.error * this.usersFeatureVectors[ userKey ][f] - this.lambda * this.itemsFeatureVectors[ itemKey ][f] ); } }); }); this.rmse = Math.sqrt(this.rmse / this.rates.length); if (typeof this.rmse !== 'number') { reject(new Error("Rmse value is not finite")); } if (this.debug) { console.log(`[Epoch ${++this.iterationNumber}]: rmse = ${this.rmse.toFixed(8)}.`); } } resolve(); }); } private computeForecast(userKey: string, itemKey: string) { return this.mu + this.usersBasePredictor[ userKey ] + this.itemsBasePredictor[ itemKey ] + this.dotFactors(userKey, itemKey); } private dotFactors(userKey: string, itemKey: string) { return this.usersFeatureVectors[ userKey ].reduce((res, factor, f) => { return res + factor * this.itemsFeatureVectors[ itemKey ][f]; }, 0); } }<file_sep>/src/internal/RecommenderSystem/Security/Config.ts /** * Created by Александр on 12.06.2016. */ export const CONFIG = { GATEWAY_TOKEN: '<KEY>' };<file_sep>/src/config.ts /* export const CONF = { port: 8081, ip: '10.135.1.53' }; */ /**/ export const CONF = { port: 3000, ip: 'localhost' }; /**/<file_sep>/src/internal/RecommenderSystem/Security/SecurityGateway.ts import {CONFIG} from "./Config"; /** * Created by Александр on 12.06.2016. */ var request = require('request-promise'); export class SecurityGateway { private static instance: SecurityGateway = null; public static getInstance(): SecurityGateway { if (SecurityGateway.instance && SecurityGateway.instance instanceof SecurityGateway) { return SecurityGateway.instance; } return (SecurityGateway.instance = new SecurityGateway()); } public sendUserRequest(uri: string, token: string, params: any = {}) { params.rs_token = token; params.token = CONFIG.GATEWAY_TOKEN; var options = { uri: uri, qs: params, json: true // Automatically parses the JSON string in the response }; return request(options); } public sendSystemRequest(uri: string, params: any = {}) { params.token = CONFIG.GATEWAY_TOKEN; var options = { uri: uri, qs: params, json: true // Automatically parses the JSON string in the response }; return request(options); } }<file_sep>/src/internal/routers/api.ts import {RecommendationsEvaluator} from "../RecommenderSystem/Forecast/RecommendationsEvaluator"; import {TokenChecker} from "../RecommenderSystem/Security/TokenChecker"; var express = require('express'); var stream = require('stream'); var router = express.Router(); var app = express(); router.all('/', function (req, res) { res.json({ 'current state': 'API RUNNING' }); }); router.get('/getRecommendations', function (req, res) { let rsToken = req.query.rs_token; let count = Math.max(Math.min(req.query.count || 10, 200), 0); let offset = Math.max(req.query.offset || 0, 0); let category = +req.query.category || 1; TokenChecker.check(rsToken) .then(response => { if (!response || response.error) { return res.json(response); } let userId = response.user && response.user.id; let recSystem = new RecommendationsEvaluator(rsToken); return recSystem.getRecommendations(userId, { count, offset, category }); }) .then(result => { res.json(result); }) .catch(err => { res.json({ error: err.toString() }); }); }); module.exports = router;<file_sep>/src/utils/Timing.ts interface IProxyTiming { proxy(_: Function): IProxyObject; zone(_: IProxyObject | Function): IProxyTiming; elapsed: number } interface IProxyObject { _proxyFunction: Function; } export default class Timing implements IProxyTiming { private start: Date; proxy(_proxyFunction: Function) { return { _proxyFunction } } zone(potentiallyCallableFunction: IProxyObject | Function) { this.start = new Date(); if (typeof potentiallyCallableFunction === 'function') { (<Function>potentiallyCallableFunction)(); } else { (<IProxyObject>potentiallyCallableFunction)._proxyFunction(); } return this; } get elapsed() { if (this.start) { return new Date().getTime() - this.start.getTime(); } return new Date().getTime(); } }<file_sep>/src/internal/RecommenderSystem/Security/TokenChecker.ts import {SecurityGateway} from "./SecurityGateway"; var Promise = require('es6-promise').Promise; /** * Created by Александр on 13.06.2016. */ export class TokenChecker { private static API_BASE: string = 'http://twosphere.ru/rs-api'; private static API_RATES_URI: string = '/checkToken'; static check(rsToken) { let apiUrl = TokenChecker.API_BASE + TokenChecker.API_RATES_URI; return SecurityGateway.getInstance() .sendUserRequest(apiUrl, rsToken); } }<file_sep>/src/internal/RecommenderSystem/Factors/RatesFetcher.ts import {SecurityGateway} from "../Security/SecurityGateway"; var async = require('async'); var Promise = require('es6-promise').Promise; /** * Created by Александр on 12.06.2016. */ export interface IRate { user_id: number, item_id: number, category: number, rate: number, timestamp: number } export interface ISystemMetaInfo { users: number, items: number, rates: number } export class RatesFetcher { private API_BASE: string = 'http://twosphere.ru/rs-api'; private API_RATES_URI: string = '/getRates'; private maxRatingsPerRequest: number = 5000; public metaInfo: ISystemMetaInfo; public rates: Array<IRate> = []; private getSystemMetaInfo() { let apiUrl = this.API_BASE; return SecurityGateway.getInstance() .sendSystemRequest(apiUrl) .then(response => { return response.result; }) .catch(function (err) { console.error('[Fetching system meta info] Error:', err); }); } private getAllRates() { return new Promise((resolve, reject) => { let ratingsNumber = this.metaInfo.rates; let breakdownNumber = Math.ceil(ratingsNumber / this.maxRatingsPerRequest); let breakdownRange = []; for (let i = 0; i < breakdownNumber; ++i) { breakdownRange.push(i * this.maxRatingsPerRequest); } let gotItems: IRate[] = []; let apiUrl = this.API_BASE + this.API_RATES_URI; var queue = async.queue((offset, callback) => { SecurityGateway.getInstance().sendSystemRequest(apiUrl, { offset, count: this.maxRatingsPerRequest }).then(resp => resp.result.items) .then((items: Array<IRate>) => { gotItems.push(...items); console.log(`Got items: ${items.length}`); callback(); }); }, 3); queue.drain = () => { resolve(gotItems); }; queue.push(breakdownRange, err => { if (err) { reject(err); } }); }); } initialize() { return this.getSystemMetaInfo() .then((metaInfo: ISystemMetaInfo) => { this.metaInfo = metaInfo; return this.getAllRates(); }) .then((rates: Array<IRate>) => { this.rates = rates; console.log(`Total got rates: ${rates.length}`); return rates; }) .catch(err => { console.log('[Unknown error]:', err); }); } }<file_sep>/src/app.ts var express = require('express'); var path = require('path'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var session = require('express-session'); var auth = require('./internal/user/auth'); //var pmx = require('pmx'); var routes = require('./internal/routers/router'); import serverInit from './internal/init'; var app = express(); // view engine setup app.set('views', __dirname + '/views'); app.set('view engine', 'jade'); // uncomment after placing your favicon in /public //app.use(favicon(__dirname + '/app/img/favicon.ico')); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.enable('trust proxy'); app.use(session({ secret: 'keyboard cat', resave: false, saveUninitialized: true })); app.use(express.static(__dirname + '/../app')); app.use(auth.allowCrossOrigin); /** * Fills acm accounts for async queue */ serverInit(); /* * Connecting routers */ app.get('/partials\/*:filename', routes.partials); app.use('/', routes.index); app.use('/api', routes.api); app.all('/*', function(req, res, next) { // Just send the index.jade for other files to support html5 mode in angular routing res.render('index/index'); }); //app.use(pmx.expressErrorHandler()); // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); //noinspection TypeScriptUnresolvedVariable err['status'] = 404; next(err); }); // error handlers // development error handler // will print stacktrace if (app.get('env') === 'development') { app.use(function(err, req, res, next) { console.log(err); res.status(err.status || 500); res.end(); }); } // production error handler // no stacktraces leaked to user app.use(function(err, req, res, next) { console.log(err); res.status(err.status || 500); res.end(); }); module.exports = app;<file_sep>/src/internal/RecommenderSystem/Factors/FactorsStore.ts import {type} from "os"; /** * Created by Александр on 12.06.2016. */ export interface SvdModelState { mu: number, usersBasePredictor: Object, itemsBasePredictor: Object, usersFeatureVectors: Object, itemsFeatureVectors: Object, items: Object } export class FactorsStore { private static instance: FactorsStore = null; public static getInstance(): FactorsStore { if (FactorsStore.instance && FactorsStore.instance instanceof FactorsStore) { return FactorsStore.instance; } return (FactorsStore.instance = new FactorsStore()); } private modelState: SvdModelState = null; public store(modelState: SvdModelState) { this.modelState = modelState; //todo: save/restore snapshot in persistent storage //this.snapshot() } public get state(): SvdModelState { return this.modelState; } public get isReady() { return this.modelState != null; } public userExists(userKey) { return !!this.modelState.usersFeatureVectors[ userKey ]; } }<file_sep>/src/internal/RecommenderSystem/Forecast/RecommendationsEvaluator.ts import {FactorsStore} from "../Factors/FactorsStore"; import {FactorsComputation} from "../Factors/FactorsComputation"; import {ItemsCollator} from "./ItemsCollator"; import {CacheStore} from "./CacheStore"; var Promise = require('es6-promise').Promise; /** * Created by Александр on 12.06.2016. */ export interface IQueryParams { count: number, offset: number, category: number } export interface IPrediction { item_id: number, forecastRate: number } export class RecommendationsEvaluator { store: FactorsStore; constructor(public rsToken: string) { this.store = FactorsStore.getInstance(); } getRecommendations(userId: number, queryParams: IQueryParams = {count: 10, offset: 0, category: 1}) { return new Promise((resolve, reject) => { if (!this.store.isReady) { return reject(new Error('Recommender model is not ready')); } else if (!this.store.userExists( this.getUserKeyById(userId) )) { return reject(new Error('Recommender model does not contain this user')); } let cacheStore = CacheStore.getInstance(); let forecastCollection; if (cacheStore.areItemsExists(userId, queryParams)) { forecastCollection = cacheStore.getItems(userId, queryParams); } else { forecastCollection = this.computeForecastCollection(userId, queryParams.category); cacheStore.storeItems(userId, queryParams, forecastCollection); } let itemsId = forecastCollection.map(item => item.item_id) .slice(queryParams.offset, queryParams.offset + queryParams.count); let collator = new ItemsCollator(); collator.collateItems(itemsId, queryParams.category, this.rsToken) .then(result => { if (result.items) { result.items = result.items.map((item, index) => { item.forecastRate = forecastCollection[queryParams.offset + index].forecastRate; return item; }); } result.all_items_count = forecastCollection.length; resolve(result); }) .catch(err => reject(err)); }); } private computeForecastCollection(userId: number, category: number = 1): Array<IPrediction> { let state = this.store.state; let itemsKeyList = Object.keys(state.itemsFeatureVectors) .filter(itemKey => { return category === 1 || state.items[ itemKey ].category === category; }); let userKey = this.getUserKeyById(userId); let forecastCollection = itemsKeyList.map(itemKey => { let forecastRate = this.computeForecast(userKey, itemKey); let curCategory = state.items[ itemKey ].category; if (category === 1 && curCategory > 2) { forecastRate *= 0.8; } return { item_id: state.items[ itemKey ].id, forecastRate } }); forecastCollection.sort((a, b) => b.forecastRate - a.forecastRate); return forecastCollection; } private computeForecast(userKey: string, itemKey: string) { let state = this.store.state; return state.mu + state.usersBasePredictor[ userKey ] + state.itemsBasePredictor[ itemKey ] + this.dotFactors(userKey, itemKey); } private dotFactors(userKey: string, itemKey: string) { let state = this.store.state; return state.usersFeatureVectors[ userKey ].reduce((res, factor, f) => { return res + factor * state.itemsFeatureVectors[ itemKey ][f]; }, 0); } private getUserKeyById(userId) { return FactorsComputation.indexPrefix + 'user_' + userId; } private getItemKeyById(itemId) { return FactorsComputation.indexPrefix + 'item_' + itemId; } }<file_sep>/src/internal/routers/index.ts var express = require('express'); var router = express.Router(); router.get('/', function(req, res) { console.log(1); res.render('index/index'); }); module.exports = router;<file_sep>/src/internal/RecommenderSystem/Forecast/ItemsCollator.ts import {SecurityGateway} from "../Security/SecurityGateway"; var Promise = require('es6-promise').Promise; /** * Created by Александр on 12.06.2016. */ export class ItemsCollator { private API_BASE: string = 'http://twosphere.ru/rs-api'; private API_RATES_URI: string = '/collateItems'; collateItems(items: number[], category: number, rsToken: string) { let apiUrl = this.API_BASE + this.API_RATES_URI; return SecurityGateway.getInstance() .sendUserRequest(apiUrl, rsToken, { items: items.join(','), category }); } }<file_sep>/src/internal/routers/router.ts module.exports = { partials: compileStaticTemplate, index: require('./index'), api: require('./api') }; function compileStaticTemplate(req, res) { var filename = req.params.filename; if (!filename) return; res.render('../../../app/partials/' + filename.replace(/(\.htm|\.html)$/i, '')); }<file_sep>/src/internal/user/auth/auth.ts var AUTH_COOKIE_NAME = 'auth.sid'; module.exports = { allowCrossOrigin: AllowCrossOrigin }; function AllowCrossOrigin(req, res, next) { var session = req.session; res.set('Access-Control-Allow-Origin', '*'); res.set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS'); res.set('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Key'); next(); }<file_sep>/src/internal/init.ts import {SecurityGateway} from "./RecommenderSystem/Security/SecurityGateway"; import {RatesFetcher, IRate} from "./RecommenderSystem/Factors/RatesFetcher"; import {FactorsComputation} from "./RecommenderSystem/Factors/FactorsComputation"; import {FactorsStore} from "./RecommenderSystem/Factors/FactorsStore"; export default function serverInit() { let fc = new FactorsComputation(); fc.initialize() .then(() => { return fc.learn(); }) .then(() => { FactorsStore.getInstance() .store({ mu: fc.mu, usersBasePredictor: fc.usersBasePredictor, itemsBasePredictor: fc.itemsBasePredictor, usersFeatureVectors: fc.usersFeatureVectors, itemsFeatureVectors: fc.itemsFeatureVectors, items: fc.itemsInfo }); console.log('Recommender model is ready for forecasting'); }) .catch(err => { throw err; }); }<file_sep>/src/internal/RecommenderSystem/Forecast/CacheStore.ts import {IQueryParams, IPrediction} from "./RecommendationsEvaluator"; /** * Created by Александр on 13.06.2016. */ export class CacheStore { private static instance: CacheStore = null; public static getInstance(): CacheStore { if (CacheStore.instance && CacheStore.instance instanceof CacheStore) { return CacheStore.instance; } return (CacheStore.instance = new CacheStore()); } private static prefixKey = '_index_'; cacheStorage: Object = {}; public storeItems(userId: number, queryParams: IQueryParams, items: Array<IPrediction>) { let userKey = this.getUserKeyById(userId); let categoryKey = this.getCategoryKeyById(queryParams.category); if (!this.cacheStorage[ userKey ]) { this.cacheStorage[ userKey ] = {}; } if (!this.cacheStorage[ userKey ][ categoryKey ]) { this.cacheStorage[ userKey ][ categoryKey ] = []; } this.cacheStorage[ userKey ][ categoryKey ] = items; this.logStats('Items saved'); } public getItems(userId: number, queryParams: IQueryParams): Array<IPrediction> { if (!this.areItemsExists(userId, queryParams)) { return []; } let userKey = this.getUserKeyById(userId); let categoryKey = this.getCategoryKeyById(queryParams.category); this.logStats('Items taken'); return this.cacheStorage[ userKey ][ categoryKey ]; } public areItemsExists(userId: number, queryParams: IQueryParams) { let userKey = this.getUserKeyById(userId); let categoryKey = this.getCategoryKeyById(queryParams.category); return !!this.cacheStorage[ userKey ] && !!this.cacheStorage[ userKey ][ categoryKey ]; } public reset() { this.logStats('Items before reset'); this.cacheStorage = {}; this.logStats('Items after reset'); } private getUserKeyById(userId) { return CacheStore.prefixKey + 'user_' + userId; } private getCategoryKeyById(category) { return CacheStore.prefixKey + 'category_' + category; } private logStats(messageName: string = '') { let cellsNumber = 0, itemsNumber = 0, usersNumber = 0; Object.keys(this.cacheStorage) .forEach(userKey => { usersNumber++; Object.keys(this.cacheStorage[userKey]) .forEach(categoryKey => { itemsNumber += this.cacheStorage[ userKey ][ categoryKey ].length; cellsNumber++; }) }); let logPrefix = 'Cache storage'; if (messageName) { messageName = `[${logPrefix}] [${messageName}]`; } else { messageName = `[${logPrefix}]`; } console.log(messageName, `Items in cache store: ${itemsNumber}. Cache indexes number: ${cellsNumber}. Users: ${usersNumber}.`); } }<file_sep>/README.md # TypeScript Funk SVD Implementation for Recommender System (misis books) ``` $ npm run install && npm run start ``` ## Schemes of work ### General scheme ![image 1](https://cloud.githubusercontent.com/assets/1553519/16013668/04d20230-3197-11e6-8277-b74f49d9024d.png) ### Functional diagram ![image 2](https://cloud.githubusercontent.com/assets/1553519/16013643/ec892780-3196-11e6-8d5f-d1e214534689.png)
5c439f0ac2cf42c21e2517261c3127fa9a1ca5b1
[ "Markdown", "TypeScript" ]
18
TypeScript
IPRIT/typescript-misis-books-recommender-system
3e7c49840499bdc202bf96f525e62748f06aa245
3fe0cc53bef2a14d2746c3afe962a697bc7d4167
refs/heads/master
<file_sep>my_name = "Dhruv" my_age = 35 my_height = 74 # inches my_weight = 180 # lbs my_eyes = "Blue" my_teeth = "White" my_hair = "Brown" print ("Lets talk about %s." %(my_name)) print ("He's %d inches tall" %(my_height)) print "He's %d pounds heavy" % my_weight print "Actually thats not too heavy" print "He's got %s eyes and %s hair" % (my_eyes, my_hair) print "His teeth are usually %s depending on the coffee" % my_teeth print "If I add %d, and %d I get %d " %( my_age, my_height, my_age + my_height + my_weight ) <file_sep># this one is like your scripts with argv def print_two(*argvs): arg1, arg2 = argvs print "arg1: %r, arg2: %r" %(arg1, arg2) # ok, that *argvs is actually pointless, we can just do this def print_two_again(arg1, arg2): print "arg1: %r, arg2: %r" %(arg1, arg2) # this one just takes one argument def print_one(arg1): print "arg1: %r" % arg1 # this one takes no arguments def print_none(): print "I got nothing!" print_two("Me", "You") print_two_again("Me", "You") print_one("Just me") print_none() <file_sep>cars = 100 space_in_car = 4.0 drivers = 30 passengers = 90 cars_not_driven = cars - drivers cars_driven = drivers carpool_capacity = cars_driven * space_in_car average_passenger_per_car = passengers / cars_driven print "There are", cars, "cards available." print "There are only ", drivers, "drivers available" print "There will be", cars_not_driven, "empty cars today" print "We have", passengers, "to carpool today" print "We need to put about", average_passenger_per_car,"in each car" <file_sep>from sys import argv from os.path import exists script, filename, to_file = argv print "Copying from %s to %s" %(filename, to_file) data_from_file = open(filename).read() print "The input file is %d bytes long." % len(data_from_file) print "Does the output file exist? %r" %exists(to_file) print "Ready, hit RETURN to continue or CTRL-C to abort." raw_input() out_file = open(to_file, 'w').write(data_from_file) print "Alright, all done."
033f6b1dd28b6f8f8ea37009ad291c403766dae6
[ "Python" ]
4
Python
salwandhruvdev/learn_python_the_hard_way
d6fa0fe767acef900d9f90a80c66b0159b49dcb6
16064a930f11b51042abe9f13b1261c9654185a7
refs/heads/master
<file_sep>import { createTheme, ThemeProvider } from "@material-ui/core"; import { Route, Router, Switch } from "react-router-dom"; import AdminMessages from "./screens/AdminMessages"; import BrandsAndCommisions from "./screens/BrandsCommisions"; import history from "./services/history"; const theme = createTheme({ breakpoints: { values: { xs: 0, sm: 500, md: 770, lg: 1280, xl: 1920 } }, palette: { primary: { main: "#1da1f2", contrastText: "#fff" }, secondary: { main: "#ff6d6d", contrastText: "#fff" }, text: { primary: "#242529", secondary: "#8a96a3" } }, typography: { fontFamily: "Metropolis", h2: { fontSize: "1.563rem", fontWeight: 600 }, h3: { fontSize: "1.25rem", fontWeight: 600 }, h5: { fontWeight: 600 }, h6: { fontWeight: 600 }, subtitle1: { fontSize: "0.938" } }, shape: { borderRadius: 30 } }); function App() { return ( <Router history={history}> <ThemeProvider theme={theme}> <Switch> <Route exact={true} path={"/"} render={(routesProps) => { return <AdminMessages />; }} /> <Route exact={false} path={"/brands"} render={(routesProps) => { return <BrandsAndCommisions />; }} /> </Switch> </ThemeProvider> </Router> ); } export default App; <file_sep>import React from "react"; import history from "../../../services/history"; import Messages from "../../../icons/Messages"; import Product from "../../../icons/Product"; import Questionare from "../../../icons/Questionare"; import Therepists from "../../../icons/Therepists"; import User from "../../../icons/User"; import LogoImg from "../../../images/Logo.png"; const Sidebar = () => { const moveToRoute = (route) => { history.push(route); }; return ( <> <div className="logo"> <img onClick={() => moveToRoute("/")} src={LogoImg} alt="" /> </div> <div className="navigation"> <ul> <li> <Questionare /> Questionare </li> <li> <Therepists /> Therepists </li> <li onClick={() => moveToRoute("/brands")}> <Product /> Product </li> <li onClick={() => moveToRoute("/")}> <User /> User </li> <li> <Messages /> Messages </li> </ul> </div> </> ); }; export default Sidebar; <file_sep>export const apiEndpoints = { userManagement: { login: "/profile/v1/user/login" }, testManagement: { login: "/profile/v1/user/login" } }; <file_sep>import { makeStyles } from "@material-ui/core/styles"; import { Backdrop, Fade, Modal } from "@material-ui/core"; import AddItemForm from "./AddItemForm"; const useStyles = makeStyles((theme) => ({ modal: { display: "flex", alignItems: "center", justifyContent: "center", padding: 20 }, paper: { backgroundColor: theme.palette.background.paper, border: "1px solid #979797", boxShadow: theme.shadows[5], padding: theme.spacing(2, 4, 3), width: 600, borderRadius: 24, overflow: "auto" } })); const AddItemPopup = ({ open, handleClose, saveBrandHandler }) => { const classes = useStyles(); return ( <Modal className={classes.modal} open={open} onClose={handleClose} closeAfterTransition BackdropComponent={Backdrop} BackdropProps={{ timeout: 500 }} aria-labelledby="simple-modal-title" aria-describedby="simple-modal-description" > <Fade in={open}> <div className={classes.paper}> <AddItemForm saveBrandHandler={saveBrandHandler} /> </div> </Fade> </Modal> ); }; export default AddItemPopup; <file_sep>import axios from "axios"; export const baseURL = process.env.API_HOST || ""; export const gpAxios = axios.create({ baseURL, headers: { "Content-Type": "application/json" } }); /** * * @param token */ export const setUserToken = (token) => { if (token) { gpAxios.defaults.headers.common[ "User-Key" ] = `${process.env.REACT_APP_TOKEN}`; gpAxios.defaults.headers.common["x-access-token"] = token; gpAxios.defaults.headers.common["Access-Control-Allow-Origin"] = "*"; } else { delete gpAxios.defaults.headers.common["User-Key"]; delete gpAxios.defaults.headers.common["x-access-token"]; } }; <file_sep>import React from "react"; const Product = () => { return ( <> <svg xmlns="http://www.w3.org/2000/svg" width="14" height="21" viewBox="0 0 14 21" > <g fill="none" fill-rule="evenodd"> <g stroke="#FFF" stroke-width="1.5"> <g> <path d="M12.646.75H3.793v8.166H2c-.69 0-1.25.56-1.25 1.25V19c0 .69.56 1.25 1.25 1.25h9.391c.69 0 1.25-.56 1.25-1.25v-8.833c0-.69-.56-1.25-1.25-1.25l-1.794-.001V1h2.892l.157-.25z" transform="translate(-35 -255) translate(35 255)" /> </g> </g> </g> </svg> </> ); }; export default Product; <file_sep>import React from "react"; import { makeStyles } from "@material-ui/core/styles"; import Table from "@material-ui/core/Table"; import TableBody from "@material-ui/core/TableBody"; import TableCell from "@material-ui/core/TableCell"; import TableContainer from "@material-ui/core/TableContainer"; import TableHead from "@material-ui/core/TableHead"; import TableRow from "@material-ui/core/TableRow"; import Pagination from "@material-ui/lab/Pagination"; import MessageCard from "./MessageCard"; import SortDown from "../../icons/SortDown"; const useStyles = makeStyles({ table: { minWidth: 650, borderCollapse: "separate", borderSpacing: "0 15px", }, }); function createData(name, calories, fat, carbs, protein) { return { name, calories, fat, carbs, protein }; } const rows = [ createData( "Frozen yoghurt", "Dec 12, 2020", "<NAME>, <NAME>", 24, 4.0, ), createData("Ice cream sandwich", 237, 9.0, 37, 4.3), createData("Eclair", 262, 16.0, 24, 6.0), createData("Cupcake", 305, 3.7, 67, 4.3), createData("Gingerbread", 356, 16.0, 49, 3.9), ]; export default function Messages() { const classes = useStyles(); return ( <> <TableContainer className="messages-card"> <Table className={classes.table} aria-label="simple table"> <TableHead> <TableRow> <TableCell> Sender <SortDown />{" "} </TableCell> <TableCell align="Left"> Date <SortDown /> </TableCell> <TableCell align="Left"> Content <SortDown /> </TableCell> </TableRow> </TableHead> <TableBody> {rows.map((row) => ( <MessageCard row={row} /> ))} </TableBody> </Table> </TableContainer> <Pagination count={10} variant="outlined" className="m-pagination" /> </> ); } <file_sep>const ContentCard = () => { return ( <div className="m-content"> <p> <b>Product Alert:</b> <NAME>, <NAME> </p> <span>My skin becomes itchy and red after using this product.</span> </div> ); }; export default ContentCard; <file_sep>import { useState } from "react"; import { makeStyles } from "@material-ui/core/styles"; import Table from "@material-ui/core/Table"; import TableBody from "@material-ui/core/TableBody"; import TableCell from "@material-ui/core/TableCell"; import TableContainer from "@material-ui/core/TableContainer"; import TableHead from "@material-ui/core/TableHead"; import TableRow from "@material-ui/core/TableRow"; import Paper from "@material-ui/core/Paper"; import Button from "@material-ui/core/Button"; import Container from "@material-ui/core/Container"; import { Grid } from "@material-ui/core"; import Header from "../../components/common/Header"; import Sidebar from "../../components/common/Sidebar"; import Brand from "./Brand"; import AddItemPopup from "./AddItemPopup"; const useStyles = makeStyles((theme) => ({ buttonsContainer: { padding: 20 }, table: { minWidth: 650 } })); export default function BrandsAndCommisions() { const classes = useStyles(); const [brands, setBrands] = useState([]); const [open, setOpen] = useState(false); const handleOpen = () => { setOpen(true); }; const handleClose = () => { setOpen(false); }; const saveBrandHandler = (title, commision) => { setBrands((brands) => [...brands, { title, commision }]); handleClose(); }; const deleteBrandHandler = (title) => { const newBrands = brands.filter((item) => item.title !== title); setBrands(newBrands); }; return ( <Container maxWidth="lg"> <div> <Grid container spacing={3}> <Grid container item xs={12}> <Grid item xs={3} className="sidebar"> <Sidebar /> </Grid> <Grid container item xs={9} className="main-layout"> <Grid item xs={12}> <Header /> <div className="messages"> <h1>Brand and Commisions</h1> <TableContainer component={Paper}> <Table className={classes.table} aria-label="simple table"> <TableHead> <TableRow> <TableCell>S. No</TableCell> <TableCell align="left">Brand</TableCell> <TableCell align="left">Commision</TableCell> <TableCell align="center">Actions</TableCell> </TableRow> </TableHead> <TableBody> {brands?.map((row, index) => ( <Brand deleteBrandHandler={deleteBrandHandler} key={row._id} index={index} row={row} /> ))} </TableBody> </Table> </TableContainer> <div className={classes.buttonsContainer}> <Button onClick={handleOpen} variant="contained" color="secondary" > Add Item </Button> </div> <AddItemPopup saveBrandHandler={saveBrandHandler} open={open} handleClose={handleClose} /> </div> </Grid> </Grid> </Grid> </Grid> </div> </Container> ); } <file_sep>import React from "react"; const SortDown = () => { return ( <> <svg xmlns="http://www.w3.org/2000/svg" width="9" height="6" viewBox="0 0 9 6" > <g fill="none" fill-rule="evenodd"> <g fill="#394034" fill-rule="nonzero"> <path d="M330.375 165.375c.182 0 .355-.082.52-.246l3.718-4.266.055-.082c.055-.054.082-.127.082-.219 0-.127-.046-.232-.137-.314-.09-.082-.2-.123-.328-.123h-7.82c-.128 0-.237.041-.328.123-.091.082-.137.187-.137.315 0 .109.027.19.082.246l.055.054 3.718 4.266c.165.164.338.246.52.246z" transform="translate(-326 -160)" /> </g> </g> </svg> </> ); }; export default SortDown; <file_sep>import TableCell from "@material-ui/core/TableCell"; import TableRow from "@material-ui/core/TableRow"; import Button from "@material-ui/core/Button"; const Brand = ({ row, index, deleteBrandHandler }) => { return ( <> <TableRow> <TableCell style={{ fontWeight: "bolder" }} component="th" scope="row"> {index + 1} </TableCell> <TableCell align="left">{row.title?.slice(0, 50)}</TableCell> <TableCell align="left">{row.content?.slice(0, 50)}</TableCell> <TableCell align="left"> <div style={{ display: "flex", justifyContent: "space-evenly" }}> <Button onClick={() => deleteBrandHandler(row.title)} variant="contained" color="secondary" > Del </Button> </div> </TableCell> </TableRow> </> ); }; export default Brand; <file_sep>const { Container, Grid } = require("@material-ui/core"); const Header = () => { return ( <> <div className="header"> <Container> <Grid container spacing={3} justifyContent="flex-end"> <Grid item xs={4} className="login"> <p><EMAIL></p> <p>Log Out</p> </Grid> </Grid> </Container> </div> </> ); }; export default Header; <file_sep>import { TableCell, TableRow } from "@material-ui/core"; import Paper from "@material-ui/core/Paper"; import ContentCard from "./ContentCard"; import SenderCard from "./SenderCard"; const MessageCard = ({ row }) => { return ( <TableRow key={row.name} component={Paper}> <TableCell component="th" scope="row"> <SenderCard /> </TableCell> <TableCell align="Left">Dec 12, 2020</TableCell> <TableCell align="Left"> <ContentCard /> </TableCell> </TableRow> ); }; export default MessageCard; <file_sep>import { Container, Grid } from "@material-ui/core"; import Header from "../../components/common/Header"; import Messages from "../../components/Messages"; import Sidebar from "../../components/common/Sidebar"; const AdminMessages = () => { return ( <Container maxWidth="lg"> <div> <Grid container spacing={3}> <Grid container item xs={12}> <Grid item xs={3} className="sidebar"> <Sidebar /> </Grid> <Grid container item xs={9} className="main-layout"> <Grid item xs={12}> <Header /> <div className="messages"> <h1>Messages</h1> <Messages /> </div> </Grid> </Grid> </Grid> </Grid> </div> </Container> ); }; export default AdminMessages; <file_sep>import { Button, TextField } from "@material-ui/core"; import { useForm } from "react-hook-form"; export default function AddItemForm({ saveBrandHandler }) { const { register, handleSubmit, formState: { errors } } = useForm(); const onSubmit = (data) => { const { title, content } = data; saveBrandHandler(title, content); console.log(title, content); }; return ( /* "handleSubmit" will validate your inputs before invoking "onSubmit" */ <form onSubmit={handleSubmit(onSubmit)}> <div> {/* include validation with required or other standard HTML validation rules */} <TextField {...register("title", { required: true })} id="title" label="title" fullWidth /> {/* errors will return when field validation fails */} {errors.title && <span>This field is required</span>} </div> <div> <TextField {...register("content", { required: true })} id="content" label="content" fullWidth /> {errors.content && <span>This field is required</span>} </div> <Button style={{ float: "right" }} type="submit" variant="contained" color="secondary" > Add Item </Button> </form> ); }
c84a274e71ac5478ece1280167298987cc5eb64e
[ "JavaScript" ]
15
JavaScript
RishabhBula/BothOfUs-test-task
9421537f6f92d6a5e3ab2e88115b68bd7d4b55c6
10456b53aaf0fdafab7dd716f1a673950a30587b
refs/heads/master
<file_sep>package main import ( "errors" "fmt" "strconv" ) const ( male = iota + 1 female ) type person struct { name string age int sex int books []string } func main() { me := person{ name: "Paulin", age: 29, sex: male, books: []string{"Dune", "Foundation"}, } fmt.Println("Je suis " + me.name + ", j'ai " + strconv.Itoa(me.age)) majorityStatus, err := getMajorityStatus(me.age) if err != nil { fmt.Println(err) } else { fmt.Println("je suis " + majorityStatus) } if me.sex == male { fmt.Println("Je suis un homme") } else { fmt.Println("Je suis une femme") } listBooks(me.books) inc(&me.age) fmt.Println("J'ai maintenant " + strconv.Itoa(me.age) + " ans !") } func getMajorityStatus(age int) (string, error) { if age < 0 { return "", errors.New("L'age ne peut pas être négatif") } if age >= 18 { return "majeur", nil } return "mineur", nil } func listBooks(books []string) { fmt.Println("Mes livres :") for index := range books { fmt.Println(books[index]) } } func inc(x *int) { *x++ }
442efaf42fde89806124f3fe60582a40052cd5b6
[ "Go" ]
1
Go
paulintrognon/golang-tutorial
66d2de46a7bf09e605c4015c1b9dc2ca453fe2e8
86df0bdea59efef911e9bc959d70fda0664cf1b8
refs/heads/main
<file_sep>import React from 'react' import {v4 as uuidv4} from 'uuid' import './styles/SearchResults.css' import ListOfCards from '../components/ListOfCards' import useResults from '../hooks/useResults' import SkeletonSearchResultsLoading from "../components/SkeletonSearchResultsLoading"; export default function SearchResults({params}) { const {keyword, type, keywordType} = params const {loading, recipes, setDietParam} = useResults({keyword, type, keywordType}) const dietLabels = [ {id: 1, name: "balanced"}, {id: 2, name: "high-fiber"}, {id: 3, name: "high-protein"}, {id: 4, name: "low-carb"}, {id: 5, name: "low-fat"}, {id: 6, name: "low-sodium"} ] const handleClick = e => { e.preventDefault() let dietParam = e.target.value return setDietParam( dietParam ) } return ( <> { loading ? <SkeletonSearchResultsLoading /> : (recipes.length) ? <div className="SearchResults__Container" > <div className="SearchResults__Header" > <h1>{decodeURI(keyword)}</h1> <ul className="Diet__Options" > { dietLabels.map((label) => ( <input key={uuidv4()} onClick={handleClick} type="button" value={label.name} className="Diet__Options-Item" /> )) } </ul> </div> <ListOfCards recipes={recipes} /> </div> : <h1 className="SearchResults__Container">There is not recipes</h1> } </> ) } <file_sep>/* eslint-disable import/no-anonymous-default-export */ export default [ { type: "mealType", content: [ { keyword: "breakfast", titleList: [ { name:"bacon", url: "https://images.unsplash.com/photo-1525184782196-8e2ded604bf7?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8Zm9vZCUyMGJyZWFrZmFzdCUyMGJhY29ufGVufDB8fDB8fA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60"}, { name:"Pudding", url: "https://images.unsplash.com/photo-1517777596324-5df4025800f2?ixid=MnwxMjA3fDB8MHxzZWFyY2h8OHx8Zm9vZCUyMGJyZWFrZmFzdCUyMHB1ZGRpbmd8ZW58MHx8MHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60"}, { name:"chicken and waffles", url: "https://images.unsplash.com/photo-1562918005-50afb98e5d32?ixid=MnwxMjA3fDB8MHxzZWFyY2h8Nnx8Zm9vZCUyMGJyZWFrZmFzdCUyMGNoaWNrZW58ZW58MHx8MHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60"}, { name:"avocado toast", url: "https://images.unsplash.com/photo-1512621776951-a57141f2eefd?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8Zm9vZCUyMGJyZWFrZmFzdCUyMGF2b2NhZG8lMjB0b2FzdHxlbnwwfHwwfHw%3D&auto=format&fit=crop&w=300&q=60"}, { name:"home fries", url: "https://images.unsplash.com/photo-1520074881623-f6cc435eb449?ixid=MnwxMjA3fDB8MHxzZWFyY2h8Mnx8Zm9vZCUyMGJyZWFrZmFzdCUyMGhvbWUlMjBmcmllc3xlbnwwfHwwfHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60"}, { name:"cereal", url: "https://images.unsplash.com/photo-1457386335663-6115e304bd29?ixid=MnwxMjA3fDB8MHxzZWFyY2h8NXx8Zm9vZCUyMGJyZWFrZmFzdCUyMGNlcmVhbHxlbnwwfHwwfHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60"}, { name:"breakfast wrap", url: "https://images.unsplash.com/photo-1521390188846-e2a3a97453a0?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8Zm9vZCUyMGJyZWFrZmFzdCUyMHdyYXB8ZW58MHx8MHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60"}, { name:"breakfast sandwich", url: "https://images.unsplash.com/photo-1521390188846-e2a3a97453a0?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8Zm9vZCUyMGJyZWFrZmFzdCUyMHdyYXB8ZW58MHx8MHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60"}, { name:"french toast", url: "https://images.unsplash.com/photo-1492683962492-deef0ec456c0?ixid=MnwxMjA3fDB8MHxzZWFyY2h8NHx8Zm9vZCUyMGJyZWFrZmFzdCUyMGZyZW5jaCUyMHRvYXN0fGVufDB8fDB8fA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60"}, { name:"sausage", url: "https://images.unsplash.com/photo-1509722747041-616f39b57569?ixid=MnwxMjA3fDB8MHxzZWFyY2h8Mnx8Zm9vZCUyMGJyZWFrZmFzdCUyMHNhdXNhZ2V8ZW58MHx8MHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" } ] }, { keyword: "dinner", titleList: [ { name:"Shrimp & Snap Pea Stir-Fry", url: "https://images.unsplash.com/photo-1430163393927-3dab9af7ea38?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8Zm9vZCUyMGRpbm5lciUyMHNuYXAlMjBwZWF8ZW58MHx8MHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"<NAME> Salad", url: "https://images.unsplash.com/photo-1522666257812-173fdc2d11fe?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8Zm9vZCUyMGRpbm5lciUyMHBlc3RvJTIwdG9ydGVsbGluaXxlbnwwfHwwfHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"Tofu Coconut Curry", url: "https://images.unsplash.com/photo-1588166524941-3bf61a9c41db?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8Zm9vZCUyMGRpbm5lciUyMHRvZnUlMjBjb2NvbnV0fGVufDB8fDB8fA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"Slow-Cooker Beef & Potato Stew", url: "https://images.unsplash.com/photo-1447129568466-afbabc829d86?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8Zm9vZCUyMGRpbm5lciUyMHNsb3clMjBjb29rZXJ8ZW58MHx8MHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"Sweet Potato Enchiladas", url: "https://images.unsplash.com/photo-1502472231352-10142bacaba2?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8NXx8Zm9vZCUyMGRpbm5lciUyMHN3ZWV0JTIwcG90YXRvfGVufDB8fDB8fA%3D%3D&auto=format&fit=crop&w=300&q=60" }, { name:"Teriyaki Chicken & Pineapple Rice", url: "https://images.unsplash.com/photo-1598515214211-89d3c73ae83b?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8Zm9vZCUyMGRpbm5lciUyMHRlcml5YWtpJTIwY2hpY2tlbnxlbnwwfHwwfHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"Lime Tilapia & Rice", url: "https://images.unsplash.com/34/rcaNUh3pQ9GD8w7Iy8qE__DSC0940.jpg?ixid=MnwxMjA3fDB8MHxzZWFyY2h8Nnx8Zm9vZCUyMGRpbm5lciUyMGxpbWUlMjB0aWxhcGlhfGVufDB8fDB8fA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"Chicken Skillet Noodles", url: "https://images.unsplash.com/photo-1473093226795-af9932fe5856?ixid=MnwxMjA3fDB8MHxzZWFyY2h8NXx8Zm9vZCUyMGRpbm5lciUyMG5vb2RsZXxlbnwwfHwwfHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"Pork & Quinoa-Stuffed Peppers", url: "https://images.unsplash.com/photo-1543340713-1bf56d3d1b68?ixid=MnwxMjA3fDB8MHxzZWFyY2h8Mnx8Zm9vZCUyMGRpbm5lciUyMHBvcmt8ZW58MHx8MHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"Caribbean Chicken", url: "https://images.unsplash.com/photo-1610057099443-fde8c4d50f91?ixid=MnwxMjA3fDB8MHxzZWFyY2h8Mnx8Zm9vZCUyMGRpbm5lciUyMCUyMGNoaWNrZW58ZW58MHx8MHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" } ] }, { keyword: "lunch", titleList: [ { name:"BBQ Chicken Salad", url: "https://images.unsplash.com/photo-1592231167202-a253c3c2d3fa?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8Zm9vZCUyMGx1bmNofGVufDB8fDB8fA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"Easy Burrito Bowls", url: "https://images.unsplash.com/photo-1579536568809-62154a3bee07?ixid=MnwxMjA3fDB8MHxzZWFyY2h8Mnx8Zm9vZCUyMGx1bmNofGVufDB8fDB8fA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"Steak Fajita Salad", url: "https://images.unsplash.com/photo-1597393353415-b3730f3719fe?ixid=MnwxMjA3fDB8MHxzZWFyY2h8M3x8Zm9vZCUyMGx1bmNofGVufDB8fDB8fA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"Quinoa Fruit Salad", url: "https://images.unsplash.com/photo-1457374282245-3ad724e4256a?ixid=MnwxMjA3fDB8MHxzZWFyY2h8OHx8Zm9vZCUyMGx1bmNofGVufDB8fDB8fA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"Chinese Chicken Salad", url: "https://images.unsplash.com/photo-1460819739742-50e4486578f5?ixid=MnwxMjA3fDB8MHxzZWFyY2h8N3x8Zm9vZCUyMGx1bmNofGVufDB8fDB8fA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"Kale Pesto Egg Salad", url: "https://images.unsplash.com/photo-1546173078-a7d5f578b31c?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MTJ8fGZvb2QlMjBsdW5jaHxlbnwwfHwwfHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"Greek Quinoa and Avocado Salad", url: "https://images.unsplash.com/photo-1585417791023-a5a6164b2646?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MjB8fGZvb2QlMjBsdW5jaHxlbnwwfHwwfHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"Black Bean Quinoa Salad", url: "https://images.unsplash.com/photo-1585672840563-f2af2ced55c9?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MjV8fGZvb2QlMjBsdW5jaHxlbnwwfHwwfHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"Chicken Pesto Sandwich", url: "https://images.unsplash.com/photo-1473093226795-af9932fe5856?ixid=MnwxMjA3fDB8MHxzZWFyY2h8Mjh8fGZvb2QlMjBsdW5jaHxlbnwwfHwwfHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"Greek Yogurt Chicken Salad Sandwich", url: "https://images.unsplash.com/photo-1485963631004-f2f00b1d6606?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8Mzh8fGZvb2QlMjBsdW5jaHxlbnwwfHwwfHw%3D&auto=format&fit=crop&w=300&q=60" } ] }, { keyword: "snack", titleList: [ { name:"Potato Chips", url: "https://images.unsplash.com/photo-1613919113640-25732ec5e61f?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8cG90YXRvJTIwY2hpcHN8ZW58MHx8MHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"Cookies", url: "https://images.unsplash.com/photo-1548365328-8c6db3220e4c?ixid=MnwxMjA3fDB8MHxzZWFyY2h8Mnx8Y29va2llc3xlbnwwfHwwfHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"Cheese Crackers", url: "https://images.unsplash.com/photo-1617210825218-a738b7380033?ixid=MnwxMjA3fDB8MHxzZWFyY2h8Mnx8Y2hlZXNlJTIwY3JhY2tlcnN8ZW58MHx8MHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"Pop-Tarts", url: "https://images.unsplash.com/photo-1559856191-dbba44b72206?ixid=MnwxMjA3fDB8MHxzZWFyY2h8M3x8cG9wJTIwdGFydHN8ZW58MHx8MHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"Tortilla Chips", url: "https://images.unsplash.com/photo-1514517521153-1be72277b32f?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8cG9wJTIwdGFydHN8ZW58MHx8MHx8&auto=format&fit=crop&w=300&q=60" }, { name:"Popcorn", url: "https://images.unsplash.com/photo-1578849278619-e73505e9610f?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8cG9wY29ybnxlbnwwfHwwfHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"Mixed Fruit", url: "https://images.unsplash.com/photo-1568625365131-079e026a927d?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8bWl4ZWQlMjBmcnVpdHN8ZW58MHx8MHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"Fruit Snacks", url: "https://images.unsplash.com/photo-1546548970-71785318a17b?ixid=MnwxMjA3fDB8MHxzZWFyY2h8Mnx8bWl4ZWQlMjBmcnVpdHN8ZW58MHx8MHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"Pretzels", url: "https://images.unsplash.com/photo-1511951786553-1d4f975424c9?ixid=MnwxMjA3fDB8MHxzZWFyY2h8Mnx8cHJldHplbHN8ZW58MHx8MHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"<NAME>", url: "https://images.unsplash.com/photo-1568086256437-e745ec321426?ixid=MnwxMjA3fDB8MHxzZWFyY2h8NXx8Z3Jhbm9sYXxlbnwwfHwwfHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" } ] }, { keyword: "teatime", titleList: [ { name:"Tarts", url: "https://images.unsplash.com/photo-1497800640957-3100979af57c?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8dGVhJTIwdGltZXxlbnwwfHwwfHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"Brownies", url: "https://images.unsplash.com/photo-1613149355673-c9bc2f590071?ixid=MnwxMjA3fDB8MHxzZWFyY2h8NHx8dGVhJTIwdGltZXxlbnwwfHwwfHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"Whoopie pies", url: "https://images.unsplash.com/photo-1619149557955-9f3a0b450f39?ixid=MnwxMjA3fDB8MHxzZWFyY2h8OXx8dGVhJTIwdGltZXxlbnwwfHwwfHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"Lemon drizzle cake", url: "https://images.unsplash.com/photo-1586097384553-af3db3537777?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MTR8fHRlYSUyMHRpbWV8ZW58MHx8MHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"Fruit scones", url: "https://images.unsplash.com/photo-1572097045660-08a1348b49fe?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MjB8fHRlYSUyMHRpbWV8ZW58MHx8MHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"Florentines", url: "https://images.unsplash.com/photo-1512311734173-51a49c854e78?ixid=MnwxMjA3fDB8MHxzZWFyY2h8Mjd8fHRlYSUyMHRpbWV8ZW58MHx8MHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"Chai Tea Latte", url: "https://images.unsplash.com/photo-1594136604897-29f7e564db27?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MjN8fHRlYSUyMHRpbWV8ZW58MHx8MHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"Cupcakes", url: "https://images.unsplash.com/photo-1611280610919-5ce571923a87?ixid=MnwxMjA3fDB8MHxzZWFyY2h8Mjl8fHRlYSUyMHRpbWV8ZW58MHx8MHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"Biscotti", url: "https://images.unsplash.com/photo-1531967802777-e0f8fc276609?ixid=MnwxMjA3fDB8MHxzZWFyY2h8Mjh8fHRlYSUyMHRpbWV8ZW58MHx8MHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"Banana bread", url: "https://images.unsplash.com/photo-1507499155415-696f83e0e828?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MzV8fHRlYSUyMHRpbWV8ZW58MHx8MHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" } ] }, ] },{ type: "dishType", content: [ { keyword: "Pancake", titleList: [ { name:"Irish Boxty", url: "https://images.unsplash.com/photo-1559100644-59dad675d48d?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8ZGlzaCUyMHR5cGUlMjBmb29kfGVufDB8fDB8fA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"American-Style", url: "https://images.unsplash.com/photo-1621236378699-8597faf6a176?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8Mnx8ZGlzaCUyMHR5cGUlMjBmb29kfGVufDB8fDB8fA%3D%3D&auto=format&fit=crop&w=300&q=60" }, { name:"Scotch Pancakes", url: "https://images.unsplash.com/photo-1602030638412-bb8dcc0bc8b0?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8YW1lcmljYW4lMjBmb29kfGVufDB8fDB8fA%3D%3D&auto=format&fit=crop&w=300&q=60" }, { name:"Blueberry pancakes", url: "https://images.unsplash.com/photo-1560717845-968823efbee1?ixid=MnwxMjA3fDB8MHxzZWFyY2h8Nnx8YW1lcmljYW4lMjBmb29kfGVufDB8fDB8fA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"Russian Blinis", url: "https://images.unsplash.com/photo-1538220856186-0be0e085984d?ixid=MnwxMjA3fDB8MHxzZWFyY2h8NXx8YW1lcmljYW4lMjBmb29kfGVufDB8fDB8fA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"Japanese cabbage", url: "https://images.unsplash.com/photo-1517306085770-871ff74b2274?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MTR8fGFtZXJpY2FuJTIwZm9vZHxlbnwwfHwwfHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"Danish Aebleskiver", url: "https://images.unsplash.com/photo-1586985288123-2495f577c250?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MTJ8fGFtZXJpY2FuJTIwZm9vZHxlbnwwfHwwfHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"Coconut crepes", url: "https://images.unsplash.com/photo-1488558980948-81db7f6c239c?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MjJ8fGFtZXJpY2FuJTIwZm9vZHxlbnwwfHwwfHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"Korean Jeon", url: "https://images.unsplash.com/photo-1581618478941-515a55d3fce5?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MzN8fGFtZXJpY2FuJTIwZm9vZHxlbnwwfHwwfHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"Dutch Poffertjes", url: "https://images.unsplash.com/photo-1598511756348-640384c52ada?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MzV8fGFtZXJpY2FuJTIwZm9vZHxlbnwwfHwwfHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" } ] }, { keyword: "Bread", titleList: [ { name:"Banana Bread", url: "https://images.unsplash.com/photo-1518562923427-19e694fbd8e9?ixid=MnwxMjA3fDB8MHxzZWFyY2h8Nnx8YnJlYWQlMjBmb29kfGVufDB8fDB8fA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"Baguette", url: "https://images.unsplash.com/photo-1523314832514-41a5cbaefa51?ixid=MnwxMjA3fDB8MHxzZWFyY2h8OHx8YnJlYWQlMjBmb29kfGVufDB8fDB8fA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"Breadstick", url: "https://images.unsplash.com/photo-1533782654613-826a072dd6f3?ixid=MnwxMjA3fDB8MHxzZWFyY2h8N3x8YnJlYWQlMjBmb29kfGVufDB8fDB8fA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"Brioche", url: "https://images.unsplash.com/photo-1512335510234-6166bc3fdaa0?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MTF8fGJyZWFkJTIwZm9vZHxlbnwwfHwwfHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"Challah", url: "https://images.unsplash.com/photo-1497581175344-8a5f1a0142a5?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MTJ8fGJyZWFkJTIwZm9vZHxlbnwwfHwwfHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"Ciabatta", url: "https://images.unsplash.com/photo-1508616185939-efe767994166?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MTR8fGJyZWFkJTIwZm9vZHxlbnwwfHwwfHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"Cornbread", url: "https://images.unsplash.com/photo-1505253364048-bf56659875a6?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MTN8fGJyZWFkJTIwZm9vZHxlbnwwfHwwfHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"Focaccia", url: "https://images.unsplash.com/photo-1530610476181-d83430b64dcd?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MTZ8fGJyZWFkJTIwZm9vZHxlbnwwfHwwfHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"Multigrain Bread", url: "https://images.unsplash.com/photo-1550599112-0c21a831f6b9?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MjV8fGJyZWFkJTIwZm9vZHxlbnwwfHwwfHw%3D&auto=format&fit=crop&w=300&q=60" }, { name:"Pita Bread", url: "https://images.unsplash.com/photo-1521791697570-e1f13d0b81d0?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MjN8fGJyZWFkJTIwZm9vZHxlbnwwfHwwfHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" } ] }, { keyword: "Cereals", titleList: [ { name:"Peanut Butter", url: "https://images.unsplash.com/photo-1526127230111-0197afe94d72?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8Y2VyZWFsJTIwZm9vZHxlbnwwfHwwfHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"Fruit Granola", url: "https://images.unsplash.com/photo-1505253213348-ce3e0ff1f0cc?ixid=MnwxMjA3fDB8MHxzZWFyY2h8Nnx8Y2VyZWFsJTIwZm9vZHxlbnwwfHwwfHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"Strawberry Cereal", url: "https://images.unsplash.com/photo-1489444444961-d0fda97f0986?ixid=MnwxMjA3fDB8MHxzZWFyY2h8N3x8Y2VyZWFsJTIwZm9vZHxlbnwwfHwwfHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"Cookies", url: "https://images.unsplash.com/photo-1528711832838-46c60d34b4e3?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8M3x8Y2VyZWFsJTIwZm9vZHxlbnwwfHwwfHw%3D&auto=format&fit=crop&w=300&q=60" }, { name:"Cheese Crispies", url: "https://images.unsplash.com/photo-1506805841350-215d85d53e04?ixid=MnwxMjA3fDB8MHxzZWFyY2h8OXx8Y2VyZWFsJTIwZm9vZHxlbnwwfHwwfHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"Yoghurt Bars", url: "https://images.unsplash.com/photo-1470909752008-c78c7f6423a3?ixid=MnwxMjA3fDB8MHxzZWFyY2h8OHx8Y2VyZWFsJTIwZm9vZHxlbnwwfHwwfHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"<NAME>", url: "https://images.unsplash.com/photo-1526430578163-6713faa4bbc5?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MTF8fGNlcmVhbCUyMGZvb2R8ZW58MHx8MHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"Cinnamon-Raisin", url: "https://images.unsplash.com/photo-1457386335663-6115e304bd29?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MTR8fGNlcmVhbCUyMGZvb2R8ZW58MHx8MHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"S'more Bites", url: "https://images.unsplash.com/photo-1614961234274-f204d01c115e?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MTd8fGNlcmVhbCUyMGZvb2R8ZW58MHx8MHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"Marshmallow Crispie Bars", url: "https://images.unsplash.com/photo-1550335430-182e6165c01c?ixid=MnwxMjA3fDB8MHxzZWFyY2h8Mjd8fGNlcmVhbCUyMGZvb2R8ZW58MHx8MHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" } ] }, { keyword: "Desserts", titleList: [ { name:"Custards and Puddings", url: "https://images.unsplash.com/photo-1497034825429-c343d7c6a68f?ixid=MnwxMjA3fDB8MHxzZWFyY2h8Mnx8ZGVzc2VydHMlMjBmb29kfGVufDB8fDB8fA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"Frozen Desserts", url: "https://images.unsplash.com/photo-1468218620578-e8d78dcda7b1?ixid=MnwxMjA3fDB8MHxzZWFyY2h8NHx8ZGVzc2VydHMlMjBmb29kfGVufDB8fDB8fA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"Cakes", url: "https://images.unsplash.com/photo-1488477181946-6428a0291777?ixid=MnwxMjA3fDB8MHxzZWFyY2h8M3x8ZGVzc2VydHMlMjBmb29kfGVufDB8fDB8fA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"Cookies", url: "https://images.unsplash.com/photo-1499636136210-6f4ee915583e?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8NXx8ZGVzc2VydHMlMjBmb29kfGVufDB8fDB8fA%3D%3D&auto=format&fit=crop&w=300&q=60" }, { name:"Pies", url: "https://images.unsplash.com/photo-1506459225024-1428097a7e18?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8OXx8ZGVzc2VydHMlMjBmb29kfGVufDB8fDB8fA%3D%3D&auto=format&fit=crop&w=300&q=60" }, { name:"Chocolates and Candies", url: "https://images.unsplash.com/photo-1474045326708-cdc78c2487cb?ixid=MnwxMjA3fDB8MHxzZWFyY2h8OHx8ZGVzc2VydHMlMjBmb29kfGVufDB8fDB8fA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"Pastries", url: "https://images.unsplash.com/photo-1488477081514-c6da99e85213?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MTN8fGRlc3NlcnRzJTIwZm9vZHxlbnwwfHwwfHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"Cookie Dough Brownies", url: "https://images.unsplash.com/photo-1470124182917-cc6e71b22ecc?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MTF8fGRlc3NlcnRzJTIwZm9vZHxlbnwwfHwwfHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"Monster Cookie Dough", url: "https://images.unsplash.com/photo-1525059337994-6f2a1311b4d4?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MTZ8fGRlc3NlcnRzJTIwZm9vZHxlbnwwfHwwfHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"Cookie Dough Buckeyes", url: "https://images.unsplash.com/photo-1472555794301-77353b152fb7?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MTh8fGRlc3NlcnRzJTIwZm9vZHxlbnwwfHwwfHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" } ] }, { keyword: "Drinks", titleList: [ { name:"Old Fashioned", url: "https://images.unsplash.com/photo-1551024709-8f23befc6f87?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8ZHJpbmtzfGVufDB8fDB8fA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"Margarita", url: "https://images.unsplash.com/photo-1582106245687-cbb466a9f07f?ixid=MnwxMjA3fDB8MHxzZWFyY2h8Mnx8ZHJpbmtzfGVufDB8fDB8fA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"Cosmopolitan", url: "https://images.unsplash.com/photo-1497534446932-c925b458314e?ixid=MnwxMjA3fDB8MHxzZWFyY2h8NHx8ZHJpbmtzfGVufDB8fDB8fA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"Negroni", url: "https://images.unsplash.com/photo-1513558161293-cdaf765ed2fd?ixid=MnwxMjA3fDB8MHxzZWFyY2h8NXx8ZHJpbmtzfGVufDB8fDB8fA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"<NAME>", url: "https://images.unsplash.com/photo-1481671703460-040cb8a2d909?ixid=MnwxMjA3fDB8MHxzZWFyY2h8OHx8ZHJpbmtzfGVufDB8fDB8fA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"Martini", url: "https://images.unsplash.com/photo-1505252585461-04db1eb84625?ixid=MnwxMjA3fDB8MHxzZWFyY2h8N3x8ZHJpbmtzfGVufDB8fDB8fA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"Mojito", url: "https://images.unsplash.com/photo-1559842438-2942c907c8fe?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MTJ8fGRyaW5rc3xlbnwwfHwwfHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"<NAME>", url: "https://images.unsplash.com/photo-1462887749044-b47cb05b83b8?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MTN8fGRyaW5rc3xlbnwwfHwwfHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"French 75", url: "https://images.unsplash.com/photo-1598679253587-829c6cc6c6fc?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MTB8fGRyaW5rc3xlbnwwfHwwfHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"Manhattan", url: "https://images.unsplash.com/photo-1547595628-c61a29f496f0?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MjB8fGRyaW5rc3xlbnwwfHwwfHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" } ] }, ] },{ type: "healthyType", content: [ { keyword: "food", titleList: [ { name:"alcohol-free", url: "https://images.unsplash.com/photo-1509459276366-50507f1e29a6?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"pork-free", url: "https://images.unsplash.com/photo-1598515213692-5f252f75d785?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"celery-free", url: "https://images.unsplash.com/photo-1430163393927-3dab9af7ea38?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60"}, { name:"crustacean-free", url:"https://images.unsplash.com/photo-1464454709131-ffd692591ee5?ixid=MnwxMjA3fDB8MHxzZWFyY2h8NHx8Zm9vZCUyMGNydXN0YWNlYW4lMjBmcmVlfGVufDB8fDB8fA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60"}, { name:"gluten-free", url: "https://images.unsplash.com/photo-1473093226795-af9932fe5856?ixid=MnwxMjA3fDB8MHxzZWFyY2h8M3x8Zm9vZCUyMGdsdXRlbiUyMGZyZWV8ZW58MHx8MHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60" }, { name:"vegetarian", url: "https://images.unsplash.com/photo-1437750769465-301382cdf094?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8Zm9vZCUyMHZlZ2V0YXJpYW58ZW58MHx8MHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60"} ] } ] } ] <file_sep>import React from 'react' import {v4 as uuidv4} from 'uuid' import Skeleton from 'react-loading-skeleton' export default function SkeletonSearchResultsLoading() { return ( <div className="SearchResults__Container" data-testid="skeleton-container" > <h1><Skeleton width={150} /></h1> <ul className="Diet__Options" > { [1,2,3,4,5,6].map((label) => ( <Skeleton key={uuidv4()} height={40} width={90} value={label.name} className="Diet__Options-Item" /> )) } </ul> <div className="List__Cards" > {[1,2,3,4,5,6].map(()=>( <figure key={uuidv4()} className="Card__Container" > <div className="Card__Image-Polaroid" > <Skeleton width={400} height={300} className="Card__Image"/> </div> <div className="Info" > <Skeleton width={200} className="Info__Kicker"/> <div> <h1 className="Info__Title" ><Skeleton width={100} height={20}/></h1> </div> <div className="Info__Relevant"> <span><Skeleton width={100}/></span> <span><Skeleton width={100}/></span> </div> </div> </figure> )) } </div> </div> ) } <file_sep>const APP_KEY = "7a559f6c982b3ea2cc4a7208024f028d" const APP_ID = "c9da61d9" export default function getResults({keyword, dietParam, type, keywordType}) { console.log(keyword, type, keywordType) let API_URL = `https://api.edamam.com/api/recipes/v2?type=public&q=${keyword}&app_id=${APP_ID}&app_key=${APP_KEY}`; if(dietParam){ API_URL = `https://api.edamam.com/api/recipes/v2?type=public&q=${keyword}&app_id=${APP_ID}&app_key=${APP_KEY}&diet=${dietParam}` }else if(type && type === "mealType") { API_URL = `https://api.edamam.com/api/recipes/v2?type=public&q=${keyword}&app_id=${APP_ID}&app_key=${APP_KEY}&mealType=${keywordType}` }else if(type && type === "dishType"){ API_URL = `https://api.edamam.com/api/recipes/v2?type=public&q=${keyword}&app_id=${APP_ID}&app_key=${APP_KEY}&dishType=${keywordType}` }else if(type && type === "healthyType"){ API_URL = `https://api.edamam.com/api/recipes/v2?type=public&q=${keywordType}&app_id=${APP_ID}&app_key=${APP_KEY}&health=${keyword}` }else { API_URL = `https://api.edamam.com/api/recipes/v2?type=public&q=${keyword}&app_id=${APP_ID}&app_key=${APP_KEY}` } return fetch(API_URL) .then(res => res.json()) .then(response => { const {hits} = response if(Array.isArray(hits)){ return hits } }) } <file_sep>import React, { useState } from 'react' const Context = React.createContext({}); export function RecipesContextProvider({children}) { const [recipes, setRecipes] = useState([]) return ( <Context.Provider value={{recipes, setRecipes}} > {children} </Context.Provider> ) } export default Context<file_sep>import React from 'react' import { Route, Switch } from 'wouter' import Home from './pages/Home' import RecipeDetail from './pages/RecipeDetail' import SearchResults from './pages/SearchResults' import OptionsAndCategories from './pages/OptionsAndCategories' import './App.css' import {RecipesContextProvider} from './context/RecipesContext' import Layout from './components/Layout' import NotFound from './pages/NotFound' function App() { return ( <div className="App"> <RecipesContextProvider> <Layout> <Switch> <Route path="/" component={Home} /> <Route path="/search/:keyword/:type?/:keywordType?" component={SearchResults} /> <Route path="/recipe/:id" component={RecipeDetail} /> <Route path="/meal-type/:mealType" component={OptionsAndCategories}/> <Route path="/dish-type/:dishType" component={OptionsAndCategories}/> <Route path="/healthy-meals/:healthyType" component={OptionsAndCategories}/> <Route path="/:rest*" component={NotFound}/> </Switch> </Layout> </RecipesContextProvider> </div> ); } export default App; <file_sep>import React from 'react' import {Link} from 'wouter' import './styles/NotFound.css' export default function NotFound() { return ( <div className="NotFound__Container" > <span>404</span> <span>Ooops!!</span> <span>THAT PAGE DOESN'T EXIST OR IS UNAVAILABLE.</span> <Link className="NotFound__Button" to="/" >Go Back to Home</Link> </div> ) } <file_sep>import React from 'react' import NavSidebar from './NavSidebar' export default function Layout(props) { return ( <> <NavSidebar /> {props.children} </> ) } <file_sep>import React from 'react' import {useLocation, Link} from 'wouter' import { v4 as uuidv4 } from 'uuid'; import suggestionsList from '../utils/suggestionsList' import './styles/SuggestionsList.css' export default function SuggestionsList({category}) { const [path, pushLocation] = useLocation() const {type, keywordType} = category let element suggestionsList.forEach( item => { if(item.type === type){ item.content.forEach( elem => { if(elem.keyword === keywordType){ element = elem } }) } }) // const handleOnClick = (e) => { // const keyword = e.target.value // console.log(keyword, type, keywordType) // pushLocation(`/search/${keyword}/${type}/${keywordType}`) // } return ( <> <section className="SuggestionList" > <div className="SuggestionList__Header"> <h2>Suggestions</h2> </div> <ul className="SuggestionList__List" > { element.titleList.map( item =>( <li className="SuggestionList__Card" key={uuidv4()}> <Link to={`/search/${item.name}/${type}/${keywordType}`}> <div className="Img-Thumbnail"> <img loading="lazy" src={item.url} alt="food"/> </div> <div className="Img-Title"> <h3>{item.name}</h3> </div> </Link> </li> )) } </ul> </section> </> ) } <file_sep>import { useContext, useEffect, useState } from 'react' import RecipesContext from '../context/RecipesContext' import getResults from '../services/getResults' export default function useResults({keyword, type, keywordType} = {keyword: null, type: null, keywordType: null}) { const [loading, setLoading] = useState(false) const [dietParam, setDietParam] = useState(null) const {recipes, setRecipes} = useContext(RecipesContext) const keywordToUse = keyword useEffect(() => { if(type || dietParam) return setLoading(true) getResults({keyword: keywordToUse}) .then( recipes => { setRecipes(recipes) setLoading(false) }) }, [keyword, keywordToUse, setRecipes, dietParam, type]) useEffect(() => { if(dietParam == null) return setLoading(true) getResults({keyword: keywordToUse, dietParam}) .then( filteredByDiet => { setRecipes(filteredByDiet) setLoading(false) }) }, [keywordToUse, dietParam, setRecipes]) useEffect(() => { if(type == null) return setLoading(true) getResults({keyword: keywordToUse, type, keywordType}) .then( filteredByMealType => { setRecipes(filteredByMealType) setLoading(false) }) }, [keywordToUse, type,setRecipes, keywordType]) return {loading, recipes, setDietParam} } <file_sep>import React from 'react' import {v4 as uuidv4} from 'uuid' import useGlobalRecipes from '../hooks/useGlobalRecipes' import getIdRecipeFromUri from '../utils/getIdRecipeFromUri' import './styles/RecipeDetail.css' import useResults from "../hooks/useResults"; import { BiCheck } from 'react-icons/bi'; export default function RecipeDetail({params}) { const recipes = useGlobalRecipes() if(!recipes.length) return (<h1>There is not that Information</h1>) const {recipe} = recipes.find( singleRecipe => { let idSingleRecipe = getIdRecipeFromUri(singleRecipe.recipe.uri) if(idSingleRecipe === params.id) return singleRecipe }) return ( <> <div className="Detail__Container"> <div className="Detail__Image-Polaroid" > <img src={recipe.image} alt="this-is-a-detail" /> </div> <div className="Info-Detail" > <span className="Info__Kicker-Detail">{recipe.source} Recommend</span> <div className="Info-Description" > <h1 className="Info__Title-Detail" >{recipe.label}</h1> <div className="Info__Relevant-Detail"> <div className="Info__Relevant-Box" > <span>CALORIES</span> <div> <strong>{Math.round(recipe.calories)}</strong> <span> Kcal</span> </div> </div> <div className="Info__Relevant-Box" > <span>CARB</span> <div> <strong>{Math.round(recipe.totalNutrients.CHOCDF.quantity)}</strong> <span> g</span> </div> </div> <div className="Info__Relevant-Box" > <span>FAT</span> <div> <strong>{Math.round(recipe.totalNutrients.FAT.quantity)}</strong> <span> g</span> </div> </div> <div className="Info__Relevant-Box" > <span>PROTS</span> <div> <strong>{Math.round(recipe.totalNutrients.PROCNT.quantity)}</strong> <span> g</span> </div> </div> </div> <div className="Info__IngredientsList"> <h3>Ingredients :</h3> <ul> { recipe.ingredientLines.map( ingredient => <div className="Ingredient__Item" > <BiCheck className="Ingredient__Item-Icon"/> <li key={uuidv4()} >{ingredient}</li> </div> ) } </ul> </div> </div> </div> </div> </> ) } <file_sep>import React from 'react' import SuggestionsList from '../components/SuggestionsList' export default function OptionsAndCategories({params}) { const getCategory = (obj) => { return { type: Object.keys(obj).toString(), keywordType: Object.values(obj).toString() } } let category = getCategory(params) return ( <div> <SuggestionsList category={category} /> </div> ) } <file_sep>import React, { useState, useRef } from 'react' import {useLocation} from 'wouter' import { BiSearchAlt2 } from 'react-icons/bi'; import './styles/Home.css' export default function Home() { const [keyword, setKeyword] = useState('') const [path, pushLocation] = useLocation() const searchInput = useRef() const handleSubmit = e => { e.preventDefault() pushLocation(`/search/${keyword}`) } const handleChange = () => { setKeyword(searchInput.current.value) } return ( <div className="Home"> <div className="Background-Square"></div> <div className="Background-Triangle"></div> <div className="Background-Circle" ></div> <div className="Background-Cube"></div> <header className="Header" > <h1 className="Header__Title" >Healthy habits for a <b>better life</b></h1> <p className="Header__Subtitle" >The pocket nutritionist app that will help you reach your health and weight goals</p> </header> <form onSubmit={handleSubmit} className="Form--Search" > <input onChange={handleChange} type="text" placeholder="Type a recipe, a food ..." value={keyword} ref={searchInput}/> <button>Search</button> </form> </div> ) } <file_sep># RECIPES NUTRITION This Project is a sample how to use Javascript for a basic development. ## Getting Started This app is a searcher of food. You can put a food and add its amount of proteins, carbs and calories. The app auto sum all data and show you the total amounts. ## Deployment The app was upload on github-page, you can visit the app [here](https://jorge-llanque.github.io/Calories_Counter/) ## TECHNOLOGIES AND TOOLS In general I'm using javascript for the development. But for more specification I'm using: * ReactJS * Javascript * Jquery * CSS3 * HTML5 * Git ## AUTHOR * **<NAME>** - *JS Developer* - [LinkedIn](https://www.linkedin.com/in/jorgellanque) <file_sep>import { useContext } from "react"; import RecipesContext from '../context/RecipesContext' export default function useGlobalRecipes() { return useContext(RecipesContext).recipes }<file_sep><Navigation activeItemId="/home" onSelect={({itemId}) => { if(itemId){ handleSelect(itemId) } }} items={[ { key: uuidv4(), title: 'Home', itemId: '/', elemBefore: () => <BiMenuAltLeft name="inbox" />, }, { key: uuidv4(), title: 'Meal Type', elemBefore: () => <BiMenuAltLeft name="inbox" />, subNav: [ { key: uuidv4(), title: "Breakfast", itemId: "/meal-type/breakfast", elemBefore: () => <BiMenuAltLeft name="inbox" />, }, { key: uuidv4(), title: "Dinner", itemId: "/meal-type/dinner", elemBefore: () => <BiMenuAltLeft name="inbox" />, }, { key: uuidv4(), title: "Lunch", itemId: "/meal-type/lunch", elemBefore: () => <BiMenuAltLeft name="inbox" />, }, { key: uuidv4(), title: "Snack", itemId: "/meal-type/snack", elemBefore: () => <BiMenuAltLeft name="inbox" />, }, { key: uuidv4(), title: "Tea Time", itemId: "/meal-type/teatime", elemBefore: () => <BiMenuAltLeft name="inbox" />, } ] }, { key: uuidv4(), title: 'Dish Type', elemBefore: () => <BiMenuAltLeft name="inbox" />, subNav: [ { key: uuidv4(), title: "Biscuits", itemId: "/dish-type/biscuits", elemBefore: () => <BiMenuAltLeft name="inbox" />, }, { key: uuidv4(), title: "Breads", itemId: "/dish-type/bread", elemBefore: () => <BiMenuAltLeft name="inbox" />, }, { key: uuidv4(), title: "Cereals", itemId: "/dish-type/cereals", elemBefore: () => <BiMenuAltLeft name="inbox" />, }, { key: uuidv4(), title: "Desserts", itemId: "/dish-type/desserts", elemBefore: () => <BiMenuAltLeft name="inbox" />, }, { key: uuidv4(), title: "Drinks", itemId: "/dish-type/drinks", elemBefore: () => <BiMenuAltLeft name="inbox" />, } ] }, { key: uuidv4(), title: 'Healthy Foods', itemId: '/healthy-meals/food', elemBefore: () => <BiMenuAltLeft name="inbox" />, } ]} />
5ce384b9f2812d179f4988ae6e297a231c8a3198
[ "JavaScript", "Markdown" ]
16
JavaScript
jorge-llanque/Recipe-Preparation-React
f267eb1cbc484d22d133be8d17d935a7b3082f45
d9420099f25838f5aca5de5de7345cd7d9212e1e
refs/heads/master
<file_sep>package TestDoctorPage; public class PageObjectLogin { public static void main(String[] args) { System.out.println("The prgram is started.."); LoginPage.validLogin("Tarique","Humayun"); System.out.println("The program end.."); } } <file_sep>package TestDoctorPage; import java.util.HashMap; import java.util.LinkedHashMap; public class HashMapDemo { public static void main(String[] args) { System.out.println("The hash map.."); //LinkedHashMap h = new LinkedHashMap(); HashMap h = new HashMap(); h.put("Chiranjivi", 7); h.put("Balaih", 6); h.put("Venkatesh", 2); h.put("Nagarjuna", 8); System.out.println(h); } }
11bb8b4cebfe249d993ef2d808e3f63f64504726
[ "Java" ]
2
Java
ibntarique/HealthCareRemote
6657ffdc182d8266e07ced2036bb3bd52fd7782d
3a517eda444c4202fc4fcc36829654bc630537d2
refs/heads/master
<file_sep>(function(){ const app = angular.module('rhapp'); app.controller('RhappController', function($scope, $filter, rhappService){ let vm = this; // vm.firstname = "Toto"; vm.applications = rhappService.getApplications(); let filter = $filter("addCivility")(vm.civilite, 2000); }); })();<file_sep>(function(){ const app = angular.module('rhapp'); app.factory('rhappService', function(rhappApplicationListConstant, prenomsFemininsConstantes, prenomsMasculinsConstantes){ let applications = rhappApplicationListConstant; let hommes = prenomsMasculinsConstantes; let femmes = prenomsFemininsConstantes; function getApplications(){ return applications; } function getHommes(){ return hommes; } function getFemmes(){ return femmes; } function addCivility(){ for (application of applications){ if (_.find(application, hommes)) application.civilite = "Homme"; else if(_.find(application, femmes)) application.civilite = "Femme"; } } return { getApplications, getHommes, getFemmes }; }); })();<file_sep># angularJs tp angular <file_sep>(function(){ const app = angular.module('rhapp'); app.constant('rhappApplicationListConstant', [{ firstname: "Pierre", lastname: "Martin", askedSalary: 55000 },{ firstname: "Jack", lastname: "Daniel", askedSalary: 9000 }]); app.constant('prenomsFemininsConstantes', [{ firstname: "Josianne", lastname: "Tabasco", askedSalary: 400000 },{ firstname: "Ginette", lastname: "<NAME>", askedSalary: 1200 }]); app.constant('prenomsMasculinsConstantes', [{ firstname: "Jean", lastname: "Jack", askedSalary: 1200368 },{ firstname: "Jackie", lastname: "Michel", askedSalary: 1 }]); })();<file_sep>(function(){ const app = angular.module('rhapp', []); })();
18391c1d45418110cf1c8119e76ffc17ca73535b
[ "JavaScript", "Markdown" ]
5
JavaScript
developaspeur/angularJs
a4c48d2b12417c5ee5dc16f7ece5fe74f56ac848
0ba76dd7b6c3976c7c619d5ceb28236a2f4aa59a
refs/heads/main
<file_sep># Howdy Hack 2021 ## Team Members A picture of our team: ![241961639_386473156421657_8259089015619180550_n](https://user-images.githubusercontent.com/24601461/132996435-924228ad-d089-417f-baf1-65c02f9bc1fd.png) <NAME>, Phu (<NAME>, <NAME>, <NAME>. ## Summary Our project is called "Mello." which is a play on the emotion "mellow" and "melody", and we just thought that the period at the end looks cool. This project uses the openCV library in Python for the back-end data processing, React.js for the front-end, web-cam access, and API calls, and the Spotify API to browse a song. The basic functionality of this is using a facial expression recognition model to analyze a user's expression and playing an song that fits their mood. ## Running the Program To run the program, first pull the reposity using your favorite environment (strongly recommend a virtual one): ### Front End 1. Open a terminal 2. `cd frontend` to navigate to the front end folder 3. `npm install` to install the required modules 4. `npm start` to initiate the front end once the install is completed. ### Back End 1. Open a new terminal 2. `cd backend` to the back end folder 3. `pip install -r requirements.txt` to install the required dependencies 4. `cd server_fer` to navigate to the server_fer folder 5. `python manage.py runserver` to initiate the back end server. ## Reference We would like to give a very special thank to <NAME>, who made all of this possible. Your pretrained model is goat 🐐. Here is his repo: https://github.com/justinshenk/fer <file_sep>absl-py==0.13.0 asgiref==3.4.1 astunparse==1.6.3 autopep8==1.5.7 cachetools==4.2.2 certifi==2021.5.30 charset-normalizer==2.0.4 clang==5.0 cycler==0.10.0 Django==3.2.7 django-cors-headers==3.8.0 djangorestframework==3.12.4 fer==21.0.3 flatbuffers==1.12 gast==0.4.0 google-auth==1.35.0 google-auth-oauthlib==0.4.6 google-pasta==0.2.0 grpcio==1.40.0 h5py==3.1.0 idna==3.2 keras==2.6.0 keras-nightly==2.5.0.dev2021032900 Keras-Preprocessing==1.1.2 kiwisolver==1.3.2 Markdown==3.3.4 matplotlib==3.4.3 mtcnn==0.1.1 numpy==1.19.5 oauthlib==3.1.1 opencv-contrib-python==4.5.3.56 opencv-python==4.5.3.56 opt-einsum==3.3.0 pandas==1.3.2 Pillow==8.3.2 protobuf==3.17.3 pyasn1==0.4.8 pyasn1-modules==0.2.8 pycodestyle==2.7.0 pyparsing==2.4.7 python-dateutil==2.8.2 pytz==2021.1 PyYAML==5.4.1 requests==2.26.0 requests-oauthlib==1.3.0 rsa==4.7.2 scipy==1.7.1 six==1.15.0 sqlparse==0.4.2 tensorboard==2.6.0 tensorboard-data-server==0.6.1 tensorboard-plugin-wit==1.8.0 tensorflow==2.6.0 tensorflow-estimator==2.6.0 termcolor==1.1.0 toml==0.10.2 typing-extensions==3.7.4.3 urllib3==1.26.6 Werkzeug==2.0.1 wrapt==1.12.1 <file_sep>import cv2 from fer import FER img = cv2.imread("/Users/anhnguyen/Data/HowdyHack2021/test-images/0.jpg") detector = FER(mtcnn=True) result = detector.top_emotion(img) print(result) <file_sep>import React, { useRef, useState, useEffect } from "react"; import Button from "@material-ui/core/Button"; import Webcam from "react-webcam"; import axios from "axios"; import "./App.css"; import GitHubIcon from "@material-ui/icons/GitHub"; import SpotifyPlayer from "react-spotify-player"; // import SpotifyPlayer from "react-spotify-web-playback"; const access_token = "<KEY>"; const App = () => { const [buttonStatus, setButton] = useState(false); const [mood, setMood] = useState(""); const webcamRef = React.useRef(null); const [imgSrc, setimgSrc] = useState(null); const allMood = [ "sad", "angry", "fear", "happy", "disgust", "neutral", "surprise", ]; const allGerne = []; const allMinDanceability = [0.35, 0.63, 0.2, 0.64, 0.21, 0.29, 1]; const allMaxDanceability = [0.5, 0.85, 0.45, 0.8, 0.4, 0.4, 1]; const allMinEnergy = [0.2, 0.5, 0.0, 0.65, 0.7, 0.0, 1]; const allMaxEnergy = [0.6, 1, 0.2, 1.0, 0.9, 0.6, 1]; const allMinLoudness = [-10.0, -10, -40.0, -10.0, -10, -25, 1]; const allMaxLoudness = [0.0, 0.0, -15.0, 0.0, 0.0, -5, 1]; const allMinValence = [0.1, 0.25, 0.0, 0.7, 0.1, 0.0, 1]; const allMaxValence = [0.5, 0.5, 0.5, 1.0, 0.4, 0.4, 1]; const allMinTempo = [50, 80, 90, 90, 80, 60, 1]; const allMaxTempo = [200, 150, 180, 180, 170, 200, 1]; const minPopularity = 0.0; const maxPopularity = 1; const [moodID, setMoodID] = useState(0); const [suggestSong, setSuggestSong] = useState([]); const [market, setMarket] = useState("UK"); const [gernes, setGernes] = useState(""); const [minDanceability, setMinDanceability] = useState(0); const [minEnergy, setMinEnergy] = useState(0); const [minLoudness, setMinLoudness] = useState(-50); const [minValence, setMinValence] = useState(0); const [minTempo, setMinTempo] = useState(0); const capture = React.useCallback(() => { const imageSrc = webcamRef.current.getScreenshot(); setButton(true); setimgSrc(imageSrc); }, [webcamRef, setimgSrc]); const sendData = async () => { let data = JSON.stringify({ title: "test", content: imgSrc, }); let url = "http://localhost:8000/ferapp/posts/create/"; let headers = { "Content-Type": "application/json", Accept: "application/json", }; let result = await axios .post(url, data, { headers }) .then((result) => result.data); setMood(result); setButton(false); }; const getInfoPlaceHolder = async () => { setMarket("US"); setGernes("country"); setMoodID(allMood.findIndex((element) => (element = mood))); // fix this later setMinDanceability(allMinDanceability[moodID]); setMinEnergy(allMinEnergy[moodID]); setMinLoudness(allMinLoudness[moodID]); setMinValence(allMinValence[moodID]); setMinTempo(allMinTempo[moodID]); }; const getSuggestSong = async () => { let url = "https://api.spotify.com/v1/recommendations?limit=1&market=" + market + "&seed_artists=4NHQUGzhtTLFvgF5SZesLK&seed_genres=" + gernes + "&seed_tracks=0c6xIDDpzE81m2q797ordA" + "&min_danceability=" + minDanceability + "&min_energy=" + minEnergy + "&min_loudness=" + minLoudness + "&min_popularity=" + minPopularity + "&min_tempo=" + minTempo + "&min_valence=" + minValence; let result = await axios .get(url, { headers: { Authorization: `Bearer ${access_token}`, "Content-Type": "application/json", Accept: "application/json", }, }) .then((res) => res.data.tracks); console.log("result", result); setSuggestSong(result); }; useEffect(() => { if (!(imgSrc === null)) { sendData(imgSrc); } if (!(mood === "")) { console.log("mood:", mood); getInfoPlaceHolder(); if (minTempo !== 0) { getSuggestSong(); } } }, [ imgSrc, mood, minDanceability, minEnergy, minLoudness, minPopularity, minTempo, minValence, ]); return ( <div style={{ alignItems: "center", textAlign: "center" }}> <h1>mello.</h1> <div style={{ display: "flex", flexDirection: "row", alignItems: "center", textAlign: "center", }} > <div style={{ width: "50%", justifyContent: "center", alignItems: "center", }} > <div style={{ justifyContent: "center", alignItems: "center", textAlign: "center", }} > <Webcam audio={false} ref={webcamRef} screenshotFormat="image/png" style={{ width: "45%", height: "40%", display: "flex", margin: "auto", marginBottom: "5px", flexWrap: "wrap", justifyContent: "center", border: "2px solid", borderColor: "#312545", borderRadius: "10px", transform: "rotateY(180deg)", }} /> </div> <div style={{ justifyContent: "center", alignItems: "center", }} > <Button disabled={buttonStatus} variant="contained" color="secondary" onClick={capture} style={{ display: "flex", margin: "auto", marginBottom: "5px", width: 300, flexWrap: "wrap", justifyContent: "center", }} > Take photo </Button> </div> {imgSrc && ( <img src={imgSrc} style={{ borderRadius: "10px", border: "2px solid", width: "45%", height: "40%", display: "flex", margin: "auto", flexWrap: "wrap", justifyContent: "center", borderColor: "#312545", transform: "rotateY(180deg)", }} alt="face capture" /> )} </div> <div style={{ width: "50%", justifyContent: "center", alignItems: "center", }} > <div> <h1>{mood === "" ? "Hello..." : mood}</h1> </div> {suggestSong.length !== 0 ? ( mood === "surprise" ? ( <div> <SpotifyPlayer uri="spotify:track:4cOdK2wGLETKBW3PvgPWqT" width="100%" view="coverart" theme="black" /> </div> ) : ( <div> <SpotifyPlayer uri={suggestSong[0].uri} width="100%" view="coverart" theme="black" /> </div> ) ) : ( <div> <SpotifyPlayer uri="spotify:track:0mHyWYXmmCB9iQyK18m3FQ" width="100%" view="coverart" theme="black" /> </div> )} </div> <a href="https://github.com/fool1280/howdy-hack-2021"> <GitHubIcon style={{ margin: "12px", position: "fixed", bottom: "0px", right: "0px", color: "whitesmoke", }} />{" "} </a> </div> </div> ); }; export default App; <file_sep>from .serializers import PostSerializer from .models import Post from rest_framework.views import APIView from rest_framework.parsers import JSONParser from rest_framework.response import Response from rest_framework import status import cv2 import os import base64 import numpy as np from fer import FER # Create your views here. class PostView(APIView): parser_classes = [JSONParser] def get(self, request, *args, **kwargs): posts = Post.objects.all() serializer = PostSerializer(posts, many=True) return Response(serializer.data) class PostCreate(APIView): parser_classes = [JSONParser] def post(self, request, *args, **kwargs): posts_serializer = PostSerializer(data=request.data) if posts_serializer.is_valid(): posts_serializer.save() encoded_string = posts_serializer.data['content'].split(',')[1] decoded_data = base64.b64decode(encoded_string) np_data = np.frombuffer(decoded_data, np.uint8) img = cv2.imdecode(np_data, cv2.IMREAD_UNCHANGED) output_image = cv2.imwrite(os.getcwd() + "test.jpg", img) image_load = cv2.imread(os.getcwd() + "test.jpg") detector = FER(mtcnn=True) result = detector.top_emotion(image_load) return Response(result[0], status=status.HTTP_201_CREATED) else: print('error', posts_serializer.errors) return Response(posts_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
c397942d569f2662320a3bf58dd6734d0788b475
[ "Markdown", "Python", "Text", "JavaScript" ]
5
Markdown
fool1280/howdy-hack-2021
4de9ce2312d696e2a83289af8ff0189c4fc480a8
8d5c4ed2a16cb7dcc4b242ae704ef089c921e7d6
refs/heads/master
<file_sep>FROM python:latest ARG PORT ENV SERVER_PORT=$PORT COPY server.py / RUN mkdir /serverdata ENTRYPOINT python3 server.py $SERVER_PORT<file_sep># building image docker build server -t lab1_image --build-arg "PORT=$1" # creating volume docker volume create lab1_volume # run container with port $1 docker run -it --rm -p $1:$1 -d -v lab1_volume:/serverdata --name server lab1_image $SHELL<file_sep># qa_assignment_1 To run a server: ```shell cd src sh server.sh <PORT> ``` It will run this server in a docker container. To browse this' server output us `telnet` utility: ```shell telnet 127.0.0.1 <PORT> ``` You will see a contents of file and checksum. To quit from listening press `control + ]`. Then iput `quit` to exit from telnet.<file_sep>import sys import hashlib import random import socket serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) HOST = socket.gethostname() DNS_ADDR = socket.gethostbyname(HOST) PORT = int(str(sys.argv[len(sys.argv) - 1])) serv.bind((DNS_ADDR, PORT)) serv.listen(5) FILEPATH = "/serverdata/file" ascii_lower = 'abcdefghijklmnopqrstuvwxyz' ascii_upper = ascii_lower.upper() digits= '0123456789' def checksum(path): md5 = hashlib.md5() with open(path, "rb") as file_: content = file_.read() md5.update(content) return md5.hexdigest() def create_file(path): ran = str(''.join(random.choices(ascii_lower + ascii_upper + digits, k = 1024))) with open(path, "w+") as file: file.write(ran) create_file(FILEPATH) digest = checksum(FILEPATH) f = open(FILEPATH, "r") data = f.read() while True: connection, address = serv.accept() print(f"connection from {address}") connection.send("\nFile data:\n\n".encode("utf-8")) connection.send(data.encode("utf-8")) connection.send("\n\nChecksum:\n\n".encode("utf-8")) connection.send(digest.encode("utf-8")) f.close()
5bac22b96ecbf4806dbe4fc2a2a1a8da291c5c4b
[ "Markdown", "Python", "Dockerfile", "Shell" ]
4
Dockerfile
DeLion13/qa_assignment1_shapovalov
ee1b73bd0ea324fba235041e402c9489859de1a2
616793e3b4b30536445d615e6b7bae8ae2bed224
refs/heads/master
<repo_name>agilly/b-fast<file_sep>/helper.h #include <stdlib.h> using namespace std; template <typename T> void info_w(T t) { std::cerr << t << std::endl ; } template<typename T, typename... Args> void info_w(T t, Args... args) // recursive variadic function { std::cerr << t << " " ; info_w(args...) ; } void info_w(){ std::cerr << std::endl; } template<typename T, typename... Args> void info(T t, Args... args) // recursive variadic function { std::cerr << "INFO:\t"<< t ; info_w(args...) ; } template <typename T> void error_w(T t) { std::cerr << t << std::endl ; exit(1); } template<typename T, typename... Args> void error_w(T t, Args... args) // recursive variadic function { std::cerr << t << " " ; error_w(args...) ; } void error_w(){ std::cerr << endl; exit(1); } template<typename T, typename... Args> void error(T t, Args... args) // recursive variadic function { std::cerr << "ERROR:\t"<< t ; error_w(args...) ; } unsigned long long choose(unsigned long long n, unsigned long long k) { // stolen from Knuth if (k > n) { return 0; } unsigned long long r = 1; for (unsigned long long d = 1; d <= k; ++d) { r *= n--; r /= d; } return r; }<file_sep>/bgen_parser.h #include <iostream> #include <fstream> #include <string> using namespace std; enum BGEN_RETURN_CODE { E_OK = 0, E_WRITE_ERROR = -1 }; struct file_info{ file_info(){} file_info(uint32_t header_offset, uint32_t size_of_header, uint32_t num_variants, uint32_t num_samples, string magic, int freedata_size, string freedata, uint32_t flags, uint32_t empty_space){ this->header_offset=header_offset; this->size_of_header=size_of_header; this->num_variants=num_variants; this->num_samples=num_samples; this->magic=magic; this->freedata_size=freedata_size; this->freedata=freedata; this->flags=flags; this->empty_space=empty_space; this->compression=(flags & 3); this->bgen_version=((flags & 60)>>2)-1; } uint32_t header_offset; uint32_t size_of_header; uint32_t num_variants; uint32_t num_samples; string magic; int freedata_size; string freedata; uint32_t flags; unsigned short int compression; bool bgen_version; bool sample_info_included; uint32_t empty_space; }; file_info parse_header(ifstream & bgenfile, bool VERBOSE){ uint32_t header_offset; uint32_t size_of_header; uint32_t num_variants; uint32_t num_samples; bgenfile.read(reinterpret_cast<char *>(&header_offset), sizeof(header_offset)); bgenfile.read(reinterpret_cast<char *>(&size_of_header), sizeof(size_of_header)); bgenfile.read(reinterpret_cast<char *>(&num_variants), sizeof(num_variants)); bgenfile.read(reinterpret_cast<char *>(&num_samples), sizeof(num_samples)); char magic[4]; bgenfile.read(magic, 4); if(VERBOSE){info("Offset is: ",header_offset);} if(VERBOSE){info("Size of header is: ", size_of_header);} if(VERBOSE){info("Number of variants: ", num_variants);} if(VERBOSE){info("Number of samples: ", num_samples);} if(VERBOSE){info("Magic number: ", magic);} int freedata_size=0; string freedata_s; if(size_of_header-20>0){ freedata_size=size_of_header-20; char freedata[freedata_size]; bgenfile.read(freedata, freedata_size); if(VERBOSE){info("Free data detected: ", freedata);} freedata_s=std::string(freedata); } uint32_t flags; bgenfile.read(reinterpret_cast<char *>(&flags), sizeof(flags)); switch(flags & 3){ case 0 : if(VERBOSE){info("SNP Block probability data is not compressed.");} break; case 1 : if(VERBOSE){info("SNP Block probability data compressed using zlib.");} break; case 2 : if(VERBOSE){info("SNP Block probability data compressed using zstandard.");} break; } switch((flags & 60)>>2){ case 1: if(VERBOSE){info("Bgen v1.1 detected.");} break; case 2: if(VERBOSE){info("Bgen v1.2 detected.");} break; } string hamlet=""; if(flags>>31==0){ hamlet="not"; } if(VERBOSE){info("Sample info is ", hamlet, "included in this file.");} if(hamlet!="not"){ error("Sample info is included (Not supported)."); } uint32_t skip=header_offset-size_of_header; if(VERBOSE){info("Skipping ", skip, "bytes.");} bgenfile.ignore(skip); file_info bgen_file_info(header_offset, size_of_header, num_variants, num_samples, std::string(magic), freedata_size, freedata_s, flags, skip); return(bgen_file_info); } BGEN_RETURN_CODE write_header(ofstream & bgenfile, file_info f_info){ // TBD: the header data needs to be calculated at the end as it contains numbers of variants and samples // TBD: // Write basic header try{ bgenfile.write((char *) &(f_info.header_offset), 4); bgenfile.write((char *) &(f_info.size_of_header), 4); bgenfile.write((char *) &(f_info.num_variants), 4); bgenfile.write((char *) &(f_info.num_samples), 4); bgenfile.write((char *) &(f_info.magic), 4); bgenfile.write((char *) &(f_info.freedata), f_info.freedata_size); bgenfile.write((char *) &(f_info.flags), 4); } catch (...) { return(E_WRITE_ERROR); } // If sample info is present, write sampe identifier block bgenfile.flush(); return(E_OK); }<file_sep>/bgenfun.cpp #include <stdlib.h> #include <iostream> #include <fstream> #include <string> #include <zlib.h> #include <cstring> #include "helper.h" #include "bgen_parser.h" using std::string; using namespace std; int main(int argc, char* argv[]) { bool VERBOSE=0; ifstream bgenfile("/lustre/scratch115/projects/ukbiobank/FullRelease/Imputed/001/Stripe/ukb_imp_chr22_v2.bgen", ios::in | ios::binary); file_info bgen_finfo; bgen_finfo=parse_header(bgenfile, 0); ofstream out("/nfs/users/nfs_a/ag15/lol", ios :: out | ios :: binary); write_header(out, bgen_finfo); bgenfile.close(); exit(0); unsigned short id_len; string id; string rsid; string chr; uint32_t pos; while(!bgenfile.eof()){ bgenfile.read(reinterpret_cast<char *>(&id_len), sizeof(id_len)); if(VERBOSE){info("First variant ID length: ", id_len);} char varid[id_len]; bgenfile.read(varid, id_len); id=std::string(varid); if(VERBOSE){info("Variant ID: ", id);} bgenfile.read(reinterpret_cast<char *>(&id_len), sizeof(id_len)); if(VERBOSE){info("First variant rsID length: ", id_len);} char varrs[id_len]; bgenfile.read(varrs, id_len); rsid=std::string(varrs); if(VERBOSE){info("Variant rsID: ", rsid);} bgenfile.read(reinterpret_cast<char *>(&id_len), sizeof(id_len)); if(VERBOSE){info("First variant chr length: ", id_len);} char varchr[id_len]; bgenfile.read(varchr, id_len); chr=std::string(varchr); if(VERBOSE){info("Variant chr: ", chr);} bgenfile.read(reinterpret_cast<char *>(&pos), sizeof(pos)); if(VERBOSE){info("Variant position: ", pos);} //alleles unsigned short num_alleles; bgenfile.read(reinterpret_cast<char *>(&num_alleles), sizeof(num_alleles)); if(VERBOSE){info("Variant has ", num_alleles, "alleles");} string alleles[num_alleles]; for(int i=0;i<num_alleles;i++){ uint32_t len_allele; bgenfile.read(reinterpret_cast<char *>(&len_allele), sizeof(len_allele)); char allele_c[len_allele]; bgenfile.read(allele_c, len_allele); string allele; alleles[i] = std::string(allele_c); if(VERBOSE){info("\t allele ", allele, "(size ", len_allele, ")");} } //genotypes uint32_t len_gblock; // compressed size uint32_t len_ugblock; // uncompressed size bgenfile.read(reinterpret_cast<char *>(&len_gblock), sizeof(len_gblock)); bgenfile.read(reinterpret_cast<char *>(&len_ugblock), sizeof(len_ugblock)); long unsigned int len_ugblock_l=(long unsigned int)len_ugblock; long unsigned int len_gblock_l=(long unsigned int)len_gblock; char gblock[len_gblock-4]; // read compressed block bgenfile.read(gblock, len_gblock-4); uint8_t dest[len_ugblock]; int unzip_code; unsigned char* gblock_u=reinterpret_cast<unsigned char*>(gblock); if(VERBOSE){info("Compressed genotype block of size: ", len_gblock_l);} if(VERBOSE){info("Uncompressed genotype block size: ", len_ugblock_l);} unzip_code=uncompress(dest, &len_ugblock_l, gblock_u, len_gblock_l); if(VERBOSE){info("Decompress returned ",unzip_code);} uint8_t* temp=&dest[0]; uint8_t snum[4]; memcpy(&snum, temp, 4); uint32_t ns=*reinterpret_cast<uint32_t*>(snum); if(VERBOSE){info("Number of samples in this variant: ",ns);} temp+=4; uint8_t numall_p[2]; memcpy(numall_p, temp, 2); int numall=*reinterpret_cast<uint16_t*>(numall_p); if(VERBOSE){info("Number of alleles for this variant: ",numall);} temp+=2; uint8_t maxpl[1]; memcpy(maxpl, temp, 1); if(VERBOSE){info("Min ploidy for this variant: ",(int)*maxpl);} temp+=1; uint8_t minpl[1]; memcpy(minpl, temp, 1); if(VERBOSE){info("Max ploidy for this variant: ",(int)*minpl);} // reading ploidy and missingness information temp+=1; uint8_t ploidy[ns]; memcpy(ploidy, temp, ns); // reading phasedness temp+=ns; uint8_t phased[1]; memcpy(phased, temp, 1); if(VERBOSE){info("Data is phased: ",(int)*phased);} // reading number of bits per genotype temp+=1; uint8_t nbits[1]; memcpy(nbits, temp, 1); if(VERBOSE){info("Data is stored in ",(int)*nbits, "bits.");} float flnb=(float) (2<< nbits[0] -1); temp+=1; // probabilities are stored depending on ploidy and allele number per sample. // they cannot be read in one go. // genotype assignment loop bool missingness[ns]; unsigned long int totmiss=0; for(int i = 0; i < ns; ++i){ uint8_t prob; missingness[i]=ploidy[i] & 128; totmiss+=missingness[i]; ploidy[i] <<= 1; ploidy[i] >>= 1; int numprob=(ploidy[i]+numall-1)*choose(numall-1, numall-1)-1; // read genotype // the following assumes that probabilities are always stored in 8-bit rep, i.e. nbits==8 always uint8_t probs[numprob]; memcpy(probs, temp, numprob); temp+=numprob; float sump=1; float dosage=0; for (unsigned int j=0; j<numprob; j++){ float flpr=(float) probs[j]; flpr=flpr/flnb; sump-=flpr; dosage+=(float)j*flpr; //cout << flpr<< ":"; } dosage+=2*sump; //cout << dosage <<" "; } //cout << "\n"; if(VERBOSE){info("Total ploidy is ", ploidy);} // float fns=(float)ns*2; // float fpl=(float)ploidy; // float fms=(float)totmiss; // std::cout << id<<"\t"<<rsid<<"\t" << (int)*minpl <<"\t" <<fns<<"\t"<< fpl<<"\t"<< fms <<"\t"<<fpl/(fns-totmiss) <<"\n"; } } // char zipped_block_c[len_gblock]; // bgenfile.read(zipped_block_c, len_gblock); // string zipped_block; // zipped_block=std::string(zipped_block_c); // info(uncompress(zipped_block_c, 0)); <file_sep>/README.md # b-fast A basic C++ library to speedily parse (and hopefully one day write) BGEN files. This was started mainly out of curiosity and is currently in an unfinished state. Therefore, it should be considered as being devoid of practical purpose and has no ambition of becoming a real tool whatsoever. `bgen_parser.h` currently exposes: * `file_info parse_header(ifstream & bgenfile, bool VERBOSE)`, which reads the header of a BGEN file open in an `ifstream` passed as argument. This is returned as a `file_info` struct. * `BGEN_RETURN_CODE write_header(ofstream & bgenfile, file_info f_info)`, which writes a header contained in a `file_info` struct to an ofstream. Currently unfinished. `bgenfun.cpp` contains a few lines of code to read and parse genotype information. `helper.h` contains the `info(...)` and `error(...)` methods, as well as the combinatorics `choose(k,n)` function.
f4be6a1290da386fd8db79a4301830c9dc6391ec
[ "Markdown", "C++" ]
4
C++
agilly/b-fast
a8fbc72d2a93f75efd02c40f2494b09bfbe197ec
6892898a2e4803dbd1c1275efeb274ed8b060cc3
refs/heads/master
<file_sep>curl 'http://127.0.0.1/api/expenses/update' \ -H 'authority: bosspy-test.xiaojiaoyu100.com' \ -H 'sec-ch-ua: "Google Chrome";v="93", " Not;A Brand";v="99", "Chromium";v="93"' \ -H 'x-version: 3.6.0-alpha.6' \ -H 'sec-ch-ua-mobile: ?0' \ -H 'authorization: Bearer <KEY>kwXm8jmGAo4S-Di7JM30zEfUGeg' \ -H 'content-type: application/json;charset=UTF-8' \ -H 'accept: application/json, text/plain, */*' \ -H 'user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36' \ -H 'x-source: BOSS' \ -H 'sec-ch-ua-platform: "Windows"' \ -H 'origin: https://bosspy-test.xiaojiaoyu100.com' \ -H 'sec-fetch-site: same-origin' \ -H 'sec-fetch-mode: cors' \ -H 'sec-fetch-dest: empty' \ -H 'referer: https://bosspy-test.xiaojiaoyu100.com/console/student-management/list' \ -H 'accept-language: zh-CN,zh;q=0.9,en;q=0.8' \ -H 'cookie: gr_user_id=2f15527c-7623-4c88-b0e4-6ad85a8437a5; grwng_uid=f645a3cf-361a-417d-8c58-23fa4512a08e; 80cc4affb69c1130_gr_last_sent_cs1=X55427; bd183afb0d5cb45c_gr_last_sent_cs1=X55427; 80cc4affb69c1130_gr_cs1=X55427; aace305c8b58ec2e_gr_last_sent_cs1=linyouxun1; aace305c8b58ec2e_gr_session_id=d3fe9e0c-a8d6-42a5-ad05-b858ebff588c; aace305c8b58ec2e_gr_last_sent_sid_with_cs1=d3fe9e0c-a8d6-42a5-ad05-b858ebff588c; aace305c8b58ec2e_gr_session_id_d3fe9e0c-a8d6-42a5-ad05-b858ebff588c=true; sessionac-test=MTYzMTQ0MTk0M3xEdi1CQkFFQ180SUFBUkFCRUFBQVFQLUNBQUVHYzNSeWFXNW5EQkFBRG5WelpYSkpSQzFVWlhOMGFXNW5Cbk4wY21sdVp3d2FBQmcxWlRaaU1qSXhZakk1WXpaallqQXdNREZtTmpOaFpEUT18BQy1_8Q01YcOdoShSv72l6r8wr8in7IK6y024rWHGME=; session_ac_ex_test=0; aace305c8b58ec2e_gr_cs1=linyouxun1' \ --data-raw '{"id":"2","accountId":"2","type":"购物","useTime":"2021-08-01 12:22","remark":"","money":2300}' \ --compressed<file_sep>function toSqlString(params, join = " and ") { return Object.keys(params) .map((ele) => `${ele} = ?`) .join(join); } function insert(tableName, params = {}) { return `INSERT INTO ${tableName}(${Object.keys(params).join( ", " )}) VALUES(${Object.keys(params) .map((_) => "?") .join(", ")})`; } function query(tableName, params = {}) { var extra = ""; if (Object.keys(params).length > 0) { extra = "where " + toSqlString(params); } return `SELECT * FROM ${tableName} ${extra || ""}`; } function update(tableName, params = {}, where = {}) { var set = ""; if (Object.keys(params).length > 0) { set = "SET " + toSqlString(params, ", "); } var whereStr = ""; if (Object.keys(where).length > 0) { whereStr = "WHERE " + toSqlString(where); } return `UPDATE ${tableName} ${set || ""} ${whereStr || ""}`; } function deleteSql(tableName, params = {}) { var extra = ""; if (Object.keys(params).length > 0) { extra = "where " + toSqlString(params); } return `DELETE FROM ${tableName} ${extra || ""}`; } module.exports = { insert, query, update, delete: deleteSql, }; <file_sep>curl 'http://127.0.0.1/api/expenses/list' \ -H 'Connection: keep-alive' \ -H 'X-WX-SERVICE: account' \ -H 'X-WECHAT-CONTAINER-PATH: /api/expenses/list' \ -H 'X-WECHAT-CALL-ID: 0.24993343300632964_1631515067577' \ -H 'User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.3 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1 wechatdevtools/1.05.2108130 MicroMessenger/8.0.5 Language/zh_CN webview/' \ -H 'X-WECHAT-ENV: account-8gjt64jg11892b13' \ -H 'content-type: application/json' \ -H 'Accept: */*' \ -H 'Sec-Fetch-Site: cross-site' \ -H 'Sec-Fetch-Mode: cors' \ -H 'Sec-Fetch-Dest: empty' \ -H 'Referer: https://servicewechat.com/wx9489128007aafc1a/devtools/page-frame.html' \ --data-binary '{"useTime":"2021-08-01"}' \ --compressed<file_sep>var express = require("express"); var router = express.Router(); var db = require("../config/db"); //引入db var sql = require("../config/sql/account"); router.post("/account/list", function (req, res, next) { db.query(sql.query(), function (err, rows) { if (err) { console.log(err); res.send({ code: 400, msg: "未知错误", data: [] }); } res.send({ code: 200, data: rows }); }); }); router.post("/account/add", function (req, res, next) { const { name = "", openid = "", password = "" } = req.body; db.queryArgs(sql.query({ openid }), [openid], function (err, rows) { if (err) { console.log(err); res.send({ code: 400, msg: "未知错误" }); } if (rows.length > 0) { res.send({ code: 400, msg: "已绑定openId" }); } else { db.queryArgs( sql.insert({ name, openid, password }), [name, openid, password], function (err, rows) { if (err) { console.log(err); res.send({ code: 400, msg: "新增数据失败", data: { name, openid, password }, }); return; } res.send({ code: 200, msg: "新增数据成功", data: { name, openid, password }, }); } ); } }); }); router.post("/account/update", function (req, res, next) { const { name = "", openid = "", password = "", id = "" } = req.body; if (!id) { res.send({ code: 400, msg: "id未填写" }); } const params = { name, openid, password, updateTime: Date.now() }; db.queryArgs(sql.query({ id }), [id], function (err, rows) { if (err) { console.log(err); res.send({ code: 400, msg: "未知错误" }); } if (rows.length > 0) { db.queryArgs( sql.update(params, { id }), [name, openid, password, new Date(), id], function (err, rows) { console.log(rows); if (err) { console.log(err); res.send({ code: 400, msg: "更新数据失败", data: params, }); return; } res.send({ code: 200, msg: "更新数据成功", data: params, }); } ); } else { res.send({ code: 400, msg: "id不存在" }); } }); }); router.post("/account/delete", function (req, res, next) { const { id = "" } = req.body; if (!id) { res.send({ code: 400, msg: "id未填写" }); } const params = { id }; db.queryArgs(sql.query(params), Object.values(params), function (err, rows) { if (err) { console.log(err); res.send({ code: 400, msg: "未知错误" }); } if (rows.length > 0) { db.queryArgs( sql.delete(params), Object.values(params), function (err, rows) { console.log(rows); if (err) { console.log(err); res.send({ code: 400, msg: "删除数据失败", data: params, }); return; } res.send({ code: 200, msg: "删除数据成功", data: params, }); } ); } else { res.send({ code: 400, msg: "id不存在" }); } }); }); module.exports = router;
03ddb8410c58bbddaf25d621bd72334fb8f36d19
[ "JavaScript", "Shell" ]
4
Shell
linyouxun/wx-account
d5e59fcdd97e29910d65890088e00f1993c00d84
76b9a189ba7bb29679f67807dfbcca7ac35bd30b
refs/heads/master
<repo_name>yemutex/bach<file_sep>/linked_list/reverse_test.py from nose.tools import * import reverse def test_reverse(): # Linked list is None assert_raises(TypeError, reverse.reverse, None) # Linked list has 1 item item = reverse.Node(1, None) h = reverse.reverse(item) assert_equal(1, h.value) # Linked list has 2 items item2 = reverse.Node(2, None) item1 = reverse.Node(1, item2) h = reverse.reverse(item1) assert_equal(2, h.value) assert_equal(1, h.next.value) # Linked list has 5 items item5 = reverse.Node(5, None) item4 = reverse.Node(4, item5) item3 = reverse.Node(3, item4) item2 = reverse.Node(2, item3) item1 = reverse.Node(1, item2) h = reverse.reverse(item1) assert_equal(5, h.value) assert_equal(4, h.next.value) assert_equal(3, h.next.next.value) assert_equal(2, h.next.next.next.value) assert_equal(1, h.next.next.next.next.value) assert_equal(None, h.next.next.next.next.next) <file_sep>/leetcode/323.connected_components.py import unittest class Solution(object): def solve(self, n, edges): vertices = set(range(n)) components = 0 neighbors = {i: [] for i in range(n)} for v1, v2 in edges: neighbors[v1].append(v2) neighbors[v2].append(v1) stack = [] visited = set() while len(vertices) > 0: vertex = vertices.pop() stack.append(vertex) visited.add(vertex) while len(stack) > 0: node = stack.pop() for item in neighbors[node]: if item not in visited: stack.append(item) if item in vertices: vertices.remove(item) visited.add(node) components += 1 return components class SolutionTestCase(unittest.TestCase): def test_example1(self): edges = [[0, 1], [1, 2], [3, 4]] self.assertEqual(Solution().solve(5, edges), 2) def test_example2(self): edges = [[0, 1], [1, 2], [2, 3], [3, 4]] self.assertEqual(Solution().solve(5, edges), 1) if __name__ == '__main__': unittest.main() <file_sep>/leetcode/993.cousins_in_bst.js var d, p; /** *@param {TreeNode} root * @param {number} x * @param {number} y * @return {boolean} */ var isCousins = function(root, x, y) { find(root, x, 0, null); const xDepth = d; const xParent = p; find(root, y, 0, null); const yDepth = d; const yParent = p; return xDepth === yDepth && xParent !== yParent; }; function find(root, target, depth, parent) { if (!root) return false; if (root.val === target) { d = depth; p = parent; return; } find(root.left, target, depth+1, root); find(root.right, target, depth+1, root); } <file_sep>/leetcode/69.sqrtx.js /** * @param {number} x * @return {number} */ var mySqrt = function(x) { if (x < 2) return x; var lo = 0, hi = x - 1; while (lo <= hi) { let mid = Math.floor((lo + hi) / 2); if (mid*mid > x) { hi = mid - 1; } else if (mid*mid < x) { lo = mid + 1; } else { return mid; } } return hi; }; <file_sep>/leetcode/436.find_right_interval.js const assert = require('assert'); const _ = require('lodash'); function find(intervals, query) { var lo = 0, hi = intervals.length-1; while (lo <= hi) { let mid = Math.floor((lo + hi) / 2); if (query.end < intervals[mid].start) { hi = mid -1 ; } else if (query.end > intervals[mid].start) { lo = mid + 1; } else { return intervals[mid]; } } if (lo >= intervals.length) { return -1; } return intervals[lo]; } /** * @param {Interval[]} intervals * @return {number[]} */ var findRightInterval = function(intervals) { var result = Array(intervals.length).fill(null); var lookup = {}; // set up a map for original index lookup for (let i = 0; i < intervals.length; i++) { let key = `${intervals[i].start},${intervals[i].end}`; lookup[key] = i; } var sortedIntervals = _.sortBy(intervals, interval => { return interval.start; }); for (let i = 0; i < intervals.length; i++) { let interval = find(sortedIntervals, intervals[i]); let key = `${interval.start},${interval.end}`; result[i] = (interval === -1) ? -1 : lookup[key]; } return result; }; function Interval(start, end) { this.start = start; this.end = end; } var interval1 = new Interval(3, 4); var interval2 = new Interval(2, 3); var interval3 = new Interval(1, 2); console.log(findRightInterval([interval1, interval2, interval3])); <file_sep>/leetcode/6.zigzag.py import unittest class Solution(object): def solve(self, s, num_rows): if num_rows == 1: return s letters = [] for i in range(num_rows): letters.append([]) index = 0 zig = True # otherwise zag for value in s: letters[index].append(value) if zig: index += 1 if index == (num_rows-1): zig = False else: index -= 1 if index == 0: zig = True for i in range(num_rows): letters[i] = ''.join(letters[i]) return ''.join(letters) class SolutionTestCase(unittest.TestCase): def test_example(self): result = Solution().solve('PAYPALISHIRING', 3) self.assertEqual(result, 'PAHNAPLSIIGYIR') def test_one_row(self): result = Solution().solve('AB', 1) self.assertEqual(result, 'AB') if __name__ == '__main__': unittest.main() <file_sep>/linked_list/circular_spec.rb require_relative 'circular' describe "Tests for circular linked lists: " do it "should indicate when there is no loop" do a = Node.new b = Node.new c = Node.new a.next = b b.next = c c.next = nil Circular.has_circle?(a).should be_false end it "should work when the whole list is a loop" do a = Node.new b = Node.new c = Node.new a.next = b b.next = c c.next = a Circular.has_circle?(a).should be(a) end it "should work when the list has a loop" do a = Node.new b = Node.new c = Node.new d = Node.new e = Node.new a.next = b b.next = c c.next = d d.next = e e.next = c Circular.has_circle?(a).should be(c) end end <file_sep>/leetcode/594.longest_harmonious.js /** * @param {number[]} nums * @return {number} */ var findLHS = function(nums) { let h = {}; let count = 0; for (let num of nums) { if (h[num] === undefined) { h[num] = 1; } else { h[num]++; } } for (let key in h) { let tmp = h[key]; if (h[parseInt(key)+1]) { tmp += h[parseInt(key)+1]; if (tmp > count) { count = tmp; } } } return count; }; <file_sep>/leetcode/526.beautiful_arrangement.js const assert = require('assert'); const _ = require('underscore'); var countArrangement = function(n) { var counter = 0; var nums = _.range(1, n+1); function beautiful(value, index) { return (value % index === 0) || (index % value === 0); } function arrange(candidates, partial) { if (candidates.length === 0) { counter++; return; } else { for (var i = 0; i < candidates.length; i++) { if (beautiful(candidates[i], partial.length+1)) { var newCandidates = candidates.slice(); var newPartial = partial.slice(); newCandidates.splice(i, 1); newPartial.push(candidates[i]); arrange(newCandidates, newPartial); } } } } arrange(nums, []); return counter; }; assert.strictEqual(countArrangement(2), 2); assert.strictEqual(countArrangement(3), 3); <file_sep>/interview_cake/stock_price.py import unittest def get_max_profit(stock_prices): if not stock_prices or len(stock_prices) < 2: raise TypeError min_price = stock_prices[0] max_profit = stock_prices[1] - stock_prices[0] for index, price in enumerate(stock_prices): if index == 0: continue if price - min_price > max_profit: max_profit = price - min_price if price < min_price: min_price = price return max_profit class MaxProfitTestCase(unittest.TestCase): def test_example(self): prices = [10, 7, 5, 8, 11, 9] self.assertEqual(get_max_profit(prices), 6) def test_monotonically_decreasing(self): prices = [10, 9, 7, 6, 5, 2, 1] self.assertEqual(get_max_profit(prices), -1) def test_single_value(self): prices = [100] with self.assertRaises(TypeError): get_max_profit(prices) if __name__ == '__main__': unittest.main() <file_sep>/interview_cake/find_duplicate.py import unittest def find_duplicate(values): floor, ceiling = 1, max(values) while floor < ceiling: mid = (floor + (ceiling-floor)) / 2 lower_floor, lower_ceiling = floor, mid upper_floor, upper_ceiling = mid+1, ceiling lower_items = 0 for value in values: if value >= lower_floor and value <= lower_ceiling: lower_items += 1 if lower_items > (lower_ceiling + 1 - lower_floor): floor, ceiling = lower_floor, lower_ceiling else: floor, ceiling = upper_floor, upper_ceiling return floor class FindDuplicateTestCase(unittest.TestCase): def test(self): values = [8, 6, 3, 1, 2, 10, 5, 2, 9, 2, 7] self.assertEqual(find_duplicate(values), 2) if __name__ == '__main__': unittest.main() <file_sep>/leetcode/840.magic_squares.js const _ = require('lodash'); /** * @param {number[][]} grid * @return {number} */ var numMagicSquaresInside = function(grid) { if (grid.length < 3 || grid[0].length < 3) return 0; let result = 0; for (let i = 0; i < grid.length-2; i++) { for (let j = 0; j < grid[0].length-2; j++) { let square = [ grid[i][j], grid[i][j+1], grid[i][j+2], grid[i+1][j], grid[i+1][j+1], grid[i+1][j+2], grid[i+2][j], grid[i+2][j+1], grid[i+2][j+2], ]; if (magic(square)) result++; } } return result; function magic(s) { return (s[0] + s[1] + s[2]) === 15 && (s[3] + s[4] + s[5]) === 15 && (s[6] + s[7] + s[8]) === 15 && (s[0] + s[3] + s[6]) === 15 && (s[1] + s[4] + s[7]) === 15 && (s[2] + s[5] + s[8]) === 15 && (s[0] + s[4] + s[8]) === 15 && (s[2] + s[4] + s[6]) === 15 && _.isEqual(_.sortBy(s), [1, 2, 3, 4, 5, 6, 7, 8, 9]); } }; <file_sep>/leetcode/48.rotate_image.py import unittest class Solution(object): def solve(self, matrix): # clock-wise rotate # 1 2 3 7 8 9 7 4 1 # 4 5 6 -> 4 5 6 -> 8 5 2 # 7 8 9 1 2 3 9 6 3 matrix.reverse() for i in range(len(matrix)): for j in range(i): matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] class SolutionTestCase(unittest.TestCase): def test_example(self): m1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] r1 = [[7, 4, 1], [8, 5, 2], [9, 6, 3]] Solution().solve(m1) self.assertEqual(m1, r1) m2 = [[5, 1, 9, 11], [2, 4, 8, 10], [13, 3, 6, 7], [15, 14, 12, 16]] r2 = [[15, 13, 2, 5], [14, 3, 4, 1], [12, 6, 8, 9], [16, 7, 10, 11]] Solution().solve(m2) self.assertEqual(m2, r2) if __name__ == '__main__': unittest.main() <file_sep>/leetcode/101.js import { TreeNode } from './util.js'; import assert from 'assert'; import _ from 'lodash'; /** * @param {TreeNode} root * @return {boolean} */ var isSymmetric = function(root) { const left = []; const right = []; function traverse(node, depth, leftFirst) { if (!node) { if (leftFirst) { left.push([null, depth]); } else { right.push([null, depth]); } return; } if (leftFirst) { traverse(node.left, depth+1, true); left.push([node.val, depth]); traverse(node.right, depth+1, true); } else { traverse(node.right, depth+1, false); right.push([node.val, depth]); traverse(node.left, depth+1, false); } } traverse(root, 0, true); traverse(root, 0, false); return _.isEqual(left, right); }; // Tests const root1 = new TreeNode(1); root1.left = new TreeNode(2); root1.right = new TreeNode(2); root1.left.left = new TreeNode(3); root1.left.right = new TreeNode(4); root1.right.left = new TreeNode(4); root1.right.right = new TreeNode(3); assert(isSymmetric(root1)); const root2 = new TreeNode(1); root2.left = new TreeNode(2); root2.right = new TreeNode(2); root2.left.left = new TreeNode(2); root2.right.left = new TreeNode(2); assert(!isSymmetric(root2)); const root3 = new TreeNode(2); root3.left = new TreeNode(3); root3.right = new TreeNode(3); root3.left.left = new TreeNode(4); root3.left.right = new TreeNode(5); root3.right.right = new TreeNode(4); assert(!isSymmetric(root3)); <file_sep>/interview_cake/coin.py import unittest def making_change_recursive_helper(amount_remaining, denominations, current): if amount_remaining == 0: return 1 if amount_remaining < 0: return 0 if current == len(denominations): return 0 current_coin = denominations[current] count = 0 while amount_remaining >= 0: count += making_change_recursive_helper( amount_remaining, denominations, current+1) amount_remaining -= current_coin return count def making_change_recursive(amount, denominations): return making_change_recursive_helper(amount, denominations, 0) class Change: def __init__(self): self.memo = {} def __make_helper(self, amount_remaining, denominations, current): if amount_remaining == 0: return 1 if amount_remaining < 0: return 0 if current == len(denominations): return 0 current_coin = denominations[current] key = str((amount_remaining, current_coin)) if key in self.memo: return self.memo[key] else: count = 0 while amount_remaining >= 0: count += self.__make_helper( amount_remaining, denominations, current+1) amount_remaining -= current_coin self.memo[key] = count return count def make(self, amount, denominations): return self.__make_helper(amount, denominations, 0) class MakingChangeTestCase(unittest.TestCase): def test_example_recursive(self): self.assertEqual(making_change_recursive(4, [1, 2, 3]), 4) def test_example_memoization(self): self.assertEqual(Change().make(4, [1, 2, 3]), 4) if __name__ == '__main__': unittest.main() <file_sep>/leetcode/414.third_max_number.js /** * @param {number[]} nums * @return {number} */ var thirdMax = function(nums) { var first = second = third = -Infinity; var temp1, temp2; for (var i = 0; i < nums.length; i++) { if (nums[i] > first) { temp1 = first; first = nums[i]; temp2 = second; second = temp1; third = temp2; } else if (nums[i] > second && nums[i] !== first) { temp2 = second; second = nums[i]; third = temp2; } else if (nums[i] > third && nums[i] !== second && nums[i] !== first) { third = nums[i]; } } if (third === -Infinity) { return first; } return third; }; <file_sep>/leetcode/744.smallest_letter_greater_than_target.js /** * @param {character[]} letters * @param {character} target * @return {character} */ var nextGreatestLetter = function(letters, target) { var lo = 0, hi = letters.length-1; while (lo <= hi) { let mid = Math.floor((lo + hi) / 2); if (letters[mid] < target) { lo = mid + 1; } else if (letters[mid] > target) { hi = mid - 1; } else { while (letters[mid] === target) { mid++; } return letters[(mid) % letters.length]; } } return letters[(lo) % letters.length]; }; <file_sep>/sorting/quick_sort.c /** * Quick sort implemented on array. */ #include <stdio.h> int part(int a[], int lf, int rt) { int piv = (lf + rt) / 2; int temp; int retval = lf; temp = a[rt]; a[rt] = a[piv]; a[piv] = temp; int i; for (i = lf; i < rt; i++) { if (a[i] < a[rt]) { temp = a[retval]; a[retval] = a[i]; a[i] = temp; retval++; } } temp = a[rt]; a[rt] = a[retval]; a[retval] = temp; return retval; } void qsort(int a[], int left, int right) { if (left < right) { int pivot = part(a, left, right); qsort(a, left, pivot-1); qsort(a, pivot+1, right); } } int main() { int n; int i; int j; printf("Enter the number of items to be sorted: "); scanf("%d", &n); if (n == 0) { printf("Invalid input.\n"); return 1; } int a[n]; printf("Enter %d items below:\n", n); for (i = 0; i < n; i++) { scanf("%d", &a[i]); } if (n > 1) { qsort(a, 0, n-1); } for (j = 0; j < n; j++) { if (j < n-1) printf("%d ", a[j]); else printf("%d\n", a[j]); } return 0; } <file_sep>/linked_list/sum_spec.rb require_relative 'sum' describe 'Tests for BigNumber addition: ' do before :each do @num = BigNumber.new('1234') @head = @num.to_list end it 'should be able to convert to linked list' do @head.should respond_to(:value) @head.should respond_to(:next) end it 'should create the linked list with right values' do @head.value.should eq(4) @head.next.value.should eq(3) @head.next.next.value.should eq(2) @head.next.next.next.value.should eq(1) @head.next.next.next.next.should eq(nil) end it "should support '+' arithmetic" do @num.should respond_to(:+) end describe 'arithmetic details' do it 'should return a BigNumber' do other = BigNumber.new('4321') (@num + other).is_a?(BigNumber).should be_true (@num + other).is_a?(BigNumber).should be_true end it 'should work with equal length lists and no carry over' do other = BigNumber.new('4321') (@num + other).value.should eq('5555') end it 'should correctly append zeros' do new_head = BigNumber.append_zeros(@head, 2) # 001234 new_head.value.should eq(4) new_head.next.value.should eq(3) new_head.next.next.next.next.value.should eq(0) new_head.next.next.next.next.next.value.should eq(0) new_head.next.next.next.next.next.next.should eq(nil) end it 'should work with different length lists and no carry over' do other = BigNumber.new('12345') (@num + other).value.should eq('13579') end it 'should work when there is carry over' do other = BigNumber.new('3276') another = BigNumber.new('99776') (@num + other).value.should eq('4510') (another + @num).value.should eq('101010') end end end <file_sep>/leetcode/1137.js const assert = require('assert'); /** * @param {number} n * @return {number} */ var tribonacci = function(n) { if (n === 0) { return 0; } else if (n < 3) { return 1; } else { const seq = [0, 1, 1]; while (seq.length < n+1) { let currLen = seq.length; seq.push(seq[currLen-1] + seq[currLen-2] + seq[currLen-3]); } return seq[seq.length-1]; } }; assert(tribonacci(4) === 4); assert(tribonacci(25) === 1389537); <file_sep>/string/reverse.py # Reverse a string in place def reverse(sentence): letters = list(sentence) for i in range(len(letters) / 2): letters[i], letters[-1-i] = letters[-1-i], letters[i] return ''.join(letters) <file_sep>/leetcode/70.climb_stairs.py import unittest class Solution(object): def solve(self, n): f = [1] * (n+1) for i in range(n+1): if i > 1: f[i] = f[i-1] + f[i-2] return f[-1] class SolutionTestCase(unittest.TestCase): def test_example(self): pass if __name__ == '__main__': unittest.main() <file_sep>/leetcode/51.n_queens.js const _ = require('underscore'); var board = []; var solutions = []; function validate(board, row, col) { // row if (board[row].indexOf('Q') > -1) { return false; } // column for (let i = 0; i < board.length; i++) { if (board[i][col] === 'Q') { return false; } } // diagnal let r = row; let c = col; while (r > 0) { r--; c--; if (board[r][c] === 'Q') { return false; } } r = row; c = col; while (r > 0) { r--; c++; if (board[r][c] === 'Q') { return false; } } return true; } function placeQueenAt(position) { let row = ''; for (let i = 0; i < board.length; i++) { row += (i === position) ? 'Q' : '.'; } return row; } function solve(board, currentRow) { if (currentRow >= board.length) { solutions.push(board); return; } for (let i = 0; i < board.length; i++) { if (validate(board, currentRow, i)) { board[currentRow] = placeQueenAt(i); solve(board.slice(), ++currentRow); currentRow--; board[currentRow] = emptyRow(board.length); } } } function emptyRow(n) { let row = ''; for (let i = 0; i < n; i++) { row += '.'; } return row; } /** * @param {number} n * @return {string[][]} */ var solveNQueens = function(n) { let row = emptyRow(n); for (let j = 0; j < n; j++) { board.push(row); } solve(board, 0); return solutions; }; solveNQueens(4); console.log(solutions); <file_sep>/leetcode/1002.find_common_characters.js /** * @param {string[]} A * @return {string[]} */ var commonChars = function(A) { let letters = {}, h = []; for (let i = 0; i < A.length; i++) { h.push({}); } let result = []; for (let i = 0; i < A.length; i++) { for (let j = 0; j < A[i].length; j++) { letters[A[i][j]] = true; if (h[i][A[i][j]]) { h[i][A[i][j]]++; } else { h[i][A[i][j]] = 1; } } } for (let k in letters) { let common = true; let counter = []; for (let i = 0; i < A.length; i++) { if (h[i][k] === undefined) { common = false; break; } else { counter.push(h[i][k]); } } if (common) { let n = Math.min(...counter); for (let i = 0; i < n; i++) { result.push(k); } } } return result; }; <file_sep>/leetcode/19.remove_from_end_of_list.py import unittest from util import ListNode class Solution(object): def solve(self, head, n): p1 = head # slow p2 = head # fast prev = head # follows p1 moved_p1 = False while n > 1: p2 = p2.next n -= 1 while p2.next is not None: p1 = p1.next p2 = p2.next if moved_p1 is False: moved_p1 = True continue if moved_p1: prev = prev.next # now p1 points to the node to be removed if prev == p1: return p1.next else: prev.next = p1.next p1.next = None return head class SolutionTestCase(unittest.TestCase): def test_example(self): node1 = ListNode(1) node2 = ListNode(2) node3 = ListNode(3) node4 = ListNode(4) node5 = ListNode(5) node1.next = node2 node2.next = node3 node3.next = node4 node4.next = node5 head = Solution().solve(node1, 2) self.assertEqual(head, node1) self.assertEqual(head.next, node2) self.assertEqual(head.next.next, node3) self.assertEqual(head.next.next.next, node5) def test_delete_head(self): node1 = ListNode(1) node2 = ListNode(2) node3 = ListNode(3) node4 = ListNode(4) node5 = ListNode(5) node1.next = node2 node2.next = node3 node3.next = node4 node4.next = node5 head = Solution().solve(node1, 5) self.assertEqual(head, node2) self.assertEqual(head.next, node3) self.assertEqual(head.next.next, node4) self.assertEqual(head.next.next.next, node5) if __name__ == '__main__': unittest.main() <file_sep>/leetcode/566.reshape_matrix.js const _ = require('lodash'); /** * @param {number[][]} nums * @param {number} r * @param {number} c * @return {number[][]} */ var matrixReshape = function(nums, r, c) { var numbers = _.flatten(nums); var result = []; var index = 0; for (let i = 0; i < r; i++) { let row = []; for (let j = 0; j < c; j++) { if (index < numbers.length) { row.push(numbers[index]); index++; } else { return nums; } } result.push(row); console.log(result); } return result; }; <file_sep>/leetcode/template.py import unittest class Solution(object): def solve(self): pass class SolutionTestCase(unittest.TestCase): def test_example(self): pass if __name__ == '__main__': unittest.main() <file_sep>/leetcode/118.pascals_triangle.js /** * @param {number} numRows * @return {number[][]} */ var generate = function(numRows) { if (numRows < 1) return []; var result = [[1]]; for (var i = 1; i < numRows; i++) { let row = Array(i+1).fill(0); for (var j = 0; j <= i; j++) { row[j] = (result[i-1][j-1] || 0) + (result[i-1][j] || 0); } result.push(row); } return result; }; <file_sep>/linked_list/remove_duplicates.c /* * Remove duplicates from an unsorted linked list without a temporary buffer. */ #include <stdio.h> #include <stdlib.h> #include <string.h> struct node { char value; struct node *next; }; /* * Keep two pointers, 'head' does a normal scan of the list while 'runner' * iterates through all prior nodes and remove duplicate elements. */ struct node * remove_duplicates(struct node *head) { struct node *curr = head; while (curr != NULL) { struct node *runner = head; struct node *prev = NULL; while (runner != curr) { if (runner->value == curr->value) { if (runner == head) { head = runner->next; } else { prev->next = runner->next; } runner->next = NULL; free(runner); break; } else { prev = runner; runner = runner->next; } } curr = curr->next; } return head; } void show_list(struct node *head) { while (head != NULL) { printf("%c", head->value); head = head->next; } printf("\n"); } /* * Take an array of char and make a corresponding linked list. Return the head * of the list. */ struct node * create_list(char *str) { int length = strlen(str); struct node *curr = NULL; struct node *prev = NULL; int i; for (i = length; i >= 0; i--) { curr = (struct node *)malloc(sizeof(struct node)); curr->value = str[i]; if (i == length) { curr->next = NULL; } else { curr->next = prev; } prev = curr; } return curr; } int main() { struct node *head = create_list("hello world"); show_list(head); struct node *new_head = remove_duplicates(head); show_list(new_head); } <file_sep>/interview_cake/rectangular_love.py import unittest def find_intersection(rect1, rect2): # no intersection if (rect1['left_x'] + rect1['width'] <= rect2['left_x'] or rect2['left_x'] + rect2['width'] <= rect1['left_x']): return None if (rect1['bottom_y'] + rect1['height'] <= rect2['bottom_y'] or rect2['bottom_y'] + rect2['height'] <= rect1['bottom_y']): return None # completely contain if (rect1['left_x'] >= rect2['left_x'] and rect1['bottom_y'] >= rect2['bottom_y'] and rect1['width'] <= rect2['width'] and rect1['height'] <= rect2['height']): return rect1 if (rect2['left_x'] >= rect1['left_x'] and rect2['bottom_y'] >= rect1['bottom_y'] and rect2['width'] <= rect1['width'] and rect2['height'] <= rect1['height']): return rect2 # partially intersect return { 'left_x': max(rect1['left_x'], rect2['left_x']), 'bottom_y': max(rect1['bottom_y'], rect2['bottom_y']), 'width': min( rect1['left_x']+rect1['width'], rect2['left_x']+rect2['width']) - max( rect1['left_x'], rect2['left_x']), 'height': min( rect1['bottom_y']+rect1['height'], rect2['bottom_y']+rect2['height']) - max( rect1['bottom_y'], rect2['bottom_y'])} class RectLoveTestCase(unittest.TestCase): def test_no_intersection(self): rect1 = { 'left_x': 1, 'bottom_y': 5, 'width': 4, 'height': 4 } rect2 = { 'left_x': 6, 'bottom_y': 4, 'width': 4, 'height': 4 } self.assertEqual(find_intersection(rect1, rect2), None) def test_partial_intersection(self): rect1 = { 'left_x': 1, 'bottom_y': 5, 'width': 10, 'height': 5 } rect2 = { 'left_x': 8, 'bottom_y': 3, 'width': 5, 'height': 3 } self.assertEqual(find_intersection(rect1, rect2), { 'left_x': 8, 'bottom_y': 5, 'width': 3, 'height': 1 }) if __name__ == '__main__': unittest.main() <file_sep>/linked_list/reverse.py # Reverse the direction of a singly-linked list in O(n) time. class Node(object): def __init__(self, value=None, next=None): self.value = value self.next = next def reverse(head): if not type(head) is Node: raise TypeError("Argument is not a linked list.") if head.next is None: return head curr = head prev = head next = head.next while next is not None: if curr == head: curr.next = None else: curr.next = prev prev = curr curr = next next = next.next curr.next = prev head = curr return head <file_sep>/interview_cake/largest_stack.py import unittest from util import Stack class MaxStack(Stack): def __init__(self): super(MaxStack, self).__init__() self.max_stack = Stack() def push(self, item): super(MaxStack, self).push(item) if len(self.max_stack.items) == 0: self.max_stack.push(item) elif len(self.max_stack.items) == 1: if self.max_stack.peek() > item: temp = self.max_stack.pop() self.max_stack.push(item) self.max_stack.push(temp) else: self.max_stack.push(item) else: if self.max_stack.peek() is None or self.max_stack.peek() < item: self.max_stack.push(item) def pop(self): item = super(MaxStack, self).pop() if item == self.get_max(): self.max_stack.pop() return item def get_max(self): return self.max_stack.peek() class LargestStackTestCase(unittest.TestCase): def test_example(self): s = MaxStack() s.push(1) self.assertEqual(s.get_max(), 1) s.push(2) self.assertEqual(s.get_max(), 2) s.push(3) self.assertEqual(s.get_max(), 3) s.push(4) self.assertEqual(s.get_max(), 4) s.pop() self.assertEqual(s.get_max(), 3) s.pop() self.assertEqual(s.get_max(), 2) s.pop() self.assertEqual(s.get_max(), 1) if __name__ == '__main__': unittest.main() <file_sep>/leetcode/15.three_sum.py import unittest class Solution(object): def solve(self, nums): triplets = [] nums.sort() for i in range(len(nums)-2): if i > 0 and nums[i] == nums[i-1]: continue left = i + 1 right = len(nums) - 1 while left < right: s = nums[i] + nums[left] + nums[right] if s < 0: left += 1 elif s > 0: right -= 1 else: triplets.append([nums[i], nums[left], nums[right]]) while left < right and nums[left] == nums[left+1]: left += 1 while left < right and nums[right] == nums[right-1]: right -= 1 left += 1 right -= 1 return triplets class SolutionTestCase(unittest.TestCase): def test_example(self): s = [-1, 0, 1, 2, -1, -4] solution = Solution().solve(s) self.assertIn([-1, 0, 1], solution) self.assertIn([-1, -1, 2], solution) self.assertEqual(len(solution), 2) def test_79(self): s = [-1, 0, 1] solution = Solution().solve(s) self.assertIn([-1, 0, 1], solution) self.assertEqual(len(solution), 1) def test_123(self): s = [-4, -2, -2, -2, 0, 1, 2, 2, 2, 3, 3, 4, 4, 6, 6] solution = Solution().solve(s) self.assertIn([-4, -2, 6], solution) self.assertIn([-4, 0, 4], solution) self.assertIn([-4, 1, 3], solution) self.assertIn([-4, 2, 2], solution) self.assertIn([-2, -2, 4], solution) self.assertIn([-2, 0, 2], solution) self.assertEqual(len(solution), 6) if __name__ == '__main__': unittest.main() <file_sep>/leetcode/349.intersection_of_two_arrays.js /** * @param {number[]} nums1 * @param {number[]} nums2 * @return {number[]} */ var intersection = function(nums1, nums2) { var hash = {}; var result = []; for (let i = 0; i < nums1.length; i++) { hash[nums1[i]] = true; } for (let j = 0; j < nums2.length; j++) { if (hash[nums2[j]] && result.indexOf(nums2[j]) < 0) { result.push(nums2[j]); } } return result; }; <file_sep>/leetcode/606.tree2str.js /** * @param {TreeNode} t * @return {string} */ var tree2str = function(t) { if (!t) return ''; if (t.left && t.right) { return `${t.val}(${tree2str(t.left)})(${tree2str(t.right)})`; } if (t.left && !t.right) { return `${t.val}(${tree2str(t.left)})`; } if (!t.left && t.right) { return `${t.val}()(${tree2str(t.right)})`; } if (!t.left && !t.right) { return `${t.val}`; } }; <file_sep>/leetcode/46.permutations.py import unittest class Solution(object): def __init__(self): self.permutations = [] def backtrack(self, nums, partial): if len(nums) == 0: self.permutations.append(partial) return for num in nums: next_nums = nums[:] next_partial = partial[:] next_nums.remove(num) next_partial.append(num) self.backtrack(next_nums, next_partial) def permute(self, nums): self.backtrack(nums, []) return self.permutations class SolutionTestCase(unittest.TestCase): def test_example(self): result = Solution().permute([1, 2, 3]) self.assertEqual(len(result), 6) if __name__ == '__main__': unittest.main() <file_sep>/leetcode/561.array_partition.js const _ = require('lodash'); /** * @param {number[]} nums * @return {number} */ var arrayPairSum = function(nums) { var sorted = _.sortBy(nums); var i = 0; var s = 0; while (i < sorted.length) { s += sorted[i]; i += 2; } return s; }; <file_sep>/interview_cake/bst_checker.py import unittest from util import BinaryTreeNode def valid_bst(root): if root is None: return True nodes = [(root, -float('inf'), float('inf'))] while len(nodes): node, lower_bound, upper_bound = nodes.pop() if node.value < lower_bound or node.value > upper_bound: return False if node.left: nodes.append((node.left, lower_bound, node.value)) if node.right: nodes.append((node.right, node.value, upper_bound)) return True def valid_bst_recursive_helper(node, lower_bound, upper_bound): if node is None: return True if node.value < lower_bound or node.value > upper_bound: return False return valid_bst_recursive_helper( node.left, lower_bound, node.value) and valid_bst_recursive_helper( node.right, node.value, upper_bound) def valid_bst_recursive(root): return valid_bst_recursive_helper(root, -float('inf'), float('inf')) class BinarySearchTreeCheckerTestCase(unittest.TestCase): def test_valid(self): tree = BinaryTreeNode(5) tree.insert_left(4) tree.left.insert_left(2) tree.insert_right(8) tree.right.insert_left(6) tree.right.insert_right(10) # self.assertTrue(valid_bst(tree)) self.assertTrue(valid_bst_recursive(tree)) def test_invalid(self): tree = BinaryTreeNode(5) tree.insert_left(4) tree.left.insert_left(2) tree.insert_right(8) tree.right.insert_left(6) tree.right.insert_right(3) # self.assertFalse(valid_bst(tree)) self.assertFalse(valid_bst_recursive(tree)) def test_gotcha(self): tree = BinaryTreeNode(50) tree.insert_left(30) tree.insert_right(80) tree.left.insert_left(20) tree.left.insert_right(60) tree.right.insert_left(70) tree.right.insert_right(90) # self.assertFalse(valid_bst(tree)) self.assertFalse(valid_bst_recursive(tree)) if __name__ == '__main__': unittest.main() <file_sep>/leetcode/938.bst_range_sum.js /** * @param {TreeNode} root * @param {number} L * @param {number} R * @return {number} */ var rangeSumBST = function(root, L, R) { if (!root) return 0; if (root.val >= L && root.val <= R) { return rangeSumBST(root.left, L, R) + rangeSumBST(root.right, L, R) + root.val; } else { return rangeSumBST(root.left, L, R) + rangeSumBST(root.right, L, R); } }; <file_sep>/util/stack.rb require_relative 'util' module Util class Stack def initialize @top = nil end def peek @top.nil? ? nil : @top.value end def push(value) node = Util::Node.new(value) node.next = @top @top = node end def pop return nil if self.empty? temp = @top @top = @top.next temp.value end def empty? !!@top.nil? end end end <file_sep>/leetcode/225.stack_using_queues.js /** * Initialize your data structure here. */ var MyStack = function() { this.pushItems = []; this.popItems = []; }; /** * Push element x onto stack. * @param {number} x * @return {void} */ MyStack.prototype.push = function(x) { this.pushItems.push(x); }; /** * Removes the element on top of the stack and returns that element. * @return {number} */ MyStack.prototype.pop = function() { while (this.pushItems.length > 1) { let item = this.pushItems.shift(); this.popItems.push(item); } let result = this.pushItems.shift(); let len = this.popItems.length; for (let i = 0; i < len; i++) { this.pushItems.push(this.popItems.shift()); } return result; }; /** * Get the top element. * @return {number} */ MyStack.prototype.top = function() { return this.pushItems[this.pushItems.length-1]; }; /** * Returns whether the stack is empty. * @return {boolean} */ MyStack.prototype.empty = function() { return this.pushItems.length === 0; }; <file_sep>/leetcode/79.word_search.py import unittest class Solution(object): def find_neighbors(self, x, y, visited): def out_of_bound(x, y): return (x < 0) or (x >= self.height) or ( y < 0) or (y >= self.width) neighbors = [] if not out_of_bound(x-1, y) and not (x-1, y) in visited.keys(): neighbors.append((x-1, y)) if not out_of_bound(x+1, y) and not (x+1, y) in visited.keys(): neighbors.append((x+1, y)) if not out_of_bound(x, y-1) and not (x, y-1) in visited.keys(): neighbors.append((x, y-1)) if not out_of_bound(x, y+1) and not (x, y+1) in visited.keys(): neighbors.append((x, y+1)) return neighbors def dfs(self, origin, letters, visited): if len(letters) < 1: return True x, y = origin letter = letters.pop(0) if letter != self.board[x][y]: return False visited[origin] = True neighbors = self.find_neighbors(x, y, visited) if len(neighbors) < 1 and len(letters) < 1: return True for neighbor in neighbors: if self.dfs(neighbor, letters[:], visited): return True del visited[origin] def exist(self, board, word): self.board = board self.width = len(board[0]) self.height = len(board) for i in range(self.height): for j in range(self.width): if board[i][j] == word[0] and self.dfs((i, j), list(word), {}): return True return False class SolutionTestCase(unittest.TestCase): def test_example(self): board = [ ['A', 'B', 'C', 'E'], ['S', 'F', 'C', 'S'], ['A', 'D', 'E', 'E'], ] self.assertTrue(Solution().exist(board, 'ABCCED')) self.assertTrue(Solution().exist(board, 'SEE')) self.assertFalse(Solution().exist(board, 'ABCB')) def test_53(self): board = [ ['a', 'b'], ['c', 'd'], ] self.assertTrue(Solution().exist(board, 'acdb')) def test_72(self): board = [ ['C', 'A', 'A'], ['A', 'A', 'A'], ['B', 'C', 'D'], ] self.assertTrue(Solution().exist(board, 'AAB')) if __name__ == '__main__': unittest.main() <file_sep>/string/word_rotation.rb # Given two strings s1 and s2, check if s2 is a rotation of s1 using only one # call to isSubstring (a method checks if one word is a substring of another). # # e.g. 'erbottlewat' is a rotation of 'waterbottle' S1 = 'waterbottle' S2 = 'erbottlewat' def rotation? s1, s2 return false if s1.length != s2.length || s1.length == 0 s1s1 = s1 + s1 s1s1.include? s2 end if rotation? S1, S2 puts "#{S1} is a rotation of #{S2}" else puts "#{S1} isn't a rotation of #{S2}" end <file_sep>/leetcode/970.powerful_integers.js /** * @param {number} x * @param {number} y * @param {number} bound * @return {number[]} */ var powerfulIntegers = function(x, y, bound) { let result = []; let maxi = 0, maxj = 0; if (x === 1) { maxi = 1; } else { while (x ** (maxi+1) < bound) { maxi++; } } if (y === 1) { maxj = 1; } else { while (y ** (maxj+1) < bound) { maxj++; } } for (let i = 0; i <= maxi; i++) { for (let j = 0; j <= maxj; j++) { let prod = x ** i + y ** j; if (prod <= bound && result.indexOf(prod) < 0) { result.push(prod); } } } return result; }; <file_sep>/leetcode/234.palindrome_linked_list.py import unittest from util import ListNode class Solution(object): def solve(self, head): slow = fast = head while fast and fast.next: fast = fast.next.next slow = slow.next if fast: slow = slow.next # reverse the second half prev = None while slow: next = slow.next slow.next = prev prev = slow slow = next fast = head slow = prev while slow: if fast.val != slow.val: return False fast = fast.next slow = slow.next return True class SolutionTestCase(unittest.TestCase): def test_example(self): node1 = ListNode('a') node2 = ListNode('b') node3 = ListNode('b') node4 = ListNode('a') node1.next = node2 node2.next = node3 node3.next = node4 self.assertTrue(Solution().solve(node1)) node1 = ListNode('a') node2 = ListNode('b') node3 = ListNode('c') node4 = ListNode('b') node5 = ListNode('a') node1.next = node2 node2.next = node3 node3.next = node4 node4.next = node5 self.assertTrue(Solution().solve(node1)) node1 = ListNode('a') node2 = ListNode('b') node1.next = node2 self.assertFalse(Solution().solve(node1)) if __name__ == '__main__': unittest.main() <file_sep>/leetcode/475.heaters.js const _ = require('lodash'); /** * @param {number[]} houses * @param {number[]} heaters * @return {number} */ var findRadius = function(houses, heaters) { var sortedHeaters = _.sortBy(heaters); var radius = 0; for (let house of houses) { let heater = nearestHeater(house); console.log('heater', heater, house); if (Math.abs(house-heater) > radius) { radius = Math.abs(house-heater); } } return radius; function nearestHeater(house) { var lo = 0, hi = heaters.length-1; while (lo <= hi) { let mid = Math.floor((lo + hi) / 2); if (sortedHeaters[mid] > house) { hi = mid - 1; } else if (sortedHeaters[mid] < house) { lo = mid + 1; } else { return sortedHeaters[mid]; } } if (hi < 0) return sortedHeaters[lo]; if (lo > heaters.length-1) return sortedHeaters[hi]; let hiDistance = Math.abs(sortedHeaters[hi]-house); let loDistance = Math.abs(sortedHeaters[lo]-house); return (hiDistance > loDistance) ? sortedHeaters[lo] : sortedHeaters[hi]; } }; <file_sep>/leetcode/155.min_stack.js /** * initialize your data structure here. */ var MinStack = function() { this.items = []; this.min = []; }; /** * @param {number} x * @return {void} */ MinStack.prototype.push = function(x) { this.items.push(x); let min = this.getMin(); if (min !== undefined) { this.min.push(Math.min(x, min)); } else { this.min.push(x); } }; /** * @return {void} */ MinStack.prototype.pop = function() { this.items.pop(); this.min.pop(); }; /** * @return {number} */ MinStack.prototype.top = function() { return this.items[this.items.length-1]; }; /** * @return {number} */ MinStack.prototype.getMin = function() { return this.min[this.min.length-1]; }; <file_sep>/leetcode/39.combination_sum.py import unittest class Solution(object): def __init__(self): self.combinations = [] def combination_helper(self, candidates, target, partial): if target == 0: partial.sort() if partial not in self.combinations: self.combinations.append(partial) elif target > 0: for candidate in candidates: partial.append(candidate) self.combination_helper( candidates, target-candidate, partial[:]) partial.pop() def solve(self, candidates, target): self.combination_helper(candidates, target, []) return self.combinations class SolutionTestCase(unittest.TestCase): def test_example1(self): solution = Solution().solve([2, 3, 6, 7], 7) self.assertEqual(len(solution), 2) self.assertIn([7], solution) self.assertIn([2, 2, 3], solution) def test_example2(self): solution = Solution().solve([2, 3, 5], 8) self.assertEqual(len(solution), 3) self.assertIn([2, 2, 2, 2], solution) self.assertIn([2, 3, 3], solution) self.assertIn([3, 5], solution) if __name__ == '__main__': unittest.main() <file_sep>/sorting/merge_sort.c /** * Merge sort implemented on an array. * This program sorts the input integers in ascending order. It assumes * the values to be sorted are in a reasonable range. */ #include <stdio.h> #include <stdlib.h> #define MAX_VALUE 32767 void merge(int a[], int head, int midpoint , int tail) { int n1 = midpoint - head + 1; int n2 = tail - midpoint; // Prepare two subarrays to copy out the value for merging // Reserve one more space at the end so the comparison won't // go out of bounds later int s1[n1+1]; int s2[n2+1]; int i, j, k; for (i = 0; i < n1; i++) s1[i] = a[i+head]; s1[n1] = MAX_VALUE; for (i = 0; i < n2; i++) s2[i] = a[i+midpoint+1]; s2[n2] = MAX_VALUE; i = 0; // index for s1 j = 0; // index for s2 for (k = head; k <= tail; k++) { if (s1[i] < s2[j]) { a[k] = s1[i]; i++; // i could go out of bound then s1[i] becomes small } else { a[k] = s2[j]; j++; // j could go out of bound then s2[j] becomes small } } } void merge_sort(int a[], int head, int tail) { if (head < tail) { int midpoint = (head + tail) / 2; merge_sort(a, head, midpoint); merge_sort(a, midpoint+1, tail); merge(a, head, midpoint, tail); } } int main() { int n; printf("Enter the number of items to be sorted: "); scanf("%d", &n); if (n < 1) { printf("Invalid input.\n"); return 0; } int a[n]; int i; printf("Enter %d items below:\n", n); for (i = 0; i < n; i++) scanf("%d", &a[i]); merge_sort(a, 0, n-1); // Display the output for (i = 0; i < n-1; i++) printf("%d ", a[i]); printf("%d\n", a[n-1]); } <file_sep>/leetcode/409.longest_palindrome.js /** * @param {string} s * @return {number} */ var longestPalindrome = function(s) { let h = {}; let count = 0; let len = s.length; for (let i = 0; i < s.length; i++) { if (h[s[i]] === undefined) { h[s[i]] = 1; } else { h[s[i]]++; } } for (let k in h) { if (h[k] > 1) { let x = Math.floor(h[k]/2) * 2; count += x; len -= x; } } if (len > 0) { count++; } return count; }; <file_sep>/leetcode/138.list_with_random_pointer.py import unittest class RandomListNode(object): def __init__(self, x): self.label = x self.next = None self.random = None class Solution(object): def solve(self, head): if head is None: return None nodes = {} curr = head while curr: nodes[curr] = RandomListNode(curr.label) curr = curr.next curr = head while curr: if curr.next: nodes[curr].next = nodes[curr.next] else: nodes[curr].next = None if curr.random: nodes[curr].random = nodes[curr.random] else: nodes[curr].random = None curr = curr.next return nodes[head] class SolutionTestCase(unittest.TestCase): def test_example(self): node1 = RandomListNode(1) node2 = RandomListNode(2) node3 = RandomListNode(3) node4 = RandomListNode(4) node1.next = node2 node2.next = node3 node3.next = node4 node1.random = node4 node2.random = node3 node3.random = node3 node4.random = node2 node = Solution().solve(node1) self.assertEqual(node.label, 1) self.assertEqual(node.next.label, 2) self.assertEqual(node.random.label, 4) node = node.next self.assertEqual(node.label, 2) self.assertEqual(node.next.label, 3) self.assertEqual(node.random.label, 3) node = node.next self.assertEqual(node.label, 3) self.assertEqual(node.next.label, 4) self.assertEqual(node.random.label, 3) node = node.next self.assertEqual(node.label, 4) self.assertEqual(node.next, None) self.assertEqual(node.random.label, 2) if __name__ == '__main__': unittest.main() <file_sep>/interview_cake/stolen_breakfast_drone.py import unittest def find_unique(values): unique = 0 for value in values: unique ^= value return unique class StolenBreakfastDroneTestCase(unittest.TestCase): def test_example(self): pass data = [1, 2, 2, 3, 1, 3, 4] self.assertEqual(find_unique(data), 4) if __name__ == '__main__': unittest.main() <file_sep>/interview_cake/products_of_others.py import unittest def products_of_others(values): if len(values) < 2: raise IndexError # product of predecessors predecessors = [1 for i in range(len(values))] # product of successors successors = [1 for i in range(len(values))] for index, value in enumerate(values): if index == 0: continue predecessors[index] = predecessors[index-1] * values[index-1] i = len(values) - 2 while i >= 0: successors[i] = successors[i+1] * values[i+1] i -= 1 products = [] for i in range(len(values)): products.append(predecessors[i] * successors[i]) return products class ProductsOfOthersTestCase(unittest.TestCase): def test_example(self): data = [1, 7, 3, 4] self.assertEqual(products_of_others(data), [84, 12, 28, 21]) def test_two(self): data = [1, 2, 6, 5, 9] self.assertEqual(products_of_others(data), [540, 270, 90, 108, 60]) if __name__ == '__main__': unittest.main() <file_sep>/leetcode/674.longest_continuous_increasing_subsequence.js /** * @param {number[]} nums * @return {number} */ var findLengthOfLCIS = function(nums) { if (nums.length < 2) return nums.length; var len = Array(nums.length).fill(1); for (let i = 1; i < nums.length; i++) { if (nums[i] > nums[i-1]) { len[i] = len[i-1] + 1; } } return Math.max(...len); }; <file_sep>/leetcode/18.four_sum.py import unittest class Solution(object): def three_sum(self, nums, target): triplets = [] nums.sort() for i in range(len(nums)-2): if i > 0 and nums[i] == nums[i-1]: continue left = i + 1 right = len(nums) - 1 while left < right: s = nums[i] + nums[left] + nums[right] if s < target: left += 1 elif s > target: right -= 1 else: triplets.append([nums[i], nums[left], nums[right]]) while left < right and nums[left] == nums[left+1]: left += 1 while left < right and nums[right] == nums[right-1]: right -= 1 left += 1 right -= 1 return triplets def solve(self, nums, target): nums.sort() results = [] for i in range(len(nums)-3): if i == 0 or nums[i] != nums[i-1]: three_sum_results = self.three_sum(nums[i+1:], target-nums[i]) if len(three_sum_results) > 0: for three_sum_result in three_sum_results: results.append([nums[i]] + three_sum_result) return results class SolutionTestCase(unittest.TestCase): def test_example(self): s = [1, 0, -1, 0, -2, 2] solution = Solution().solve(s, 0) self.assertIn([-1, 0, 0, 1], solution) self.assertIn([-2, -1, 1, 2], solution) self.assertIn([-2, 0, 0, 2], solution) self.assertEqual(len(solution), 3) if __name__ == '__main__': unittest.main() <file_sep>/tree/find_median.py # Find Median # www.hackerrank.com/challenges/find-median-1 import sys n = int(sys.stdin.readline()) for i in range(n): value = int(sys.stdin.readline()) <file_sep>/leetcode/174.dungeon_game.py import unittest import copy class Solution(object): def solve(self, dungeon): length, width = len(dungeon), len(dungeon[0]) health = copy.deepcopy(dungeon) for i in reversed(range(0, length)): for j in reversed(range(0, width)): if (i == length-1) and (j == width-1): health[i][j] = max(1, 1 - dungeon[length-1][width-1]) elif i == length-1: health[i][j] = max(1, health[i][j+1] - dungeon[i][j]) elif j == width-1: health[i][j] = max(1, health[i+1][j] - dungeon[i][j]) else: health[i][j] = max(1, min( health[i+1][j], health[i][j+1]) - dungeon[i][j]) return health[0][0] class SolutionTestCase(unittest.TestCase): def test_example(self): dungeon = [ [-2, -3, 3], [-5, -10, 1], [10, 30, -5] ] self.assertEqual(Solution().solve(dungeon), 7) def test_1(self): dungeon = [ [0, 0, 0], [1, 1, -1] ] self.assertEqual(Solution().solve(dungeon), 1) def test_2(self): dungeon = [ [1, -3, 3], [0, -2, 0], [-3, -3, -3] ] self.assertEqual(Solution().solve(dungeon), 3) if __name__ == '__main__': unittest.main() <file_sep>/interview_cake/bracket_validator.py import unittest def validate(brackets): stack = [brackets[0]] brackets = brackets[1:] for bracket in brackets: if bracket == ')' and stack[len(stack)-1] == '(': stack.pop() elif bracket == ']' and stack[len(stack)-1] == '[': stack.pop() elif bracket == '}' and stack[len(stack)-1] == '{': stack.pop() else: stack.append(bracket) return len(stack) == 0 class BracketValidatorTestCase(unittest.TestCase): def test_example1(self): self.assertTrue(validate('{[]()}')) def test_example2(self): self.assertFalse(validate('{[(])}')) def test_example3(self): self.assertFalse(validate('{[}')) if __name__ == '__main__': unittest.main() <file_sep>/leetcode/454.4sum_ii.js /** * @param {number[]} A * @param {number[]} B * @param {number[]} C * @param {number[]} D * @return {number} */ var fourSumCount = function(A, B, C, D) { var lookup = {}; var length = A.length; var counter = 0; for (var i = 0; i < length; i++) { for (var j = 0; j < length; j++) { if (lookup[A[i]+B[j]]) { lookup[A[i]+B[j]]++; } else { lookup[A[i]+B[j]] = 1; } } } for (var k = 0; k < length; k++) { for (var l = 0; l < length; l++) { if (lookup[-(C[k]+D[l])]) { counter += lookup[-(C[k]+D[l])]; } } } return counter; }; <file_sep>/leetcode/441.arranging_coins.js /** * @param {number} n * @return {number} */ var arrangeCoins = function(n) { var i = 0; while (n >= 0) { i++; n -= i; } return i-1; }; <file_sep>/leetcode/200.number_of_islands.py import unittest class Solution(object): def solve(self, grid): if len(grid) < 1: return 0 self.n, self.m = len(grid), len(grid[0]) self.grid = [list(s) for s in grid] num_islands = 0 for i in range(self.n): for j in range(self.m): if self.grid[i][j] == '1': self.dfs_mark(self.grid, i, j) num_islands += 1 return num_islands def dfs_mark(self, grid, i, j): if i < 0 or i > self.n-1 or j < 0 or j > self.m-1 or grid[i][j] != '1': return grid[i][j] = '0' self.dfs_mark(self.grid, i-1, j) self.dfs_mark(self.grid, i+1, j) self.dfs_mark(self.grid, i, j-1) self.dfs_mark(self.grid, i, j+1) class SolutionTestCase(unittest.TestCase): def test_example1(self): grid = ['11110', '11010', '11000', '00000'] self.assertEqual(Solution().solve(grid), 1) def test_example2(self): grid = ['11000', '11000', '00100', '00011'] self.assertEqual(Solution().solve(grid), 3) if __name__ == '__main__': unittest.main() <file_sep>/leetcode/605.can_place_flowers.js /** * @param {number[]} flowerbed * @param {number} n * @return {boolean} */ var canPlaceFlowers = function(flowerbed, n) { let i = 0, j = flowerbed.length-1; let l2r = r2l = n; while (i < flowerbed.length) { if (!flowerbed[i-1] && !flowerbed[i+1] && !flowerbed[i]) { l2r--; i += 2; } else { i++; } } if (l2r < 1) return true; while (j > -1) { if (!flowerbed[j-1] && !flowerbed[j+1] && !flowerbed[j]) { r2l--; j -= 2; } else { j--; } } if (r2l < 1) return true; return false; }; <file_sep>/leetcode/60.permutation_sequence.py import math import unittest class Solution(object): def solve(self, n, k): nums = range(1, n+1) result = [] k = k - 1 while k > 0: q = k / math.factorial(n-1) r = k % math.factorial(n-1) digit = nums[q] result.append(digit) nums.remove(digit) n -= 1 k = r result += nums return ''.join(map(str, result)) class SolutionTestCase(unittest.TestCase): def test_example(self): self.assertEqual(Solution().solve(3, 3), '213') self.assertEqual(Solution().solve(4, 9), '2314') if __name__ == '__main__': unittest.main() <file_sep>/leetcode/167.2sum_ii.js const _ = require('lodash'); /** * @param {number[]} numbers * @param {number} target * @return {number[]} */ var twoSum = function(numbers, target) { var lo = 0, hi = numbers.length-1; while (lo < hi) { if (numbers[lo] + numbers[hi] < target) { lo++; } else if (numbers[lo] + numbers[hi] > target) { hi--; } else { return [lo+1, hi+1]; } } }; <file_sep>/queue/truck_tour.py # Truck Tour # www.hackerrank.com/challenges/truck-tour import sys # Given that the truck moves 1 km for each litre of petrol, a petrol pump # with, say, 5L of petrol and 3km to the next pump is equivalent of that # pump having only 2L petrol but 0km to the next pump. Therefore, an example # circle of four petrol pumps # # 1km 0km # 5L--------2L 1L--------1L # | | | | # 4km | | 2km becomes 0km | | 0km # | | | | # 1L--------10L -7L--------8L # 8km 0km # # Now we simply start from anywhere and keep a counter of the current # cumulative petrol level. Whenever it dips below zero we know the truck won't # make the full circle, so we reset the counter and use the next pump as the # new starting point. n = int(sys.stdin.readline()) distances = [] for i in range(n): values = sys.stdin.readline().split(' ') values = map(int, values) distances.append(values[0] - values[1]) current_sum = 0 start_pump = -1 for index, distance in enumerate(distances): current_sum += distance if current_sum >= 0: if start_pump < 0: start_pump = index else: current_sum = 0 start_pump = -1 print start_pump <file_sep>/util/stack_spec.rb require_relative 'stack' module Util describe "Stack Tests: " do before(:each) do @stack = Stack.new end it "should be able to peek" do names = %w(bing bang bosh) names.each { |name| @stack.push(name) } @stack.peek.should == 'bosh' end it "should properly push" do numbers = [3, 1, 5, 1, 5, 9] numbers.each { |num| @stack.push(num) } @stack.peek.should == 9 @stack.push(2) @stack.peek.should == 2 end describe "pop" do before(:each) do 3.times { @stack.push(2) } end it "should pop some elements" do 2.times { @stack.pop } @stack.empty?.should be_false end it "should pop all elements" do 3.times { @stack.pop } @stack.empty?.should be_true end it "should return popped element" do result = @stack.pop result.should == 2 end end it "should know when empty" do @stack.empty?.should be_true @stack.push(1) @stack.empty?.should be_false end end end <file_sep>/leetcode/96.unique_bst.py import unittest class Solution(object): def num_trees(self, n): ''' Number of unique trees = number of unique left subtrees * number of unique right subtrees. Therefore, the formulation is: F(n) = F(0)*F(n-1) + F(1)*F(n-2) + ... + F(n-2)*F(1) + F(n-1)*F(0) ''' if n == 1: return 1 f = [1] * (n+1) f[1] = 1 f[2] = 2 for i in xrange(n+1): if i > 2: f[i] = sum([f[j] * f[i-1-j] for j in range(i)]) return f[-1] class UniqueBSTTestCase(unittest.TestCase): def test_3(self): self.assertEqual(Solution().num_trees(3), 5) def test_4(self): self.assertEqual(Solution().num_trees(4), 14) def test_5(self): self.assertEqual(Solution().num_trees(5), 42) def test_6(self): self.assertEqual(Solution().num_trees(6), 132) if __name__ == '__main__': unittest.main() <file_sep>/stack/sort.rb # Sort a stack in ascending order with only push, pop, peek, and isEmpty. require_relative '../util/util' class SortStack def self.sort(stack) temp = Util::Stack.new result = Util::Stack.new while !stack.empty? || !temp.empty? if stack.empty? base, alt = temp, stack else base, alt = stack, temp end max = base.pop while curr = base.pop if curr < max alt.push(curr) else alt.push(max) max = curr end end result.push(max) end result end end <file_sep>/leetcode/559.max_depth.js const _ = require('lodash'); /** * @param {Node} root * @return {number} */ var maxDepth = function(root) { if (!root) return 0; if (!root.children) return 1; let maxdepth = 0; for (let i = 0; i < root.children.length; i++) { const d = maxDepth(root.children[i]); if (maxDepth(d > maxdepth)) { maxdepth = d; } } return maxdepth+1; }; <file_sep>/leetcode/16.three_sum_closest.py import unittest class Solution(object): def solve(self, nums, target): closest_sum = float('inf') nums.sort() for i in range(len(nums)-2): if i > 0 and nums[i] == nums[i-1]: continue left = i + 1 right = len(nums) - 1 while left < right: s = nums[i] + nums[left] + nums[right] if s < target: if abs(target - s) < abs(target - closest_sum): closest_sum = s left += 1 elif s > target: if abs(target - s) < abs(target - closest_sum): closest_sum = s right -= 1 else: return s return closest_sum class SolutionTestCase(unittest.TestCase): def test_example(self): nums = [-1, 2, 1, -4] target = 1 s = Solution().solve(nums, target) self.assertEqual(s, 2) if __name__ == '__main__': unittest.main() <file_sep>/leetcode/110.js import _ from 'lodash'; import assert from 'assert'; import { TreeNode } from './util.js'; /** * @param {TreeNode} root * @return {boolean} */ var isBalanced = function(root) { function getDepth(node) { if (!node) return -1; const leftDepth = getDepth(node.left); const rightDepth = getDepth(node.right); if (leftDepth === Infinity || rightDepth === Infinity) return Infinity; if (Math.abs(leftDepth - rightDepth) > 1) return Infinity; return Math.max(leftDepth, rightDepth) + 1; } return getDepth(root) !== Infinity; }; // Tests const root = new TreeNode(3); root.left = new TreeNode(9); root.right = new TreeNode(20); root.right.left = new TreeNode(15); root.right.right = new TreeNode(7); assert(isBalanced(root)); const root2 = new TreeNode(1); root2.left = new TreeNode(2); root2.right = new TreeNode(2); root2.left.left = new TreeNode(3); root2.left.right = new TreeNode(3); root2.left.left.left = new TreeNode(4); root2.left.left.right = new TreeNode(4); assert(!isBalanced(root2)); <file_sep>/leetcode/894.js import { TreeNode } from './util.js'; /** * @param {number} N * @return {TreeNode[]} */ var allPossibleFBT = function(N) { const allTrees = { 0: [], 1: [new TreeNode(0)] }; return fbt(N); function fbt(n) { if (!allTrees[n]) { const ans = []; for (let i = 0; i < n; i++) { let j = n-1-i; const left = fbt(i); const right = fbt(j); for (let l of left) { for (let r of right) { const node = new TreeNode(0); node.left = l; node.right = r; ans.push(node); } } } allTrees[n] = ans; } return allTrees[n]; } }; <file_sep>/util/graph.rb require 'set' require 'thread' require_relative 'util' module Util class Graph attr_accessor :vertices, :edges, :directed def initialize(args) @vertices = Set.new @edges = Set.new @directed = args[:directed] end def add(thing) if thing.is_a? Vertex @vertices << thing else @edges << thing @vertices.merge([thing.head, thing.tail]) thing.head.neighbors << thing.tail thing.tail.neighbors << thing.head unless @directed end end def dfs(src) depth_first(src, []) end def bfs(src) visited, enqueued, unvisited = [], [], Queue.new unvisited << src enqueued << src.id while not unvisited.empty? vertex = unvisited.pop visited << vertex.id vertex.neighbors.each do |neighbor| unvisited << neighbor unless enqueued.include? neighbor.id enqueued << neighbor.id end end visited end private def depth_first(src, visited) unless visited.include? src.id visited << src.id if src.neighbors.any? src.neighbors.each { |neighbor| depth_first(neighbor, visited) } end end visited end end class Vertex attr_accessor :id, :neighbors def initialize(id) @id = id @neighbors = [] end end class Edge attr_accessor :head, :tail, :weight def initialize(args) @head = args[:head] @tail = args[:tail] @weight = args[:weight] unless args[:weight].nil? end end end <file_sep>/leetcode/1.two_sum.py def two_sum(nums, target): d = dict() for index, value in enumerate(nums): if target - value in d.keys(): return [d[target-value], index] else: d[value] = index return [] print two_sum([2, 7, 11, 15], 9) <file_sep>/leetcode/1022.sum_root_to_leaf.js const _ = require('lodash'); /** * @param {TreeNode} root * @return {number} */ var sumRootToLeaf = function(root) { function traverse(tree, value) { if (!tree) return; if (!tree.left && !tree.right) { nums.push(value + tree.val); return; } let newValue = value + tree.val; traverse(tree.left, newValue); traverse(tree.right, newValue); } var nums = []; traverse(root, ''); return _.sum(_.map(nums, num => { return parseInt(num, 2); })); }; <file_sep>/interview_cake/shuffle.py import random def get_random(floor, ceiling): random.randrange(floor, ceiling+1) def shuffle(items): i = len(items) - 1 while i > 0: k = get_random(0, i) items[i], items[k] = items[k], items[i] i -= 1 <file_sep>/leetcode/11.container_most_water.py import unittest class Solution(object): def solve(self, height): left = 0 right = len(height) - 1 water = (right - left) * min(height[left], height[right]) while right > left: if height[right] > height[left]: left += 1 else: right -= 1 area = (right - left) * min(height[left], height[right]) water = max(water, area) return water class SolutionTestCase(unittest.TestCase): def test_example(self): h = [1, 2, 1, 3, 3, 1, 2, 1, 1, 3] area = Solution().solve(h) self.assertEqual(area, 18) def test_unequal_height(self): h = [1, 2] area = Solution().solve(h) self.assertEqual(area, 1) if __name__ == '__main__': unittest.main() <file_sep>/leetcode/131.palindrome_partition.py import unittest # if we view this problem as finding all the positions where we would # partition the given string, it becomes equivalent to finding all subsets # of the list [1..len(s)] class Solution(object): def all_palindromic(self, partition): for part in partition: if part != part[::-1]: return False return True def get_partition(self, positions, s): if len(positions) < 1: return [s] partition = [] for i in range(len(positions)): if i == 0: partition.append(s[:positions[0]]) else: partition.append(s[positions[i-1]:positions[i]]) partition.append(s[positions[-1]:]) return partition def subsets(self, nums): all_subsets = [[]] remainder = nums[:] for num in nums: remainder.remove(num) result = self.subsets(remainder) for item in result: subset = [num] + item all_subsets.append(subset) return all_subsets def solve(self, s): all_positions = self.subsets(range(1, len(s))) palindromic_partitions = [] for positions in all_positions: partition = self.get_partition(positions, s) if self.all_palindromic(partition): palindromic_partitions.append(partition) return palindromic_partitions class SolutionTestCase(unittest.TestCase): def test_example(self): solution = Solution().solve('aab') self.assertEqual(len(solution), 2) self.assertIn(['aa', 'b'], solution) self.assertIn(['a', 'a', 'b'], solution) def test_get_partition(self): partition = Solution().get_partition([1, 2], 'aab') self.assertEqual(partition, ['a', 'a', 'b']) if __name__ == '__main__': unittest.main() <file_sep>/leetcode/204.count_primes.js /** * @param {number} n * @return {number} */ var countPrimes = function(n) { if (n < 3) return 0; let count = 0; for (let i = 2; i < n; i++) { if (isPrime(i)) { count++; } } return count; function isPrime(k) { for (let j = 2; j <= Math.floor(Math.sqrt(k)); j++) { if (k % j === 0) return false; } return true; } }; <file_sep>/string/atoi.py # Convert a string into an integer def atoi(s): total = 0 negative = False if s[0] == '-': negative = True s = s[1:] for c in s: value = ord(c) - 48 total = 10 * total + value return total <file_sep>/leetcode/448.find_all_disappeared.js /** * @param {number[]} nums * @return {number[]} */ var findDisappearedNumbers = function(nums) { var result = []; for (let i = 0; i < nums.length; i++) { let index = Math.abs(nums[i]) - 1; nums[index] = -Math.abs(nums[index]); } for (let j = 0; j < nums.length; j++) { if (nums[j] > 0) result.push(j+1); } return result; }; <file_sep>/interview_cake/util.py import unittest class BinaryTreeNode: def __init__(self, value): self.value = value self.left = None self.right = None def insert_left(self, value): self.left = BinaryTreeNode(value) return self.left def insert_right(self, value): self.right = BinaryTreeNode(value) return self.right class Stack(object): def __init__(self): self.items = [] def push(self, item): self.items.append(item) def pop(self): if not self.items: return None return self.items.pop() def peek(self): if not self.items: return None return self.items[-1] class LinkedListNode: def __init__(self, value): self.value = value self.next = None class GraphNode: def __init__(self, label): self.label = label self.neighbors = set() self.color = None class Trie(object): def __init__(self): self.root = {} def find(self, key): node = self.root for char in key: if char in node: node = node[char] else: return False return True def insert(self, key): node = self.root i = 0 for char in key: if char in node: node = node[char] else: break i += 1 while i < len(key): node[key[i]] = {} node = node[key[i]] i += 1 """Tests""" class TrieTestCase(unittest.TestCase): def setUp(self): self.trie = Trie() self.trie.root = { 'd': { 'o': { 'n': {}, 'g': { 'o': { 'o': { 'd': {}}}, 'e': {}}}}} def test_find(self): self.assertTrue(self.trie.find('dog')) self.assertTrue(self.trie.find('doge')) self.assertFalse(self.trie.find('done')) def test_insert(self): self.trie.insert('doggie') self.assertEqual(self.trie.root, { 'd': { 'o': { 'n': {}, 'g': { 'o': { 'o': { 'd': {}}}, 'e': {}, 'g': { 'i': { 'e': {}}}}}}}) if __name__ == '__main__': unittest.main() <file_sep>/leetcode/119.pascals_triangle_ii.js /** * @param {number} rowIndex * @return {number[]} */ var getRow = function(rowIndex) { var prev = [1], curr = []; if (rowIndex < 1) return prev; for (var i = 0; i <= rowIndex; i++) { for (var j = 0; j <= i; j++) { curr[j] = (prev[j-1] || 0) + (prev[j] || 0); } prev = curr.slice(); } return curr; }; <file_sep>/leetcode/687.js import { TreeNode } from './util.js'; /** * @param {TreeNode} root * @return {number} */ var longestUnivaluePath = function(root) { let result = 0; function findLength(node) { if (!node) return 0; let leftLength = findLength(node.left); let rightLength = findLength(node.right); let leftPath = rightPath = 0; if (node.left && node.left.val === node.val) { leftPath = leftLength + 1; } if (node.right && node.right.val === node.val) { rightPath = rightLength + 1; } result = Math.max(result, leftPath+rightPath); return Math.max(leftPath, rightPath); } findLength(root); return result; }; <file_sep>/stack/largest_rect.py # Largest Rectangle # www.hackerrank.com/challenges/largest-rectangle # # The following code implements the algorithm described in Problem H-4 at: # www.informatik.uni-ulm.de/acm/Locals/2003/html/judge.html import sys n = int(sys.stdin.readline()) h = sys.stdin.readline().split(' ') heights = map(int, h) max_area = 0 # Initialize [left, right] for each bar bounds = [[0, 0] for _ in range(n)] # Calculate how far right we can go from a given bar def find_right_bounds(heights): stack = [] for index, height in enumerate(heights): # Stack is empty if not stack: stack.append(index) # Current bar has a larger height than top of stack, meaning we can # go farther right elif heights[stack[-1]] < height: stack.append(index) # Current bar has a smaller height, meaning we've found the right # boundary for one or more bars currently in the stack. We remove # them from the stack and update their right bounds accordingly elif heights[stack[-1]] > height: while stack and heights[stack[-1]] > height: prev_top = stack.pop() bounds[prev_top][1] = index - prev_top stack.append(index) while stack: prev_top = stack.pop() bounds[prev_top][1] = n - prev_top # Same as find_right_bounds() but for the left direction def find_left_bounds(heights): stack = [] for index, height in reversed(list(enumerate(heights))): if not stack: stack.append(index) elif heights[stack[-1]] < height: stack.append(index) elif heights[stack[-1]] > height: while stack and heights[stack[-1]] > height: prev_top = stack.pop() bounds[prev_top][0] = prev_top - index stack.append(index) while stack: prev_top = stack.pop() bounds[prev_top][0] = prev_top + 1 if __name__ == '__main__': find_right_bounds(heights) find_left_bounds(heights) # Calculate the rectangle area for each bar and find the max for index, bound in enumerate(bounds): area = heights[index] * (bound[0] + bound[1] - 1) if area > max_area: max_area = area print max_area <file_sep>/leetcode/53.max_subarray.py import unittest class Solution(object): def max_sum(self, nums): max_sums = nums[:] for i in xrange(len(nums)): if i > 0: max_sums[i] = max(max_sums[i-1] + nums[i], nums[i]) return max(max_sums) class MaxSumTestCase(unittest.TestCase): def test_example(self): self.assertEqual(Solution().max_sum( [-2, 1, -3, 4, -1, 2, 1, -5, 4]), 6) if __name__ == '__main__': unittest.main() <file_sep>/linked_list/sum.rb # Given two non-negative integers where each is represented as a linked # list (in reverse order), output the sum as a linked list. # # Input: 3->1->5, 5->9->2 # Output: 8->0->8 require_relative '../util/util' class BigNumber attr_accessor :value, :length def initialize(str) @value = str @length = str.length end # Append (remember list is in reverse order) list with 0s where numnber of 0s # equal count. def self.append_zeros(list, count) temp = '' count.times { temp << '0' } zeros = BigNumber.new(temp) head = zeros.to_list # head -> 0 -> 0 tail = list # tail -> 4 -> 3 -> 2 -> 1 tail = tail.next while tail.next # tail -> 1 tail.next = head # 4 -> 3 -> 2 -> 1 -> 0 -> 0 list end # Convert string into a linked list, which is created in reverse order to # simplify the implementation of addition. # i.e. '1234' becomes 4 -> 3 -> 2 -> 1 def to_list digits = @value.reverse.split('') curr = prev = nil (digits.length - 1).downto(0) do |index| curr = Util::Node.new(digits[index].to_i) curr.next = prev prev = curr end curr end def +(operand) result = '' zeros_to_append = (self.length - operand.length).abs # Make two linked lists of equal length. if self.length > operand.length list1 = self.to_list list2 = BigNumber.append_zeros(operand.to_list, zeros_to_append) elsif self.length < operand.length list1 = BigNumber.append_zeros(self.to_list, zeros_to_append) list2 = operand.to_list else list1 = self.to_list list2 = operand.to_list end # Add digit by digit. while list1 digit_sum = list1.value + list2.value if list1.next list1.next.value += 1 if digit_sum > 9 result << (digit_sum % 10).to_s else # Carry over happens on last digit, simply keep the sum since there is # no 'next' digit to hold the carry over. result << digit_sum.to_s.reverse end list1, list2 = list1.next, list2.next end BigNumber.new(result.reverse) end end <file_sep>/leetcode/888.fair_candy_swap.js const _ = require('lodash'); /** * @param {number[]} A * @param {number[]} B * @return {number[]} */ var fairCandySwap = function(A, B) { let sumA = _.sum(A); let sumB = _.sum(B); let delta = Math.abs(sumA - sumB); let dA = {}, dB = {}; for (let i = 0; i < A.length; i++) { if (dA[A[i]] === undefined) { dA[A[i]] = true; } } for (let i = 0; i < B.length; i++) { if (dB[B[i]] === undefined) { dB[B[i]] = true; } } if (sumA > sumB) { for (let i = 0; i < A.length; i++) { let target = A[i] - (delta/2); if (dB[target]) return [A[i], target]; } } else { for (let i = 0; i < B.length; i++) { let target = B[i] - (delta/2); if (dA[target]) return [target, B[i]]; } } }; <file_sep>/recursion/queens_spec.rb require_relative 'queens' describe "N-Queens Tests" do describe "placeable" do before(:each) { @game = Queens.new(4) } it "same row" do @game.board = [ [1, 0, 0, 0], [0, 0, 1, 0], [0, 0, 0, 0], [0, 0, 0, 0] ] @game.send(:placeable?, 1, 1).should be_false end it "same column" do @game.board = [ [0, 0, 1, 0], [1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0] ] @game.send(:placeable?, 3, 2).should be_false end it "diagonal" do @game.board = [ [1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0] ] @game.send(:placeable?, 3, 3).should be_false end it "should be placeable" do @game.board = [ [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 0, 0], [0, 0, 0, 0] ] @game.send(:placeable?, 2, 1).should be_true end end it "1x1" do game = Queens.new(1) game.place_queen(0) game.count.should == 1 end it "2x2" do game = Queens.new(2) game.place_queen(0) game.count.should == 0 end it "4x4" do game = Queens.new(4) game.place_queen(0) game.count.should == 2 end it "8x8" do game = Queens.new(8) game.place_queen(0) game.count.should == 92 end end <file_sep>/interview_cake/merge_ranges.py import unittest def merge_ranges(ranges): if len(ranges) < 2: return ranges sorted_ranges = sorted(ranges) merged_ranges = [sorted_ranges[0]] for current_start, current_end in sorted_ranges[1:]: last_merged = merged_ranges[-1] if current_start <= last_merged[1]: last_merged = (last_merged[0], max(current_end, last_merged[1])) merged_ranges[-1] = last_merged else: merged_ranges.append((current_start, current_end)) return merged_ranges class MergeRangesTestCase(unittest.TestCase): def test_example(self): data = [(0, 1), (3, 5), (4, 8), (10, 12), (9, 10)] self.assertEqual(merge_ranges(data), [(0, 1), (3, 8), (9, 12)]) def test_subsumed(self): data = [(1, 10), (2, 6), (3, 5), (7, 9)] self.assertEqual(merge_ranges(data), [(1, 10)]) if __name__ == '__main__': unittest.main() <file_sep>/recursion/queens.rb # Find all ways of arranging N queens on a chess board so that none of them # share the same row, column or diagonal. class Queens attr_reader :count attr_accessor :board # for spec def initialize(value) @size = value @board = Array.new(value) { Array.new(value, 0) } @count = 0 end def place_queen(row) if row >= @size @count += 1 print_board return end (0..@size-1).each do |column| if placeable?(row, column) @board[row][column] = 1 place_queen(row + 1) @board[row][column] = 0 end end end private def placeable?(row, col) # Row and column (0..@size-1).each do |index| return false if @board[row][index] == 1 or @board[index][col] == 1 end # Diagonals above (1..row).each do |index| if col - index > -1 return false if @board[row-index][col-index] == 1 end if col + index < @size return false if @board[row-index][col+index] == 1 end end true end def print_board (0..@size-1).each do |i| (0..@size-1).each do |j| print @board[i][j] end puts "" end puts "" end end BOARD_SIZE = 8 game = Queens.new(BOARD_SIZE) game.place_queen(0) puts game.count <file_sep>/leetcode/236.lca.py import unittest from util import BinaryTreeNode class Solution(object): def solve(self, root, p, q): queue = [root] parents = {} while len(queue) > 0: node = queue.pop() if node.left: parents[node.left] = node queue.insert(0, node.left) if node.right: parents[node.right] = node queue.insert(0, node.right) # compute paths from root to p and q respectively p_path, q_path = [p], [q] temp = p while temp != root: p_path.append(parents[temp]) temp = parents[temp] temp = q while temp != root: q_path.append(parents[temp]) temp = parents[temp] p_path.reverse() q_path.reverse() # compare the two paths to find LCA temp = 0 while temp < min(len(p_path), len(q_path)): if p_path[temp] == q_path[temp]: temp += 1 else: return p_path[temp-1] return p_path[temp-1] class SolutionTestCase(unittest.TestCase): def test_example(self): seven = BinaryTreeNode(7) four = BinaryTreeNode(4) six = BinaryTreeNode(6) two = BinaryTreeNode(2) two.left = seven two.right = four five = BinaryTreeNode(5) five.left = six five.right = two zero = BinaryTreeNode(0) eight = BinaryTreeNode(8) one = BinaryTreeNode(1) one.left = zero one.right = eight three = BinaryTreeNode(3) three.left = five three.right = one self.assertEqual(Solution().solve(three, five, one), three) self.assertEqual(Solution().solve(three, five, four), five) self.assertEqual(Solution().solve(three, seven, eight), three) if __name__ == '__main__': unittest.main() <file_sep>/leetcode/733.js /** * @param {number[][]} image * @param {number} sr * @param {number} sc * @param {number} newColor * @return {number[][]} */ var floodFill = function(image, sr, sc, newColor) { const originalColor = image[sr][sc]; const visited = {}; fill(sr, sc, newColor); return image; function fill(row, col, color) { if (row < 0 || row > image.length-1) return; if (col < 0 || col > image[0].length-1) return; if (visited[`${row}-${col}`]) return; visited[`${row}-${col}`] = true; if (image[row][col] === originalColor) { image[row][col] = color; fill(row-1, col, color); fill(row, col-1, color); fill(row, col+1, color); fill(row+1, col, color); } } }; <file_sep>/leetcode/981.time_based_kv_store.js const _ = require('lodash'); const assert = require('assert'); /** * Initialize your data structure here. */ var TimeMap = function() { this.entries = {}; }; /** * @param {string} key * @param {string} value * @param {number} timestamp * @return {void} */ TimeMap.prototype.set = function(key, value, timestamp) { let kv = {}; kv[timestamp] = value; if (this.entries[key]) { this.entries[key].push(kv); } else { this.entries[key] = [kv]; } }; /** * @param {string} key * @param {number} timestamp * @return {string} */ TimeMap.prototype.get = function(key, timestamp) { if (!this.entries[key]) { return ''; } function getKey(entry) { return Object.keys(entry)[0]; } function getValue(entry) { return Object.values(entry)[0]; } var entries = this.entries[key]; var lo = 0; var hi = entries.length - 1; var obj; while (lo <= hi) { let mid = Math.floor((lo + hi) / 2); if (timestamp < getKey(entries[mid])) { hi = mid - 1; } else if (timestamp > getKey(entries[mid])) { lo = mid + 1; } else { return getValue(entries[mid]); } } if (hi < 0) { return ''; } return getValue(entries[hi]); }; var tm = new TimeMap(); tm.set('foo', 'bar', 1); assert(tm.get('foo', 1) === 'bar'); assert(tm.get('foo', 3) === 'bar'); tm.set('foo', 'bar2', 4); assert(tm.get('foo', 4) === 'bar2'); assert(tm.get('foo', 5) === 'bar2'); var tm2 = new TimeMap(); tm2.set('love', 'high', 10); tm2.set('love', 'low', 20); assert(tm2.get('love', 5) === ''); assert(tm2.get('love', 10) === 'high'); assert(tm2.get('love', 15) === 'high'); assert(tm2.get('love', 20) === 'low'); assert(tm2.get('love', 25) === 'low'); var tm3 = new TimeMap(); tm3.set('ctondw', 'ztpearaw', 1); tm3.set('vrobykydll', 'hwliiq', 2); tm3.set('gszaw', 'ztpearaw', 3); tm3.set('ctondw', 'gszaw', 4); assert(tm3.get('gszaw', 5) === 'ztpearaw'); assert(tm3.get('ctondw', 6) === 'gszaw'); assert(tm3.get('ctondw', 7) === 'gszaw'); assert(tm3.get('gszaw', 8) === 'ztpearaw'); assert(tm3.get('vrobykydll', 9) === 'hwliiq'); assert(tm3.get('ctondw', 10) === 'gszaw'); tm3.set('vrobykydll', 'kcvcjzzwx', 11); assert(tm3.get('vrobykydll', 12) === 'kcvcjzzwx'); <file_sep>/leetcode/257.js import { TreeNode } from "./util.js"; /** * @param {TreeNode} root * @return {string[]} */ var binaryTreePaths = function(root) { const paths = []; function findPath(node, path) { if (!node) return; if (!node.left && !node.right) { path += `${node.val}`; paths.push(path); return; } path += `${node.val}->`; findPath(node.left, path); findPath(node.right, path); } findPath(root, ''); return paths; }; // Tests const root = new TreeNode(1); root.left = new TreeNode(2); root.right = new TreeNode(3); root.left.right = new TreeNode(5); console.log(binaryTreePaths(root)); <file_sep>/leetcode/216.combination_sum_iii.py import unittest class Solution(object): def __init__(self): self.combinations = [] def combination_sum(self, k, n): def combination_helper(k, n, partial): if k == 0: if n == 0: partial.sort() if partial not in self.combinations: self.combinations.append(partial) else: remaining_set = set(range(1, 10)) - set(partial) for num in list(remaining_set): partial.append(num) combination_helper(k-1, n-num, partial[:]) partial.pop() combination_helper(k, n, []) return self.combinations class SolutionTestCase(unittest.TestCase): def test_example(self): solution = Solution().combination_sum(3, 9) self.assertEqual(len(solution), 3) self.assertIn([1, 2, 6], solution) self.assertIn([1, 3, 5], solution) self.assertIn([2, 3, 4], solution) def test_max(self): solution = Solution().combination_sum(9, 45) self.assertEqual(len(solution), 1) self.assertIn([1, 2, 3, 4, 5, 6, 7, 8, 9], solution) if __name__ == '__main__': unittest.main() <file_sep>/leetcode/658.k_closest_elements.js const assert = require('assert'); const _ = require('lodash'); // return the index of the element in arr that is closest to x function closest(arr, x) { var lo = 0, hi = arr.length-1; while (lo <= hi) { let mid = Math.floor((lo + hi) / 2); if (x < arr[mid]) { hi = mid - 1; } else if (x > arr[mid]) { lo = mid + 1; } else { return mid; } } if (hi < 0) { return lo; } if (lo > arr.length-1) { return hi; } if (Math.abs(arr[hi]-x) < Math.abs(arr[lo]-x)) { return hi; } else if (Math.abs(arr[hi]-x) > Math.abs(arr[lo]-x)) { return lo; } else { if (arr[hi] < arr[lo]) { return hi; } else { return lo; } } } /** * @param {number[]} arr * @param {number} k * @param {number} x * @return {number[]} */ var findClosestElements = function(arr, k, x) { var start = closest(arr, x); var lo = start-1, hi = start+1; var result = [arr[start]]; if (lo < 0) { return arr.slice(0, k); } if (hi >= arr.length) { return arr.slice(arr.length-k); } while (result.length < k) { let loValue = (lo > -1) ? arr[lo] : Infinity; let hiValue = (hi < arr.length) ? arr[hi] : Infinity; if (Math.abs(x-hiValue) < Math.abs(x-loValue)) { result.push(hiValue); hi++; } else { result.push(loValue); lo--; } } return _.sortBy(result); }; <file_sep>/leetcode/653.two_sum_iv.js /** * @param {TreeNode} root * @param {number} k * @return {boolean} */ var findTarget = function(root, k) { var s = new Set([]); function traverse(node) { if (!node) return false; if (s.has(k-node.val)) { return true; } else { s.add(node.val); } return traverse(node.left) || traverse(node.right); } return traverse(root); }; <file_sep>/leetcode/872.leaf_similar.js const _ = require('lodash'); /** * @param {TreeNode} root1 * @param {TreeNode} root2 * @return {boolean} */ var leafSimilar = function(root1, root2) { const s1 = [], s2 = []; getLeaves(root1, s1); getLeaves(roo2, s2); return _.isEqual(s1, s2); }; function getLeaves(root, s) { if (!root.left && !root.right) { s.push(root); return; } if (root.left) { getLeaves(root.left, s); } if (root.right) { getLeaves(root.right, s); } } <file_sep>/leetcode/90.subsets_ii.py import unittest class Solution(object): def solve(self, nums): all_subsets = [[]] remainder = nums[:] for num in nums: remainder.remove(num) result = self.solve(remainder) for item in result: subset = [num] + item subset.sort() if subset not in all_subsets: all_subsets.append(subset) return all_subsets class SolutionTestCase(unittest.TestCase): def test_example(self): solution = Solution().solve([1, 2, 2]) self.assertEqual(len(solution), 6) self.assertIn([2], solution) self.assertIn([1], solution) self.assertIn([1, 2, 2], solution) self.assertIn([2, 2], solution) self.assertIn([1, 2], solution) self.assertIn([], solution) if __name__ == '__main__': unittest.main() <file_sep>/leetcode/37.sudoku.js const assert = require('assert'); const _ = require('underscore'); const BOARD_SIZE = 9; let allPeers = {}; /** * Returns the row, column, and box given the current square * * @return [[Array], [Array], [Array]] */ function getUnits(current) { let indices = _.range(0, BOARD_SIZE); let row = _.map(indices, (num) => { return [current[0], num]; }); let column = _.map(indices, (num) => { return [num, current[1]]; }); let box = []; let r, c; switch (true) { case (current[0] < 3): r = [0, 1, 2, 0, 1, 2, 0, 1, 2]; for (let i = 0; i < BOARD_SIZE; i++) { box.push([r[i], undefined]); } break; case (current[0] < 6): r = [3, 4, 5, 3, 4, 5, 3, 4, 5]; for (let i = 0; i < BOARD_SIZE; i++) { box.push([r[i], undefined]); } break; case (current[0] < 9): r = [6, 7, 8, 6, 7, 8, 6, 7, 8]; for (let i = 0; i < BOARD_SIZE; i++) { box.push([r[i], undefined]); } break; } switch (true) { case (current[1] < 3): c = [0, 0, 0, 1, 1, 1, 2, 2, 2]; for (let i = 0; i < BOARD_SIZE; i++) { box[i][1] = c[i]; } break; case (current[1] < 6): c = [3, 3, 3, 4, 4, 4, 5, 5, 5]; for (let i = 0; i < BOARD_SIZE; i++) { box[i][1] = c[i]; } break; case (current[1] < 9): c = [6, 6, 6, 7, 7, 7, 8, 8, 8]; for (let i = 0; i < BOARD_SIZE; i++) { box[i][1] = c[i]; } break; } return [row, column, box]; } function unitsWithoutSelf(units, current) { let result = []; units = _.flatten(units, true); // flatten one level for (let i = 0; i < units.length; i++) { if (!_.isEqual(units[i], [current[0], current[1]])) { result.push(units[i]); } } return result; } function getAllPeers(board) { let result = {}; for (var i = 0; i < BOARD_SIZE; i++) { for (var j = 0; j < BOARD_SIZE; j++) { let current = [i, j]; let units = getUnits(current); result[JSON.stringify(current)] = unitsWithoutSelf(units, current); } } return result; } function validate(board, row, col, value) { let peers = allPeers[JSON.stringify([row, col])]; for (let p of peers) { let peerRow = p[0]; let peerCol = p[1]; if (board[peerRow][peerCol] === value) { return false; } } return true; } function nextSquare(board) { for (let i = 0; i < BOARD_SIZE; i++) { for (let j = 0; j < BOARD_SIZE; j++) { if (board[i][j] === '.') { return [i, j]; } } } return false; } function solve(board) { let next = nextSquare(board); let row = next[0]; let col = next[1]; let candidates = ['1', '2', '3', '4', '5', '6', '7', '8', '9']; if (!next) { return true; // solved } for (let candidate of candidates) { if (validate(board, row, col, candidate)) { board[row][col] = candidate; if (solve(board)) { return true; } board[row][col] = '.'; } } return false; } var solveSudoku = function(board) { allPeers = getAllPeers(board); solve(board); }; var board = [ ['5', '3', '.', '.', '7', '.', '.', '.', '.'], ['6', '.', '.', '1', '9', '5', '.', '.', '.'], ['.', '9', '8', '.', '.', '.', '.', '6', '.'], ['8', '.', '.', '.', '6', '.', '.', '.', '3'], ['4', '.', '.', '8', '.', '3', '.', '.', '1'], ['7', '.', '.', '.', '2', '.', '.', '.', '6'], ['.', '6', '.', '.', '.', '.', '2', '8', '.'], ['.', '.', '.', '4', '1', '9', '.', '.', '5'], ['.', '.', '.', '.', '8', '.', '.', '7', '9'] ]; solveSudoku(board); <file_sep>/leetcode/852.mountain_peak_index.js /** * @param {number[]} A * @return {number} */ var peakIndexInMountainArray = function(A) { var lo = 0, hi = A.length-1; while (lo <= hi) { let mid = Math.floor((lo+hi) / 2); let pred = A[mid-1] || -Infinity, succ = A[mid+1] || -Infinity; if (pred < A[mid] && A[mid] < succ) { lo = mid + 1; } else if (pred > A[mid] && A[mid] > succ) { hi = mid - 1; } else { return mid; } } }; console.log(peakIndexInMountainArray([0, 2, 1, 0])); <file_sep>/interview_cake/balanced_binary_tree.py import unittest from util import BinaryTreeNode def superbalanced(tree): if tree is None: return True depths = [] # keep track of all leaves depth, short circuit when possible nodes = [(tree, 0)] # treat this as a stack while len(nodes): node, depth = nodes.pop() if (not node.left) and (not node.right): if depth not in depths: depths.append(depth) if (len(depths) > 2 or (len(depths) == 2 and abs( depths[0] - depths[1]) > 1)): return False else: if node.right: nodes.append((node.right, depth+1)) if node.left: nodes.append((node.left, depth+1)) return True class BalancedBinaryTreeTestCase(unittest.TestCase): def test_balanced(self): tree = BinaryTreeNode(0) tree.insert_left(1) tree.insert_right(2) tree.left.insert_left(3) tree.left.insert_right(4) tree.left.right.insert_left(5) tree.left.right.insert_right(6) tree.right.insert_right(7) self.assertTrue(superbalanced(tree)) def test_unbalanced(self): tree = BinaryTreeNode(0) tree.insert_left(1) tree.insert_right(2) tree.left.insert_left(3) tree.left.insert_right(4) tree.left.right.insert_left(5) tree.left.right.insert_right(6) self.assertFalse(superbalanced(tree)) if __name__ == '__main__': unittest.main() <file_sep>/string/anagrams.rb # Check if two strings are anagrams. STRING_ONE = 'cinema' STRING_TWO = 'iceman' def anagrams? s1, s2 return false if s1.length != s2.length a1 = s1.split('').sort a2 = s2.split('').sort a1 == a2 end if anagrams? STRING_ONE, STRING_TWO puts "#{STRING_ONE} and #{STRING_TWO} are anagrams" else puts "#{STRING_ONE} and #{STRING_TWO} aren't anagrams" end <file_sep>/sorting/heap_sort.c /** * Heap (binary) sort implemented on an array. * This program sorts the input integers in ascending order by maintaining * a max-heap while popping its root. */ #include <stdio.h> /* * This method makes subtree rooted at i become a max-heap, with assumption * that the left subtree and right subtree of h[i] are max-heaps, but h[i] * may be smaller than its children. */ void max_heapify(int h[], int i, int size) { int lc = 2 * i; int rc = 2 * i + 1; int max = i; if (h[i] < h[lc] && lc <= size) max = lc; if (h[max] < h[rc] && rc <= size) max = rc; if (max != i) { int temp; temp = h[i]; h[i] = h[max]; h[max] = temp; max_heapify(h, max, size); } } void build_max_heap(int h[], int size) { int i; for (i = size/2; i > 0; i--) max_heapify(h, i, size); } int main() { int n; printf("Enter the number of items to be sorted: "); scanf("%d", &n); if (n < 1) { printf("Invalid input.\n"); return 1; } /* To satisfy left(i) == 2*i the root should be placed at a[1] not a[0] */ int a[n+1]; int i; printf("Enter %d items below:\n", n); for (i = 1; i < n+1; i++) scanf("%d", &a[i]); int size = n; build_max_heap(a, size); int temp; for (i = n; i > 1; i--) { temp = a[1]; a[1] = a[i]; a[i] = temp; size--; max_heapify(a, 1, size); } /* Display the output */ for (i = 1; i < n+1; i++) { if (i != n) printf("%d ", a[i]); else printf("%d\n", a[i]); } } <file_sep>/string/reverse.c /** * Reverse a C-style string. * e.g. "abcd" is represented as five characters including the null character. */ #include <stdio.h> /* * Reverse string */ void reverse(char *s, char *r, int size) { int i, j; r[size - 1] = '\0'; for (i = size - 2, j = 0; i >= 0; i--, j++) { r[i] = *(s + j); } } /* * Reverse string in place */ void reverse_in_place(char *s) { char tmp; char *head = s, *tail = s; while (*tail != '\0') { tail++; } tail--; while (head < tail) { tmp = *tail; *tail = *head; *head = tmp; head++; tail--; } } /* * Find string size (including the null character at the end) */ int find_size(char *s) { int size = 0; char *curr = s; while (*curr != '\0') { size++; curr++; } return size + 1; } int main() { char original[] = "world"; if (original == NULL) return 0; int size = find_size(original); char reversed[size]; //reverse(original, reversed, size); reverse_in_place(original); int i; for (i = 0; i < size; i++) { printf("%c", original[i]); } printf("\n"); } <file_sep>/leetcode/26.remove_duplicates_from_sorted_array.js /** * @param {number[]} nums * @return {number} */ var removeDuplicates = function(nums) { if (nums.length < 2) return nums.length; var p1 = 0, p2 = 1; while (p2 < nums.length) { if (nums[p1] === nums[p2]) { nums.splice(p2, 1); } else { p1++; p2++; } } return nums.length; }; <file_sep>/leetcode/617.merge_bst.js import { TreeNode } from './util.js'; /** * @param {TreeNode} t1 * @param {TreeNode} t2 * @return {TreeNode} */ var mergeTrees = function(t1, t2) { return merge(t1, t2, null); }; function merge(t1, t2, t) { if (t1 === null && t2 === null) { return; } else if (t1 === null) { return t2; } else if (t2 === null) { return t1; } else { t = new TreeNode(t1.val + t2.val); t.left = merge(t1.left, t2.left, t); t.right = merge(t1.right, t2.right, t); return t; } } const t1 = new TreeNode(1); t1.left = new TreeNode(3); t1.left.left = new TreeNode(5); t1.right = new TreeNode(2); const t2 = new TreeNode(2); t2.left = new TreeNode(1); t2.left.right = new TreeNode(4); t2.right = new TreeNode(3); t2.right.right = new TreeNode(7); const t = mergeTrees(t1, t2); t.print(); <file_sep>/recursion/hanoi.rb # Tower of Hanoi solved with recursion. require_relative '../util/util' class Stack < Util::Stack attr_reader :name def initialize(name) @top = nil @name = name end end class Hanoi def initialize(value) @a = Stack.new("A") @b = Stack.new("B") @c = Stack.new("C") @num = value disks = Array(1..value) disks.reverse.each { |disk| @a.push(disk) } end # To move n disks from peg A to peg C: # 1. move n−1 disks from A to B. This leaves disk n alone on peg A # 2. move disk n from A to C # 3. move n−1 disks from B to C so they sit on disk n def move(num, src, dest, buffer) if num > 0 move(num - 1, src, buffer, dest) bottom = src.pop if dest.peek.nil? || bottom <= dest.peek dest.push(bottom) puts "Move disk #{bottom} from #{src.name} to #{dest.name}" else raise "Cannot place a larger disk on top of a smaller disk." end move(num - 1, buffer, dest, src) end end def runner move(@num, @a, @c, @b) end end NUM_OF_DISKS = 3 h = Hanoi.new(NUM_OF_DISKS) h.runner <file_sep>/leetcode/139.word_break.py import unittest class Solution(object): def word_break(self, s, word_list): d = [False] * len(s) for i in range(len(s)): for word in word_list: if word == s[i-len(word)+1:i+1] and ( d[i-len(word)] or i-len(word) == -1): d[i] = True break return d[-1] class WordBreakTestCase(unittest.TestCase): def test_example(self): s = 'leetcode' word_list = ['leet', 'code'] self.assertTrue(Solution().word_break(s, word_list)) if __name__ == '__main__': unittest.main() <file_sep>/leetcode/724.pivot_index.js /** * @param {number[]} nums * @return {number} */ var pivotIndex = function(nums) { if (nums.length < 2) return -1; var s = { 0: [0, null] }; for (let i = 1; i < nums.length; i++) { s[i] = [s[i-1][0] + nums[i-1], null]; } s[nums.length-1][1] = 0; for (let i = nums.length-2; i > -1; i--) { s[i][1] = s[i+1][1] + nums[i+1]; } for (let key in s) { if (s[key][0] === s[key][1]) return parseInt(key); } return -1; }; <file_sep>/hash_table/chaining.c /* * Hash table with collision resolution by chaining. * All elements that hash to the same slot are contained in a linked list. * * This program is the solution to problem 11.2-2 * * h(k) = k mod 9 * To be inserted: [5, 28, 19, 15, 20, 33, 12, 17, 10] * After insertion: * 0 | * 1 | 10 -> 19 -> 28 * 2 | 20 * 3 | 12 * 4 | * 5 | 5 * 6 | 33 -> 15 * 7 | * 8 | 17 */ #include <stdio.h> #include <stdlib.h> #define TABLE_SIZE 9 typedef struct node { int value; struct node *next; } node; void insert(struct node *T[], int x) { node *temp = (node *)malloc(sizeof(node)); temp->value = x; int i; i = x % TABLE_SIZE; if (T[i] == NULL) { temp->next = NULL; } else { temp->next = T[i]; } T[i] = temp; } /* * Return node x if found, return NULL otherwise */ struct node* search(struct node *T[], int x) { node *temp = T[x % TABLE_SIZE]; while (temp != NULL) { if (temp->value == x) return temp; temp = temp->next; } return NULL; } /* * Delete the first occurrence found * Return 0 on success, return -1 otherwise */ int delete(struct node *T[], int x) { node *curr = T[x % TABLE_SIZE]; /* Case: empty list */ if (curr == NULL) return -1; /* Case: first element is the one to be deleted */ if (curr->value == x) { free(curr); curr = NULL; return 0; } /* Case: general */ node *prev = curr; curr = curr->next; while (curr != NULL) { if (curr->value == x) { prev->next = curr->next; free(curr); curr = NULL; return 0; } curr = curr->next; prev = prev->next; } return -1; } void display(struct node *T[]) { printf("Hash Table:\n"); int i; for (i = 0; i < TABLE_SIZE; i++) { node *temp = T[i]; if (temp == NULL) printf("%d |\n", i); else printf("%d | ", i); while (temp != NULL) { if (temp->next == NULL) { printf("%d\n", temp->value); break; } printf("%d -> ", temp->value); temp = temp->next; } } } int main() { /* Hash table */ struct node *h[TABLE_SIZE]; int test[TABLE_SIZE] = { 5, 28, 19, 15, 20, 33, 12, 17, 10 }; int i; /* Initialize the hash table */ for (i = 0; i < TABLE_SIZE; i++) { h[i] = NULL; } /* Test insertion */ for (i = 0; i < TABLE_SIZE; i++) { insert(h, test[i]); } display(h); /* Test search */ node *search_result; search_result = search(h, 15); if (search_result->value == 15) printf("Test for search on success PASSED.\n"); else printf("Test for search on success FAILED.\n"); search_result = search(h, 87); if (search_result == NULL) printf("Test for search on failure PASSED.\n"); else printf("Test for search on failure FAILED.\n"); /* Test delete */ int delete_result; delete_result = delete(h, 19); if (delete_result == 0) printf("Test for delete on success PASSED.\n"); else printf("Test for delete on success FAILED.\n"); delete_result = delete(h, 87); if (delete_result == -1) printf("Test for delete on failure PASSED.\n"); else printf("Test for delete on failure FAILED.\n"); display(h); } <file_sep>/leetcode/49.group_anagrams.py import unittest class Solution(object): def solve(self, strs): result = [] groups = {} for s in strs: key = ''.join(sorted(s)) try: groups[key] except KeyError: groups[key] = [s] else: groups[key].append(s) for k, v in groups.iteritems(): result.append(v) return result class SolutionTestCase(unittest.TestCase): def test_example(self): words = ['eat', 'tea', 'tan', 'ate', 'nat', 'bat'] expect = [['ate', 'eat', 'tea'], ['nat', 'tan'], ['bat']] self.assertEqual(Solution().solve(words), expect) if __name__ == '__main__': unittest.main() <file_sep>/interview_cake/queue_two_stacks.py from util import Stack class Queue2Stacks: def __init__(self): self.in_stack = Stack() self.out_stack = Stack() def enqueue(self, item): self.in_stack.push(item) def dequeue(self): item = self.out_stack.pop() if item is None: # if out_stack is empty, import everything from in_stack then pop while True: temp = self.in_stack.pop() if temp is None: # queue is empty break else: self.out_stack.push(temp) self.out_stack.pop() <file_sep>/leetcode/485.max_consecutive_ones.js /** * @param {number[]} nums * @return {number} */ var findMaxConsecutiveOnes = function(nums) { var maxLen = -Infinity; var currLen = 0; for (let i = 0; i < nums.length; i++) { if (nums[i] === 0) { if (currLen > maxLen) maxLen = currLen; currLen = 0; } else { currLen++; } } return Math.max(maxLen, currLen); }; <file_sep>/stack/sort_spec.rb require_relative 'sort' describe "Tests for sort a stack: " do it "should sort the stack in ascending order" do stack = Util::Stack.new array = [3, 1, 4, 1, 5, 9, 2, 6, 5] array2 = [] array.each { |element| stack.push(element) } result = SortStack.sort(stack) array.length.times { array2 << result.pop } array2.should == array.sort end end <file_sep>/leetcode/93.ip_addresses.py import unittest class Solution(object): def __init__(self): self.result = [] def backtrack(self, k, s, partial): if k > 3: if len(s) < 1: self.result.append(partial[:-1]) return else: for i in range(1, 4): if i > len(s): continue if i == 1: self.backtrack(k+1, s[i:], partial + s[0:i] + '.') elif i == 2 and s[0] != '0': self.backtrack(k+1, s[i:], partial + s[0:i] + '.') elif i == 3 and s[0] != '0' and int(s[0:3]) < 256: self.backtrack(k+1, s[i:], partial + s[0:i] + '.') def solve(self, s): self.backtrack(0, s, '') return self.result class SolutionTestCase(unittest.TestCase): def test_example(self): ip_addresses = Solution().solve('25525511135') self.assertEqual(len(ip_addresses), 2) self.assertIn('255.255.11.135', ip_addresses) self.assertIn('255.255.111.35', ip_addresses) if __name__ == '__main__': unittest.main() <file_sep>/leetcode/261.graph_valid_tree.py import unittest class Solution(object): def solve(self, n, edges): # build graph with given edges neighbors = {i: [] for i in range(n)} for v1, v2 in edges: neighbors[v1].append(v2) neighbors[v2].append(v1) # traverse the graph with DFS while updating visited visited = set() visited.add(0) stack = neighbors[0] while len(stack) > 0: node = stack.pop() for item in neighbors[node]: if item not in visited: stack.append(item) visited.add(node) return len(edges) == n-1 and len(visited) == n class SolutionTestCase(unittest.TestCase): def test_valid(self): edges = [[0, 1], [0, 2], [0, 3], [1, 4]] self.assertTrue(Solution().solve(5, edges)) def test_invalid(self): edges = [[0, 1], [1, 2], [2, 3], [1, 3], [1, 4]] self.assertFalse(Solution().solve(5, edges)) def test_disconnected(self): edges = [[0, 1], [0, 4], [1, 4], [2, 3]] self.assertFalse(Solution().solve(5, edges)) def test_valid2(self): edges = [[0, 1], [0, 2], [2, 5], [3, 4], [3, 5]] self.assertTrue(Solution().solve(6, edges)) if __name__ == '__main__': unittest.main() <file_sep>/leetcode/746.min_cost_climbing_stairs.js /** * @param {number[]} cost * @return {number} */ var minCostClimbingStairs = function(cost) { if (cost.length < 3) return Math.min(...cost); let a = [cost[0], cost[1]]; for (let i = 2; i < cost.length; i++) { a[i] = Math.min(cost[i] + a[i-1], cost[i] + a[i-2]); } return Math.min(a[cost.length-1], a[cost.length-2]); }; <file_sep>/interview_cake/find_rotation.py import unittest def find_rotation(words): lower, upper = 0, len(words)-1 while lower < upper: mid = (upper-lower) / 2 + lower if words[lower][0] > words[mid][0]: upper = mid else: lower = mid + 1 return lower class FindRotationTestCase(unittest.TestCase): def test_example(self): words = [ 'ptolemaic', 'retrograde', 'supplant', 'undulate', 'xenoepist', 'asymptote', # <-- rotates here! 'babka', 'banoffee', 'engender', 'karpatka', 'othellolagkage'] self.assertEqual(find_rotation(words), 5) if __name__ == '__main__': unittest.main() <file_sep>/leetcode/496.next_greater_element_i.js /** * @param {number[]} nums1 * @param {number[]} nums2 * @return {number[]} */ var nextGreaterElement = function(nums1, nums2) { let result = []; let dict = {}; for (let i = 0; i < nums2.length; i++) { dict[nums2[i]] = nums2.slice(i+1); } for (let i = 0; i < nums1.length; i++) { let candidates = dict[nums1[i]]; if (candidates.length < 1) { result[i] = -1; continue; } for (let j = 0; j < candidates.length; j++) { if (candidates[j] > nums1[i]) { result[i] = candidates[j]; break; } if (j === candidates.length-1) result[i] = -1; } } return result; }; <file_sep>/skiena/2-1.c /* 2-1 Primary Arithmetic */ #include <stdio.h> #include <stdlib.h> #include <string.h> /* Right zero padding to 10 characters */ char *zero_pad10(char *n) { /* 10 includes null character */ char *padded = (char *)malloc(10); strcpy(padded, n); int i; for (i = 1; i < 10-strlen(n); i++) { strcat(padded, "0"); } return padded; } int carry_count(char *a, char *b) { int count = 0; /* Make sure a and b have the same length */ char *padded_a = zero_pad10(a); char *padded_b = zero_pad10(b); /* Add up each digit */ int test = 1; while (*padded_a != '\0') { int sum; sum = ((int)*padded_a - '0') + ((int)*padded_b - '0'); if (sum > 9) { count++; } padded_a++; padded_b++; } return count; } int main() { size_t buffer = 32; /* Assume each input line is 32 bytes */ char *input; char *num1, *num2; input = (char *)malloc(buffer); while (getline(&input, &buffer, stdin) > 0) { int count; char *line = strdup(input); num1 = strsep(&line, " "); num2 = strsep(&line, "\n"); if (*num1 == '0' || *num2 == '0') { break; } count = carry_count(num1, num2); if (count <= 0) { printf("No carry operation.\n"); } else { printf("%d carry operation.\n", count); } } return 0; } <file_sep>/leetcode/78.subsets.py import unittest class Solution(object): def subsets(self, nums): all_subsets = [[]] remainder = nums[:] for num in nums: remainder.remove(num) result = self.subsets(remainder) for item in result: subset = [num] + item all_subsets.append(subset) return all_subsets class SolutionTestCase(unittest.TestCase): def test_example(self): all_subsets = Solution().subsets([1, 2, 3, 4]) self.assertEqual(len(all_subsets), 16) if __name__ == '__main__': unittest.main() <file_sep>/leetcode/884.uncommon_words.js /** * @param {string} A * @param {string} B * @return {string[]} */ var uncommonFromSentences = function(A, B) { let h1 = {}, h2 = {}; A = A.split(' '); B = B.split(' '); for (let word of A) { if (h1[word]) { h1[word]++; } else { h1[word] = 1; } } for (let word of B) { if (h2[word]) { h2[word]++; } else { h2[word] = 1; } } let result = []; for (let word of A) { if (h1[word] === 1 && !h2[word]) { result.push(word); } } for (let word of B) { if (h2[word] === 1 && !h1[word]) { result.push(word); } } return result; }; <file_sep>/interview_cake/highest_product.py import unittest def highest_product(values): if len(values) < 3: raise Exception('Too few items in the list.') highest = max(values[0], values[1]) lowest = min(values[0], values[1]) highest_product_2 = values[0] * values[1] lowest_product_2 = values[0] * values[1] highest_product_3 = values[0] * values[1] * values[2] values = values[2:] # start from the 3rd item for current in values: highest_product_3 = max( highest_product_3, current * highest_product_2, current * lowest_product_2) highest_product_2 = max( highest_product_2, current * highest, current * lowest) highest = max(highest, current) lowest_product_2 = min( lowest_product_2, current * highest, current * lowest) lowest = min(lowest, current) return highest_product_3 class HighestProductTestCase(unittest.TestCase): def test_negative_numbers(self): data = [-10, -10, 1, 3, 2] self.assertEqual(highest_product(data), 300) def test_last_item_yield(self): data = [1, 10, -5, 1, -100] self.assertEqual(highest_product(data), 5000) def test_normal(self): data = [4, 5, 1, 3, 1] self.assertEqual(highest_product(data), 60) if __name__ == '__main__': unittest.main() <file_sep>/leetcode/700.search_bst.js /** * @param {TreeNode} root * @param {number} val * @return {TreeNode} */ var searchBST = function(root, val) { if (root === null) return null; if (root.val === val) { return root.val; } return searchBST(root.left, val) || searchBST(root.right, val); }; <file_sep>/util/graph_spec.rb require_relative 'graph' module Util describe "Graph Tests: " do # A # / \ # B C # | / | # D - F - G # | # H - E before(:each) do @graph = Graph.new(directed: false) @a = Vertex.new("A") @b = Vertex.new("B") @c = Vertex.new("C") @d = Vertex.new("D") @e = Vertex.new("E") @f = Vertex.new("F") @g = Vertex.new("G") @h = Vertex.new("H") @ab = Edge.new(head: @a, tail: @b) @ac = Edge.new(head: @a, tail: @c) @bf = Edge.new(head: @b, tail: @f) @cg = Edge.new(head: @c, tail: @g) @cf = Edge.new(head: @c, tail: @f) @fd = Edge.new(head: @f, tail: @d) @fg = Edge.new(head: @f, tail: @g) @fh = Edge.new(head: @f, tail: @h) @he = Edge.new(head: @h, tail: @e) [@a, @b, @c, @d, @e, @f, @g, @h].each { |v| @graph.add(v) } [@ab, @ac, @bf, @cf, @cg, @fd, @fg, @fh, @he].each { |e| @graph.add(e) } end it "should properly build the graph" do @graph.vertices.should have(8).nodes @graph.edges.should have(9).edges @a.neighbors.should == [@b, @c] @b.neighbors.should == [@a, @f] @c.neighbors.should == [@a, @f, @g] @d.neighbors.should == [@f] @e.neighbors.should == [@h] @f.neighbors.should == [@b, @c, @d, @g, @h] @g.neighbors.should == [@c, @f] @h.neighbors.should == [@f, @e] end it "should traverse the graph using DFS" do @graph.dfs(@a).should == ["A", "B", "F", "C", "G", "D", "H", "E"] @graph.dfs(@c).should == ["C", "A", "B", "F", "D", "G", "H", "E"] end it "should traverse the graph using BFS" do @graph.bfs(@a).should == ["A", "B", "C", "F", "G", "D", "H", "E"] @graph.bfs(@c).should == ["C", "A", "F", "G", "B", "D", "H", "E"] end end end <file_sep>/leetcode/5.longest_palindromic_substr.py import unittest class Solution(object): def palindromic(self, s): return s == s[::-1] def solve(self, s): a = [1] * len(s) for i in range(1, len(s)): # find out how far back we need to look last = a[i-1] start = max(i - 1 - last, 0) # from that position on, look at each substring up until the # current position to find the longest palindromic one for j in range(start, i): temp = s[j:i+1] if self.palindromic(temp) and len(temp) > a[i]: a[i] = len(temp) max_len = max(a) position = a.index(max_len) return s[position-max_len+1:position+1] class SolutionTestCase(unittest.TestCase): def test_example(self): s = Solution().solve('babad') self.assertIn(s, ['aba', 'bab']) if __name__ == '__main__': unittest.main() <file_sep>/string/all_unique.c /** * Implement an algorithm to determine if a string has all unique characters. * What if you can not use additional data structures? */ #include <stdio.h> /* * Relaxed condition * Use an extra array to hold character count */ int all_unique(char *s, int size) { // Assume all characters are ASCII int char_set[256]; int i; for (i = 0; i < 256; i++) { char_set[i] = 0; } for (i = 0; i < size; i++) { int curr_char = (int)s[i]; if (char_set[curr_char]) { return 0; } char_set[curr_char] = 1; } return 1; } /* * Somewhat strict condition * Use a single 32-bit int to hold character count, assuming charset is 'a' - 'z' */ int all_unique_bitwise(char *s, int size) { int i; int char_set = 0; for (i = 0; i < size; i++) { int curr_char = (int)s[i] - (int)'a'; if ((char_set & (1 << curr_char)) > 0) { return 0; } char_set |= (1 << curr_char); } return 1; } int main() { printf("string returns %d\n", all_unique("string", 6)); printf("hello returns %d\n", all_unique("hello", 5)); printf("goran returns %d\n", all_unique_bitwise("goran", 5)); printf("maximize returns %d\n", all_unique_bitwise("maximize", 8)); } <file_sep>/leetcode/17.letter_combination_of_number.py import unittest class Solution(object): def generate(self, base, letters): result = [] for i in base: for j in letters: result.append(i+j) return result def solve(self, digits): if len(digits) < 1: return [] dictionary = { '2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz', } self.combo = list(dictionary[digits[0]]) for i in range(1, len(digits)): digit = digits[i] letters = dictionary[digit] self.combo = self.generate(self.combo, letters) return self.combo class SolutionTestCase(unittest.TestCase): def test_example(self): self.assertEqual(Solution().solve('23'), [ 'ad', 'ae', 'af', 'bd', 'be', 'bf', 'cd', 'ce', 'cf']) if __name__ == '__main__': unittest.main() <file_sep>/linked_list/circular.rb # Given a linked list, return the node at the beginning of the loop. # # Input: A (where A -> B -> C -> D -> E -> C) # Output: C class Node attr_accessor :next def initialize end end class Circular # Algorithm for finding the beginning of the loop: # 0. Return false if at any point current_node.next is nil # 1. Set up two pointers p1 and p2 so that p2 moves twice as fast as p1; # 2. Traverse the list until p1 and p2 meet; # 3. Keep p2 at its current position and move p1 to the start of the list; # 4. Move both pointers at the same pace (one node at a time) until they meet again; # 5. The node they are at is the beginning of the loop. def self.has_circle?(head) p1 = p2 = head while p1 = p1.next p2 = p2.next.next rescue break # in case list doesn't have loop if p1.equal?(p2) p1 = head while !p1.equal?(p2) p1 = p1.next p2 = p2.next end return p1 end end false end end <file_sep>/leetcode/47.permutations_ii.py class Solution(object): def __init__(self): self.permutations = {} def permute(self, nums, partial): if len(nums) == 0: self.permutations[tuple(partial)] = True return for num in nums: next_nums = nums[:] next_partial = partial[:] next_nums.remove(num) next_partial.append(num) self.permute(next_nums, next_partial) def solve(self, nums): self.permute(sorted(nums), []) return self.permutations.keys() if __name__ == '__main__': print Solution().solve([1, 1, 2]) <file_sep>/sorting/anagrams.rb # Group anagrams together in a collection of words. class Anagrams attr_reader :words def initialize(words) @words = words end def sort! quick_sort(0, @words.length-1) end private def quick_sort(left, right) pivot = nil if left < right pivot = partition(left, right) quick_sort(left, pivot - 1) quick_sort(pivot + 1, right) end end def partition(left, right) pivot = (left + right) / 2 retval = left # final pisotion for pivot @words[pivot], @words[right] = @words[right], @words[pivot] (left..right - 1).each do |i| if @words[i].alphabetize < @words[right].alphabetize @words[i], @words[retval] = @words[retval], @words[i] retval += 1 end end @words[right], @words[retval] = @words[retval], @words[right] retval end end class String def alphabetize chars = self.split("") chars = sort! chars.join end end <file_sep>/leetcode/2.add_two_numbers.py import unittest from util import ListNode class Solution(object): def solve(self, l1, l2): if l1 is None: return l2 elif l2 is None: return l1 # both l1 and l2 have at least 1 node curr = prev = head = ListNode(l1.val + l2.val) curr = ListNode(0) l1 = l1.next l2 = l2.next while (l1 is not None) and (l2 is not None): curr.val = l1.val + l2.val prev.next = curr l1 = l1.next l2 = l2.next curr = ListNode(0) prev = prev.next if l1 is None: prev.next = l2 if l2 is None: prev.next = l1 # take care of carry over curr = head prev = None carry = 0 while curr is not None: curr.val += carry if curr.val > 9: carry = curr.val / 10 curr.val %= 10 else: carry = 0 if curr.next is None: prev = curr curr = curr.next if carry > 0: curr = ListNode(carry) prev.next = curr return head class SolutionTestCase(unittest.TestCase): def test_example(self): node1 = ListNode(4) node2 = ListNode(3) node1.next = node2 node2.next = None node3 = ListNode(5) node4 = ListNode(6) node5 = ListNode(4) node3.next = node4 node4.next = node5 node5.next = None head = Solution().solve(node1, node3) self.assertEqual(head.val, 9) head = head.next self.assertEqual(head.val, 9) head = head.next self.assertEqual(head.val, 4) head = head.next self.assertIs(head, None) def test_carry(self): node1 = ListNode(9) node2 = ListNode(9) node3 = ListNode(9) node1.next = node2 node2.next = node3 node3.next = None node4 = ListNode(1) head = Solution().solve(node1, node4) self.assertEqual(head.val, 0) head = head.next self.assertEqual(head.val, 0) head = head.next self.assertEqual(head.val, 0) head = head.next self.assertEqual(head.val, 1) head = head.next self.assertIs(head, None) if __name__ == '__main__': unittest.main() <file_sep>/leetcode/85.max_rectangle.py import unittest class Solution(object): def solve(self, matrix): if matrix is None or len(matrix) < 1: return 0 length, width = len(matrix), len(matrix[0]) left, right = [0] * width, [width] * width height = [0] * width result = 0 for i in range(length): curr_left, curr_right = 0, width # calculate left boundary for j in range(width): if matrix[i][j] == '1': left[j] = max(left[j], curr_left) else: left[j] = 0 curr_left = j + 1 # calculate right boundary for j in reversed(range(width)): if matrix[i][j] == '1': right[j] = min(right[j], curr_right) else: right[j] = width curr_right = j # calculate height for j in range(width): if matrix[i][j] == '1': height[j] += 1 else: height[j] = 0 area = [(right[k] - left[k]) * height[k] for k in range(width)] result = max(result, max(area)) return result class SolutionTestCase(unittest.TestCase): def test_example(self): m = ['11001', '01001', '00111', '00111', '00001'] self.assertEqual(Solution().solve(m), 6) def test_first(self): m = ['10100', '10111', '11111', '10010'] self.assertEqual(Solution().solve(m), 6) if __name__ == '__main__': unittest.main() <file_sep>/interview_cake/reverse_linked_list.py import unittest from util import LinkedListNode def reverse(head): if head.next is None: return head if head.next.next is None: head.next.next = head new_head = head.next head.next = None return new_head # there are at least 3 nodes prev = head curr = head.next next = curr.next prev.next = None while next: curr.next = prev prev = curr curr = next next = next.next curr.next = prev return curr class ReverseLinkedListTestCase(unittest.TestCase): def test_example(self): head = LinkedListNode(1) head.next = LinkedListNode(2) head.next.next = LinkedListNode(3) head.next.next.next = LinkedListNode(4) head.next.next.next.next = LinkedListNode(5) head = reverse(head) self.assertEqual(head.value, 5) head = head.next self.assertEqual(head.value, 4) head = head.next self.assertEqual(head.value, 3) head = head.next self.assertEqual(head.value, 2) head = head.next self.assertEqual(head.value, 1) head = head.next self.assertEqual(head, None) if __name__ == '__main__': unittest.main() <file_sep>/interview_cake/fibonacci.py import unittest memo = {} def fibonacci(n): """using memoization""" if n < 2: return n if n in memo: return memo[n] else: value = fibonacci(n-1) + fibonacci(n-2) memo[n] = value return value def fib(n): """dynamic programming""" f = [0] * (n+1) f[1] = 1 for i in range(2, n+1): f[i] = f[i-1] + f[i-2] return f[n] class FibonacciTestCase(unittest.TestCase): def test_20(self): self.assertEqual(fibonacci(20), 6765) self.assertEqual(fib(20), 6765) def test_23(self): self.assertEqual(fibonacci(23), 28657) self.assertEqual(fib(23), 28657) def test_24(self): self.assertEqual(fibonacci(24), 46368) self.assertEqual(fib(24), 46368) def test_137(self): self.assertEqual(fibonacci(137), 19134702400093278081449423917) self.assertEqual(fib(137), 19134702400093278081449423917) if __name__ == '__main__': unittest.main() <file_sep>/heap/heap_spec.rb require_relative 'heap' describe "Heap tests" do it "should initialize with valid argument" do expect { Heap.new(:invalid) }.to raise_error(ArgumentError) expect { Heap.new(:max) }.to_not raise_error end it "should max heapify" do h = Heap.new(:max) h.data = [nil, 100, 19, 36, 17, 3, 25, 1, 2, 92] (h.data.length / 2).downto(1) { |index| h.heapify(index) } h.data.should == [nil, 100, 92, 36, 19, 3, 25, 1, 2, 17] end it "should min heapify" do h = Heap.new(:min) h.data = [nil, 10, 12, 50, 13, 14, 99, 51, 6] (h.data.length / 2).downto(1) { |index| h.heapify(index) } h.data.should == [nil, 6, 10, 50, 12, 14, 99, 51, 13] end it "should support heap sort" do h = Heap.new(:max) array = [6, 5, 3, 1, 8, 7, 2, 4] array.each { |el| h.insert(el) } (h.data.length / 2).downto(1) { |index| h.heapify(index) } h.data.should == [nil, 8, 6, 7, 4, 5, 3, 2, 1] (array.length - 1).downto(0) do |index| h.data[1], h.data[index+1] = h.data[index+1], h.data[1] array[index] = h.data.pop (h.data.length / 2).downto(1) { |i| h.heapify(i) } end array.should == [1, 2, 3, 4, 5, 6, 7, 8] end end <file_sep>/leetcode/797.all_paths_source_target.py import unittest class Solution(object): def find_path(self, graph, source, target, path, all_paths): for neighbor in sorted(graph[source]): p = path[:] p.append(neighbor) if neighbor == target: all_paths.append(p) return self.find_path(graph, neighbor, target, p, all_paths) def solve(self, graph): target = len(graph) - 1 all_paths = [] self.find_path(graph, 0, target, [0], all_paths) return all_paths class SolutionTestCase(unittest.TestCase): def test_example(self): graph = [[1, 2], [3], [3], []] paths = Solution().solve(graph) self.assertEqual(len(paths), 2) self.assertIn([0, 1, 3], paths) self.assertIn([0, 2, 3], paths) def test_target_has_neighbor(self): graph = [[1, 2], [4], [3], [5], [], [4]] paths = Solution().solve(graph) self.assertEqual(len(paths), 1) self.assertIn([0, 2, 3, 5], paths) def test_6_of_26(self): graph = [[4, 3, 1], [3, 2, 4], [3], [4], []] paths = Solution().solve(graph) self.assertEqual(len(paths), 5) self.assertIn([0, 4], paths) self.assertIn([0, 3, 4], paths) self.assertIn([0, 1, 3, 4], paths) self.assertIn([0, 1, 2, 3, 4], paths) self.assertIn([0, 1, 4], paths) if __name__ == '__main__': unittest.main() <file_sep>/leetcode/811.subdomain_visit_count.js /** * @param {string[]} cpdomains * @return {string[]} */ var subdomainVisits = function(cpdomains) { let result = []; let h = {}; for (let pair of cpdomains) { let [count, domain] = pair.split(' '); count = parseInt(count); let parts = domain.split('.'); for (let i = 0; i < parts.length; i++) { let key = parts.slice(i).join('.'); if (h[key]) { h[key] += count; } else { h[key] = count; } } } for (let k in h) { result.push(`${h[k]} ${k}`); } return result; }; <file_sep>/leetcode/152.max_prod_subarray.py import unittest class Solution(object): def max_product(self, nums): # keep track of the max and min products that can be achieved # ending with index i max_values = nums[:] min_values = nums[:] for i in xrange(len(nums)): if i > 0: max_values[i] = max( max_values[i-1] * nums[i], min_values[i-1] * nums[i], nums[i]) min_values[i] = min( max_values[i-1] * nums[i], min_values[i-1] * nums[i], nums[i]) return max(max_values) class MaxProductTestCase(unittest.TestCase): def test_example(self): self.assertEqual(Solution().max_product([2, 3, -2, 4]), 6) def test_negatives(self): self.assertEqual(Solution().max_product([-2, 3, -4]), 24) def test_negatives2(self): self.assertEqual(Solution().max_product([2, -5, -2, -4, 3]), 24) if __name__ == '__main__': unittest.main() <file_sep>/leetcode/338.count_bits.py import unittest class Solution(object): def count_bits(self, num): if num == 0: return [0] if num == 1: return [0, 1] n, exp = num, 1 while (n / 2): exp += 1 n /= 2 values = [0] * (exp ** 2) values[1] = 1 index = 2 for e in range(1, exp): prev_start = 2 ** (e-1) prev_end = 2 ** e temp = values[index:index+(2**e/2)] = values[prev_start:prev_end] values[index+(2**e/2):(2**(e+1))] = [i+1 for i in temp] index += 2 ** e return values[0:(num+1)] class CountBitsTestCase(unittest.TestCase): def test_example(self): self.assertEqual(Solution().count_bits(5), [0, 1, 1, 2, 1, 2]) if __name__ == '__main__': unittest.main() <file_sep>/tree/bst.c /* * Binary search tree implemented with linked list. */ #include <stdio.h> #include <stdlib.h> typedef struct node { int value; struct node *parent; struct node *left; struct node *right; } node; typedef struct bst { struct node *root; } bst; /* * Given the root and a key, return a pointer to a node with that key * on success; return NULL otherwise */ struct node* search(node *r, int k) { if (r == NULL || r->value == k) return r; if (k < r->value) return search(r->left, k); else return search(r->right, k); } /* * Given a node x in the tree, return a pointer to the minimum element * in the subtree rooted at x */ struct node* minimum(node *x) { if (x->left == NULL) return x; else return minimum(x->left); } /* * Given a node x in the tree, return a pointer to the maximum element * in the subtree rooted at x */ struct node* maximum(node *x) { if (x->right == NULL) return x; else return maximum(x->right); } /* * Return the successor of a node x if it exists; return NULL otherwise */ struct node* successor(node *x) { if (x->right != NULL) return minimum(x->right); else { /* Return the lowest ancestor of x whose left child is also * an ancestor (including x itself) of x */ node *p = x->parent; while (p != NULL && x == p->right) { x = p; p = x->parent; } return p; } } /* * Return the predecessor of a node x if it exists; return NULL otherwise */ struct node* predecessor(node *x) { if (x->left != NULL) return maximum(x->left); else { /* Return the lowest ancestor of x whose right child is also * an ancestor (including x itself) of x */ node *p = x->parent; while (p != NULL && x == p->left) { x = p; p = x->parent; } return p; } } /* * Given the root and a key, insert the node with that key into the * appropriate position */ void insert(bst *b, int k) { node *i = b->root; node *p = NULL; node *t = (node *)malloc(sizeof(node)); t->value = k; t->parent = NULL; t->left = NULL; t->right = NULL; /* Connecting the inserting node with its parent */ while (i != NULL) { p = i; if (k < i->value) i = i->left; else i = i->right; } t->parent = p; /* Connecting the parent with the inserting node */ if (p == NULL) { /* The tree is empty */ b->root = t; } else if (k < p->value) p->left = t; else p->right = t; } /* * See detailed explanation on page 263 of Intro to Algorithms */ struct node* delete(node *r, int k) { node *target = search(r, k); node *succ; node *temp; if (target->left == NULL || target->right == NULL) { /* target has at most one child */ succ = target; } else { /* target has two children */ succ = successor(target); } /* succ can have only one child in either case above */ if (succ->left != NULL) temp = succ->left; else temp = succ->right; /* Connect child with grandparent */ if (temp != NULL) temp->parent = succ->parent; /* Connect grandparent with child */ if (succ->parent == NULL) r = temp; else if (succ == succ->parent->left) succ->parent->left = temp; else succ->parent->right = temp; if (succ != target) { int swap; swap = target->value; target->value = succ->value; succ->value = swap; } return succ; } /* * Traverse and display the nodes of the tree */ void print(node *r) { if (r != NULL) { if (r->left != NULL) printf("%d -> %d \t", r->value, r->left->value); else printf("%d -> NULL\t", r->value); if (r->right != NULL) printf("%d -> %d", r->value, r->right->value); else printf("%d -> NULL", r->value); printf("\n"); print(r->left); print(r->right); } } <file_sep>/leetcode/211.add_and_search.py import unittest class TreeNode(object): def __init__(self, x): self.val = x self.terminal = False self.children = [] class Solution(object): def __init__(self): self.root = TreeNode(None) def add_word(self, word): node = self.root for index, letter in enumerate(word): found = False for child in node.children: if letter == child.val: found = True node = child break if not found: new_child = TreeNode(letter) node.children.append(new_child) node = new_child if index == len(word)-1: # mark current position as a potential terminal node node.terminal = True def search(self, word): def search_helper(node, word): if len(word) == 0: return node.terminal if word[0] != '.': for child in node.children: if child.val == word[0]: return search_helper(child, word[1:]) return False else: for child in node.children: if search_helper(child, word[1:]): return True return False return search_helper(self.root, word) class SolutionTestCase(unittest.TestCase): def test_example(self): o = Solution() o.add_word('bad') o.add_word('dad') o.add_word('mad') o.add_word('badad') self.assertFalse(o.search('pad')) self.assertTrue(o.search('bad')) self.assertTrue(o.search('.ad')) self.assertTrue(o.search('b..')) self.assertFalse(o.search('bada')) self.assertTrue(o.search('ba.ad')) if __name__ == '__main__': unittest.main() <file_sep>/leetcode/111.js import { TreeNode } from './util.js'; /** * @param {TreeNode} root * @return {number} */ var minDepth = function(root) { if (!root) return 0; let result = Infinity; function traverse(node, depth) { if (!node) return; if (!node.left && !node.right) { if (depth < result) { result = depth; } return; } traverse(node.left, depth+1); traverse(node.right, depth+1); } traverse(root, 1); return result; }; // Tests const root = new TreeNode(3); root.left = new TreeNode(9); root.right = new TreeNode(20); root.right.left = new TreeNode(15); root.right.right = new TreeNode(7); console.log(minDepth(root)); <file_sep>/interview_cake/cake_thief.py import unittest def max_duffel_bag_value(cakes, capacity): if capacity < 1: return 0 max_values = [0] * (capacity+1) # base case for cake in cakes: weight, value = cake max_values[weight] = value for i in range(1, capacity+1): values = [] for k in cakes: if i - k[0] > -1: values.append(max_values[i-k[0]] + k[1]) else: values.append(0) max_values[i] = max(values) return max_values[capacity] class CakeThiefTestCase(unittest.TestCase): def test_example(self): cakes = [(7, 160), (3, 90), (2, 15)] capacity = 20 self.assertEqual(max_duffel_bag_value(cakes, capacity), 555) def test_edge(self): cakes = [(7, 160), (3, 90), (2, 15)] capacity = 0 self.assertEqual(max_duffel_bag_value(cakes, capacity), 0) def test_3(self): cakes = [(3, 40), (5, 70)] capacity = 9 self.assertEqual(max_duffel_bag_value(cakes, capacity), 120) def test_4(self): cakes = [(3, 40), (5, 70)] capacity = 8 self.assertEqual(max_duffel_bag_value(cakes, capacity), 110) if __name__ == '__main__': unittest.main() <file_sep>/leetcode/463.island_perimeter.js /** * @param {number[][]} grid * @return {number} */ var islandPerimeter = function(grid) { let root = findRoot(grid); if (root === null) { return 0; } return bfs(grid, root); }; function findRoot(grid) { for (let i = 0; i < grid.length; i++) { for (let j = 0; j < grid[0].length; j++) { if (grid[i][j] === 1) { return [i, j]; } } } return null; } function findNeighbors(grid, node) { let x = node[0], y = node[1]; let result = []; if (y > 0 && grid[x][y-1] > 0) { result.push([x, y-1]); } if (y+1 < grid[0].length && grid[x][y+1] > 0) { result.push([x, y+1]); } if (x > 0 && grid[x-1][y] > 0) { result.push([x-1, y]); } if (x+1 < grid.length && grid[x+1][y] > 0) { result.push([x+1, y]); } return result; } function bfs(grid, source) { let result = 0; let queue = [source]; let visited = {}; visited[source] = true; while (queue.length > 0) { let curr = queue.pop(); let neighbors = findNeighbors(grid, curr); for (let neighbor of neighbors) { if (visited[neighbor] === undefined) { queue.push(neighbor); visited[neighbor] = true; } } result += (4 - neighbors.length); } return result; } <file_sep>/leetcode/1014.capacity_to_ship_packages.js const assert = require('assert'); const _ = require('lodash'); function fit(weights, days, capacity) { while (days > 0) { var quota = capacity; while (quota >= 0) { let w = weights.shift(); quota -= w; if (quota < 0) { quota += w; weights.unshift(w); break; } } days--; } if (weights.length > 0) { return false; } return true; } var shipWithinDays = function(weights, D) { var sum = _.reduce(weights, (s, w) => s + w); var capacity = Math.ceil(sum / D); while (!fit(weights.slice(), D, capacity)) { capacity++; } return capacity; }; const weights1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; const d1 = 5; assert(shipWithinDays(weights1, d1) === 15); const weights2 = [3, 2, 2, 4, 1, 4]; const d2 = 3; assert(shipWithinDays(weights2, d2) === 6); const weights3 = [1, 2, 3, 1, 1]; const d3 = 4; assert(shipWithinDays(weights3, d3) === 3); <file_sep>/string/substring.py # Determine whether a string x is a substring of string y def is_substring(x, y): l = len(x) if l > 0: try: index = y.index(x[0]) except ValueError: return False if y[index:index+l] == x: return True return False <file_sep>/tree/trie.rb # Auto-completion for English words using trie. # # This program uses <NAME>'s Most Common English Words API as the dictionary. # http://alexdadgar.com/projects/rank/ require 'json' require 'open-uri' class AutoComplete def initialize @trie = Trie.new end def setup data = open(DICT_URL) { |io| io.read } dict = JSON.parse(data) dict.each do |item| item = item.flatten # item = ["the", 1] @trie.add(item.first, item.last) # build trie end end def run puts "!!! Type '\\q' to exit the program.\n" while true print "?> " str = ARGF.readline.strip! break if str == "\\q" unless str.empty? words = @trie.find_word_children(str) # Nothing just formatting output. words.length < 1 ? puts('[]') : print('[') words.each_with_index do |word, index| print word index < words.length - 1 ? print(', ') : print("]\n") end end end end end class Trie def initialize @trie = Hash.new end def add(word, frequency) subtrie = @trie word.each_char do |letter| subtrie[letter] ||= Hash.new subtrie = subtrie[letter] end subtrie[:end] = frequency end # Find all children that are valid words for a prefix. def find_word_children(prefix) words = Array.new root = get_subtrie(prefix) words.concat(get_leaves(root, prefix)) # since all valid words are stored in the leaves words end private def get_subtrie(prefix) subtrie = @trie prefix.each_char do |letter| return nil unless subtrie = subtrie[letter] end subtrie end def get_leaves(root, prefix) leaves = Array.new return leaves if root.nil? leaves << prefix if root.has_key?(:end) root.each_key do |key| if key != :end leaves.concat(get_leaves(root[key], prefix + key)) end end leaves end end DICT_SIZE = 1000 DICT_URL = "http://www.alexdadgar.com/projects/rank/api?top=#{DICT_SIZE}" ac = AutoComplete.new ac.setup ac.run <file_sep>/stack/stack.c /* * Stack implemented by a singly linked list. * This program is the solution to problem 10.2-2 * * Visual structure: * item_1 <- item_2 <- ... <- item_n (top of stack) */ #include <stdio.h> #include <stdlib.h> typedef struct node { int value; struct node *next; } node; typedef struct stack { int count; struct node *top; } stack; int is_empty(stack *S) { if (S->count == 0) return 1; else return 0; } void push(stack *S, int num) { node *item = (node *)malloc(sizeof(node)); item->value = num; item->next = S->top; S->top = item; S->count += 1; } int pop(stack *S) { printf("popping item..."); if (is_empty(S)) { printf("ERROR: Stack is empty.\n"); return -1; } else { int retval = S->top->value; node *temp = S->top->next; free(S->top); S->top = temp; S->count -= 1; return retval; } } void display(stack *S) { node *curr = S->top; while (curr != NULL) { printf("%d ", curr->value); curr = curr->next; } printf("\n"); } int main() { printf("Stack test:\n\ push 10 times, display stack\n\ pop 2 times, display stack\n\ pop 9 times, display error\n\n"); stack *s = (stack *)malloc(sizeof(stack)); int i, j; printf("pushing...\n"); for (i = 1; i < 11; i++) { push(s, i); } display(s); printf("%d\n", pop(s)); printf("%d\n", pop(s)); display(s); for (j = 1; j < 10; j++) { int temp = pop(s); if (temp != -1) printf("%d\n", temp); } } <file_sep>/leetcode/util.py class ListNode(object): def __init__(self, x): self.val = x self.next = None class BinaryTreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class UndirectedGraphNode(object): def __init__(self, label): self.label = label self.neighbors = set() self.color = None <file_sep>/leetcode/637.average_of_levels.js const _ = require('lodash'); /** * @param {TreeNode} root * @return {number[]} */ var averageOfLevels = function(root) { const result = []; let queue = [root]; while (queue.length > 0) { const sum = _.reduce(queue, (s, o) => { return s + o.val; }, 0); const avg = sum / queue.length; result.push(avg); const temp = queue.slice(); queue = []; for (let i = 0; i < temp.length; i++) { if (temp[i].left) queue.push(temp[i].left); if (temp[i].right) queue.push(temp[i].right); } } return result; }; <file_sep>/interview_cake/second_largest_item_bst.py import unittest from util import BinaryTreeNode def largest_item(root): node = root while node.right: node = node.right return node def second_largest_item(root): if root is None: return node = root while node: if node.left and not node.right: return largest_item(node.left) elif node.right and not node.right.right and not node.right.left: return node else: node = node.right class SecondLargestItemTestCase(unittest.TestCase): def test_naive(self): tree = BinaryTreeNode(50) tree.insert_left(30) tree.insert_right(80) tree.left.insert_left(20) tree.left.insert_right(40) tree.right.insert_left(70) tree.right.insert_right(90) self.assertEqual(second_largest_item(tree).value, 80) def test_left_subtree(self): tree = BinaryTreeNode(50) tree.insert_left(30) tree.insert_right(90) tree.left.insert_left(20) tree.right.insert_left(70) tree.right.left.insert_left(60) tree.right.left.insert_right(80) self.assertEqual(second_largest_item(tree).value, 80) if __name__ == '__main__': unittest.main() <file_sep>/hash_table/lin_prob.c /* * Open-addressed hash table with linear probing. * Auxiliary hash function: h(k) = k mod 9 * * To be inserted: [5, 28, 19, 15, 20, 33, 12, 17, 10] * After insertion: * 0 | 10 * 1 | 28 * 2 | 19 * 3 | 20 * 4 | 12 * 5 | 5 * 6 | 15 * 7 | 33 * 8 | 17 */ #include <stdio.h> #include <stdlib.h> #define TABLE_SIZE 9 /* In open-addressing the size of hash table is pre-determined */ int h[TABLE_SIZE]; /* Return 0 on success, return -1 on table overflow */ int insert(int x) { int i = 0; int j = -1; while (i < TABLE_SIZE) { j = ((x % TABLE_SIZE) + i) % TABLE_SIZE; if (h[j] == -1) { h[j] = x; return 0; } else i++; } return -1; } /* Return the position of x on success, return -1 otherwise */ int search(int x) { int i = 0; int j = -1; do { j = ((x % TABLE_SIZE) + i) % TABLE_SIZE; if (h[j] == x) return j; else i++; } while (h[j] == -1 || i == TABLE_SIZE); return -1; } void display() { int i; printf("Hash Table:\n"); for (i = 0; i < TABLE_SIZE; i++) printf("%d | %d\n", i, h[i]); } int main() { /* Initialization */ int i; for (i = 0; i < TABLE_SIZE; i++) h[i] = -1; /* Test insertion */ int t[TABLE_SIZE] = {5, 28, 19, 15, 20, 33, 12, 17, 10}; int retval; for (i = 0; i < TABLE_SIZE; i++) { retval = insert(t[i]); if (retval == -1) { printf("ERROR: hash table overflow\n"); return 0; } } display(); /* Test search */ int result; result = search(15); if (result == 6) printf("Test for search on success PASSED.\n"); else printf("Test for search on success FAILED.\n"); result = search(87); if (result == -1) printf("Test for search on failure PASSED.\n"); else printf("Test for search on failure FAILED.\n"); } <file_sep>/queue/queue.c /* * Queue implemented by a singly linked list. * This program is the solution to problem 10.2-3 * * Visual structure: * (head) item_1 -> item_2 -> ... -> item_n (tail) */ #include <stdio.h> #include <stdlib.h> typedef struct node { int value; struct node *next; } node; typedef struct queue { int count; struct node *head; struct node *tail; } queue; int is_empty(queue *Q) { if (Q->count == 0) return 1; else return 0; } void enqueue(queue *Q, int num) { node *item = (node *)malloc(sizeof(node)); item->value = num; if (Q->count == 0) { Q->head = item; Q->tail = item; } else { Q->tail->next = item; Q->tail = item; } Q->count += 1; } int dequeue(queue *Q) { printf("dequeuing..."); if (is_empty(Q)) { printf("ERROR: Queue is empty.\n"); return -1; } else { int retval = Q->head->value; node *temp = Q->head->next; free(Q->head); Q->head = temp; Q->count -= 1; return retval; } } void display(queue *Q) { node *curr = Q->head; while (curr != NULL) { printf("%d ", curr->value); curr = curr->next; } printf("\n"); } int main() { printf("Queue test:\n\ enqueue 10 times, display queue\n\ dequeue 2 times, display queue\n\ dequeue 9 times, display error\n\n"); queue *q = (queue *)malloc(sizeof(queue)); int i, j; printf("enqueuing...\n"); for (i = 1; i < 11; i++) { enqueue(q, i); } display(q); printf("%d\n", dequeue(q)); printf("%d\n", dequeue(q)); display(q); for (j = 1; j < 10; j++) { int temp = dequeue(q); if (temp != -1) printf("%d\n", temp); } } <file_sep>/leetcode/849.max_distance_to_closest.js /** * @param {number[]} seats * @return {number} */ var maxDistToClosest = function(seats) { var maxDist = 0; var left = Array(seats.length).fill(Infinity); var right = Array(seats.length).fill(Infinity); for (let i = 0; i < seats.length; i++) { if (seats[i] > 0) { left[i] = 0; } else { if (i < 1) continue; left[i] = left[i-1] + 1; } } for (let j = seats.length-1; j >= 0; j--) { if (seats[j] > 0) { right[j] = 0; } else { if (j === seats.length-1) continue; right[j] = right[j+1] + 1; } } for (let k = 0; k < seats.length; k++) { let dist = Math.min(left[k], right[k]); if (dist > maxDist) { maxDist = dist; } } return maxDist; }; <file_sep>/leetcode/953.alien_dictionary.js /** * @param {string[]} words * @param {string} order * @return {boolean} */ var isAlienSorted = function(words, order) { if (words.length < 2) return true; for (let i = 1; i < words.length; i++) { let w1 = words[i-1], w2 = words[i]; let j = 0; if (w1.includes(w2)) return false; while (j < w1.length && j < w2.length) { if (order.indexOf(w1[j]) < order.indexOf(w2[j])) { break; } if (order.indexOf(w1[j]) > order.indexOf(w2[j])) { return false; } j++; } } return true; }; <file_sep>/sorting/ksmall.py # Finding the Kth smallest element in an array of n elements. from random import randint def partition(a, start, end): pivot = randint(start, end) a[pivot], a[end] = a[end], a[pivot] final= start for i in range(start, end): if a[i] < a[end]: a[i], a[final] = a[final], a[i] final += 1 a[final], a[end] = a[end], a[final] return final def quick_find(a, start, end, k): pivot = partition(a, start, end) if pivot + 1 < k: quick_find(a, pivot+1, end, k-pivot-1) elif pivot + 1 == k: return a[pivot+1] else: quick_find(a, start, pivot-1, k) def ksmall(a, k): print quick_find(a, 0, len(a)-1, k) array = [1, 4, 2, 8, 5, 7] ksmall(array, 3) <file_sep>/leetcode/104.js import { TreeNode } from './util.js'; /** * @param {TreeNode} root * @return {number} */ var maxDepth = function(root) { let answer = 0; function dfs(node, depth) { if (!node) return; if (depth > answer) answer = depth; dfs(node.left, depth+1); dfs(node.right, depth+1); } dfs(root, 1); return answer; }; // Tests const root = new TreeNode(3); root.left = new TreeNode(9); root.right = new TreeNode(20); root.right.left = new TreeNode(15); root.right.right = new TreeNode(7); console.log(maxDepth(root)); <file_sep>/leetcode/1021.remove_outermost_parentheses.js /** * @param {string} S * @return {string} */ var removeOuterParentheses = function(S) { let stack = []; let counter = -1; let result = ''; for (let i = 0; i < S.length; i++) { stack.push(S[i]); if (S[i] === ')') { if (counter > 0) { counter--; } else { result += stack.slice(counter+1, stack.length-1).join(''); stack = []; counter = -1; } } else { counter++; } } return result; }; <file_sep>/leetcode/tests.js import assert from 'assert'; import { array2tree } from './util.js'; /** * array2tree() */ const a1 = []; const t1 = array2tree(a1); assert(t1 === null); const a2 = [5, 4, 8, 11, null, 13, 4, 7, 2, null, null, null, 1]; const t2 = array2tree(a2); assert(t2.val === 5); assert(t2.left.val === 4); assert(t2.right.val === 8); assert(t2.left.left.val === 11); assert(t2.left.right === null); assert(t2.left.left.left.val === 7); assert(t2.left.left.right.val === 2); assert(t2.right.val === 8); assert(t2.right.left.val === 13); assert(t2.right.right.val === 4); assert(t2.right.left.left === null); assert(t2.right.left.right === null); assert(t2.right.right.left === null); assert(t2.right.right.right.val === 1); assert(t2.right.right.right.left === null); assert(t2.right.right.right.right === null); <file_sep>/interview_cake/temperature_tracker.py class TempTracker: def __init__(self): self.temp = dict() self.total = 0 self.count = 0 self.mode = None self.largest = None self.smallest = None def insert(self, value): if value in self.temp: self.temp[value] += 1 if self.temp[value] > self.mode: self.mode = self.temp[value] else: self.temp[value] = 1 self.total += value self.count += 1 self.largest = max(self.largest, value) self.smallest = min(self.smallest, value) def get_max(self): return self.largest def get_min(self): return self.smallest def get_mean(self): return float(self.total) / self.count def get_mode(self): return self.mode <file_sep>/leetcode/215.kth_largest.py def findKthLargest(nums, k): while k > 0: largest = -float('inf') for num in nums: if num > largest: largest = num nums.remove(largest) if k == 1: return largest k -= 1 print findKthLargest([3, 2, 1, 5, 6, 4], 2) <file_sep>/leetcode/3.longest_sub_no_rep.py import unittest class Solution(object): def solve(self, s): if len(s) < 1: return 0 l = [1] * len(s) for i in range(1, len(s)): j = i - 1 k = l[j] while k > 0: if s[i] == s[j]: l[i] = i - j break else: j -= 1 k -= 1 if k == 0: l[i] = l[i-1] + 1 return max(l) class SolutionTestCase(unittest.TestCase): def test_example1(self): self.assertEqual(Solution().solve('abcabcbb'), 3) def test_example2(self): self.assertEqual(Solution().solve('bbbbb'), 1) def test_example3(self): self.assertEqual(Solution().solve('pwwkew'), 3) def test_edge(self): self.assertEqual(Solution().solve(''), 0) def test_case1(self): self.assertEqual(Solution().solve('dvdf'), 3) def test_case2(self): self.assertEqual(Solution().solve('abba'), 2) if __name__ == '__main__': unittest.main() <file_sep>/heap/heap.rb # Generic binary heap as array. class Heap attr_accessor :data def initialize(type) raise ArgumentError unless [:min, :max].include? type @type = type @data = [nil] end def heapify(root) return if root > @data.length / 2 # root is a leaf winner = 0 left = root * 2 right = root * 2 + 1 if !@data[left].nil? and compare(@data[left], @data[root]) winner = left else winner = root end if !@data[right].nil? and compare(@data[right], @data[winner]) winner = right end if winner != root @data[root], @data[winner] = @data[winner], @data[root] heapify(winner) end end def peek @data.first end def delete @data.delete_at(0) end def insert(key) @data.push(key) end private def compare(v1, v2) @type == :max ? v1 > v2 : v1 < v2 end end <file_sep>/leetcode/5.longest_palindromic_substr.js const assert = require('assert'); var longestPalindrome = function(s) { // initialization let p = []; for (let i = 0; i < s.length; i++) { p.push(new Array(s.length).fill(false)); p[i][i] = true; if (i < s.length-1) { p[i][i+1] = s[i] === s[i+1]; } } // DP for (let j = 2; j < s.length; j++) { for (let i = 0; i < j-1; i++) { p[i][j] = p[i+1][j-1] && (s[i] === s[j]); } } // find result let longest = s[0]; for (let i = 0; i < s.length; i++) { for (let j = i; j < s.length; j++) { if (p[i][j] && (j-i+1) > longest.length) { longest = s.slice(i, j+1); } } } return longest; }; assert(['bab', 'aba'].includes(longestPalindrome('babad'))); assert(longestPalindrome('cbbd') === 'bb'); assert(longestPalindrome('abcba') === 'abcba'); <file_sep>/leetcode/279.perfect_squares.py import unittest class Solution(object): def max_base(self, n): return int(n ** (1/2.0)) def solve(self, n): f = [0] * (n+1) for i in range(1, n+1): dependents = [j*j for j in range(1, self.max_base(i)+1)] f[i] = min([f[i-d]+1 for d in dependents]) return f[-1] class SolutionTestCase(unittest.TestCase): def test_example1(self): self.assertEqual(Solution().solve(12), 3) def test_example2(self): self.assertEqual(Solution().solve(13), 2) if __name__ == '__main__': unittest.main() <file_sep>/interview_cake/mesh_message.py import unittest def shortest_route(network, sender, recipient): # breadth first search queue = [sender] visited = [] parent = {k: None for k in network.keys()} while len(queue) > 0: node = queue.pop() visited.append(node) if node == recipient: break for neighbor in network[node]: if neighbor not in visited: queue.insert(0, neighbor) parent[neighbor] = node # backtrack the search tree to find the shortest path path = [recipient] curr = recipient while curr != sender: prev = parent[curr] path.insert(0, prev) curr = prev return path class MeshMessageTestCase(unittest.TestCase): def test_example(self): network = { 'Min': ['William', 'Jayden', 'Omar'], 'William': ['Min', 'Noam'], 'Jayden': ['Min', 'Amelia', 'Ren', 'Noam'], 'Ren': ['Jayden', 'Omar'], 'Amelia': ['Jayden', 'Adam', 'Miguel'], 'Adam': ['Amelia', 'Miguel', 'Sofia', 'Lucas'], 'Miguel': ['Amelia', 'Adam', 'Liam', 'Nathan'], 'Noam': [], 'Omar': [], } self.assertEqual(shortest_route(network, 'Jayden', 'Adam'), [ 'Jayden', 'Amelia', 'Adam']) if __name__ == '__main__': unittest.main() <file_sep>/leetcode/628.max_product_three_numbers.js const _ = require('lodash'); /** * @param {number[]} nums * @return {number} */ var maximumProduct = function(nums) { var sorted = _.sortBy(nums); return Math.max( sorted[0]*sorted[1]*sorted[sorted.length-1], sorted[sorted.length-1]*sorted[sorted.length-2]*sorted[sorted.length-3] ); }; <file_sep>/leetcode/295.data_stream_median.py import unittest from heapq import heappush, heappushpop, heappop class MedianFinder(object): def __init__(self): self.small = [] self.large = [] def add_num(self, num): heappush(self.small, -heappushpop(self.large, num)) if len(self.large) < len(self.small): heappush(self.large, -heappop(self.small)) def find_median(self): if len(self.large) > len(self.small): return float(self.large[0]) return (self.large[0] - self.small[0]) / 2.0 class MedianFinderTestCase(unittest.TestCase): def test(self): mf = MedianFinder() mf.add_num(1) mf.add_num(2) self.assertEqual(mf.find_median(), 1.5) mf.add_num(3) self.assertEqual(mf.find_median(), 2) mf.add_num(8) self.assertEqual(mf.find_median(), 2.5) mf.add_num(9) self.assertEqual(mf.find_median(), 3) if __name__ == '__main__': unittest.main() <file_sep>/leetcode/621.task_scheduler.py import unittest class Solution(object): def __init__(self): self.data = {} def parse_tasks(self, tasks): for task in tasks: if task not in self.data.keys(): self.data[task] = 1 else: self.data[task] += 1 def solve(self, tasks, n): self.parse_tasks(tasks) task_sequence = [] # spread each task as far apart as possible while sum(self.data.values()) > 0: for key in self.data: if self.data[key] > 0: task_sequence.append(key) self.data[key] -= 1 # insert idle intervals for i, v in enumerate(task_sequence): current = task_sequence[i] if current is not None: window = task_sequence[max(i-n, 0):i] idles = 0 for j in range(len(window)): if window[j] == current: idles = j + 1 break while idles > 0: task_sequence.insert(i, None) idles -= 1 return len(task_sequence) class SolutionTestCase(unittest.TestCase): def test_example(self): tasks = ['A', 'A', 'A', 'B', 'B', 'B'] n = 2 self.assertEqual(Solution().solve(tasks, n), 8) def test_single_task(self): tasks = ['A', 'A', 'A'] n = 2 self.assertEqual(Solution().solve(tasks, n), 7) def test_unbalanced(self): tasks = ['A', 'A', 'A', 'A', 'A', 'A', 'B', 'C', 'D', 'E', 'F', 'G'] n = 2 self.assertEqual(Solution().solve(tasks, n), 16) if __name__ == '__main__': unittest.main() <file_sep>/util/util.rb require_relative 'node' require_relative 'stack' require_relative 'graph' <file_sep>/leetcode/77.combinations.py import unittest class Solution(object): def generate(self, nums, k): if k == 0: return [[]] result = [] remainder = nums[:] for num in nums: remainder.remove(num) for item in self.generate(remainder, k-1): result.append([num] + item) return result def solve(self, n, k): nums = range(1, n+1) return self.generate(nums, k) class SolutionTestCase(unittest.TestCase): def test_example(self): solution = Solution().solve(4, 2) self.assertEqual(len(solution), 6) self.assertIn([2, 4], solution) self.assertIn([3, 4], solution) self.assertIn([1, 4], solution) self.assertIn([1, 3], solution) self.assertIn([1, 2], solution) self.assertIn([2, 3], solution) if __name__ == '__main__': unittest.main() <file_sep>/leetcode/22.generate_parentheses.py import unittest class Solution(object): def __init__(self): self.results = [] def generate(self, sequence, left, right, n): if len(sequence) == 2 * n: self.results.append(sequence) return if left > 0: self.generate(sequence + '(', left-1, right, n) if right > left: self.generate(sequence + ')', left, right-1, n) def solve(self, n): self.generate('', n, n, n) return self.results class SolutionTestCase(unittest.TestCase): def test_example(self): results = Solution().solve(3) self.assertIn('((()))', results) self.assertIn('(()())', results) self.assertIn('(())()', results) self.assertIn('()(())', results) self.assertIn('()()()', results) self.assertEqual(len(results), 5) if __name__ == '__main__': unittest.main() <file_sep>/string/remove_duplicates.rb # Remove the duplicate characters in a string without using # any additional buffer. def remove_duplicates str return str if str.nil? || str.length < 2 i = 1 while i < str.length (0..i - 1).each do |j| if str[i] == str[j] str[i] = '' i -= 1 break end end i += 1 end str end puts remove_duplicates 'maximization' <file_sep>/leetcode/108.js import { TreeNode } from "./util.js"; /** * @param {number[]} nums * @return {TreeNode} */ var sortedArrayToBST = function(nums) { function convert(A, root) { if (A.length < 1) return null; let mid = Math.floor((A.length-1) / 2); root.val = A[mid]; root.left = convert(A.slice(0, mid), new TreeNode()); root.right = convert(A.slice(mid+1, A.length), new TreeNode()); return root; } return convert(nums, new TreeNode()); }; <file_sep>/leetcode/121.best_time_buy_sell_stock.js /** * @param {number[]} prices * @return {number} */ var maxProfit = function(prices) { var profit = 0; var lowest = prices[0]; for (var i = 1; i < prices.length; i++) { profit = Math.max(prices[i]-lowest, profit); if (prices[i] < lowest) { lowest = prices[i]; } } return profit; };
00ea1d091776e411cc0bd1f2eede383b61665e7d
[ "JavaScript", "C", "Python", "Ruby" ]
178
Python
yemutex/bach
cdec6245be8d2a5d86a848b3c1f710a4492649ae
fba70fb85d021d5bb7d9eb96c350ff7a809ef760
refs/heads/master
<file_sep>## Put comments here that give an overall description of what your ## functions do ## Write a short comment describing this function ## makeCacheMatrix is a function that constructs a 'special matrix' containing a ## list to functions that implement the following operations ## set: Sets the value of the matrix. When a new matrix is 'set' the value of ## of the inverse is deleted. ## get: Recovers the value of the matrix which has been stored in the parent ## environment ## setinv:Sets the value of the inverse matrix as a variable in the parent environment ## getinv:Returns the value of the inverse matrix (m_inv) which is found in the ## parent environment makeCacheMatrix <- function(x = matrix()) { m_inv <- NULL set <- function(y){ x <<- y m_inv <<- NULL } get <- function() x setinv <- function(inverse) m_inv <<- inverse getinv <- function() m_inv list(set = set, get = get, setinv = setinv, getinv = getinv) } ## Write a short comment describing this function ## cacheSolve returns the inverse value of a matrix created with makeCacheMatrix ## function. The function tries to find the inverse in the cache (parent environmet). ## If the inverse has been calculated previously then it returns its value from ## the cache (parent environment). Otherwise, if the inverse is not found ## it computes the inverse, stores it in the cache and returns its value cacheSolve <- function(x, ...) { ## Return a matrix that is the inverse of 'x' m_inv <- x$getinv() if(!is.null(m_inv)){ message("getting cached data") return(m_inv) } mat <- x$get() m_inv <- solve(mat,...) x$setinv(m_inv) m_inv }
3ba48471a871bba90a9b1a09c637922bbcd5dd06
[ "R" ]
1
R
FrancescTarres/ProgrammingAssignment2
f5bcd7453f954bf45259b3f10813d384b82f98f5
1cb78af4ab909e1a7aa7275cc4f86fa8538a9606
refs/heads/main
<file_sep>export function foo({ foo }) { console.log(`Inside foo({foo:${foo}})`); } <file_sep>import { foo } from "foo"; foo({ foo: 100 }); <file_sep>export declare function foo({ foo }: { foo: number; }): void; <file_sep>import { foo } from "foo"; foo({ foo: 100 }); <file_sep># TS Node Repro ## Issue .d.ts files are ignored when `allowJs && checkJs` Works fine when either of them are set to false. ## Run ```bash cd ./myapp-bar yarn tsc # produces no error node --loader ts-node/esm main.ts # errors ``` ## Error shown ``` (node:700514) ExperimentalWarning: --experimental-loader is an experimental feature. This feature could change at any time (Use `node --trace-warnings ...` to show where the warning was created) /home/farseen/Projects/97.Temp/ts-node-types/node_modules/ts-node/src/index.ts:618 return new TSError(diagnosticText, diagnosticCodes); ^ TSError: ⨯ Unable to compile TypeScript: ../myapp-foo/dist/foo.js:1:23 - error TS7031: Binding element 'foo' implicitly has an 'any' type. 1 export function foo({ foo }) { ~~~ at createTSError (/home/farseen/Projects/97.Temp/ts-node-types/node_modules/ts-node/src/index.ts:618:12) at reportTSError (/home/farseen/Projects/97.Temp/ts-node-types/node_modules/ts-node/src/index.ts:622:19) at getOutput (/home/farseen/Projects/97.Temp/ts-node-types/node_modules/ts-node/src/index.ts:809:36) at Object.compile (/home/farseen/Projects/97.Temp/ts-node-types/node_modules/ts-node/src/index.ts:1111:30) at /home/farseen/Projects/97.Temp/ts-node-types/node_modules/ts-node/src/esm.ts:146:38 at Generator.next (<anonymous>) at /home/farseen/Projects/97.Temp/ts-node-types/node_modules/ts-node/dist/esm.js:8:71 at new Promise (<anonymous>) at __awaiter (/home/farseen/Projects/97.Temp/ts-node-types/node_modules/ts-node/dist/esm.js:4:12) at transformSource (/home/farseen/Projects/97.Temp/ts-node-types/node_modules/ts-node/dist/esm.js:88:16) ```
935d3b0047120a5b5827cddb6640807139566710
[ "JavaScript", "TypeScript", "Markdown" ]
5
JavaScript
itsfarseen/ts-node-repro
e7e4747bb5585fd7ce0dc258fcdca3cf0062cb58
7dbb6c71dbf3d97aef047cdfdcb076c463ad437d
refs/heads/master
<repo_name>tylearymf/HlslTools<file_sep>/src/ShaderTools.Tests/Hlsl/Binding/FunctionInvocationExpressionTests.cs using System.Diagnostics; using System.Linq; using NUnit.Framework; using ShaderTools.Core.Diagnostics; using ShaderTools.Core.Text; using ShaderTools.Hlsl.Diagnostics; using ShaderTools.Hlsl.Symbols; using ShaderTools.Hlsl.Symbols.Markup; using ShaderTools.Hlsl.Syntax; using ShaderTools.Hlsl.Text; namespace ShaderTools.Tests.Hlsl.Binding { [TestFixture] public class FunctionInvocationExpressionTests { [TestCase("int", "int")] [TestCase("uint", "int")] [TestCase("float", "float")] [TestCase("half", "#ambiguous")] [TestCase("half1", "#ambiguous")] [TestCase("float1", "float")] [TestCase("half2", "#ambiguous")] [TestCase("float2x1", "float2")] [TestCase("float1x2", "float2")] [TestCase("float1x3", "#ambiguous")] [TestCase("float3x1", "#ambiguous")] [TestCase("float2x3", "float")] [TestCase("float3x3", "float3x3")] [TestCase("half2x3", "#ambiguous")] [TestCase("int2x2", "int")] [TestCase("MyStruct", "#undeclared")] public void TestFunctionOverloadResolution1Arg(string type, string expectedMatchType) { var code = $@" struct MyStruct {{}}; int foo(int x) {{ return 1; }} int foo(float x) {{ return 2; }} int foo(double x) {{ return 3; }} int foo(int2 x) {{ return 4; }} int foo(float2 x) {{ return 5; }} int foo(double2 x) {{ return 6; }} int foo(float3x3 x) {{ return 7; }} void main() {{ foo(({type}) 0); }}"; var syntaxTree = SyntaxFactory.ParseSyntaxTree(SourceText.From(code)); var syntaxTreeSource = syntaxTree.Root.ToFullString(); Assert.AreEqual(code, syntaxTreeSource, $"Source should have been {code} but is {syntaxTreeSource}."); var expression = (FunctionInvocationExpressionSyntax) syntaxTree.Root.ChildNodes .OfType<FunctionDefinitionSyntax>() .Where(x => x.Name.GetName() == "main") .Select(x => ((ExpressionStatementSyntax) x.Body.Statements[0]).Expression) .First(); var compilation = new ShaderTools.Hlsl.Compilation.Compilation(syntaxTree); var semanticModel = compilation.GetSemanticModel(); var combinedDiagnostics = syntaxTree.GetDiagnostics().Concat(semanticModel.GetDiagnostics()).ToList(); foreach (var d in combinedDiagnostics) Debug.WriteLine(d); var invokedFunctionSymbol = (FunctionSymbol) semanticModel.GetSymbol(expression); var diagnostic = combinedDiagnostics.SingleOrDefault(x => x.Severity == DiagnosticSeverity.Error); var result = diagnostic == null ? ExpressionTestUtility.GetExpressionTypeString(invokedFunctionSymbol.Parameters[0].ValueType) : ExpressionTestUtility.GetErrorString(diagnostic.DiagnosticId); Assert.AreEqual(expectedMatchType, result, $"Expression should have matched the function overload '{expectedMatchType}' but it actually matched '{result}'."); } [TestCase("float", "float", "float, float")] [TestCase("float", "half", "#ambiguous")] [TestCase("half", "half", "#ambiguous")] [TestCase("half2", "half", "#ambiguous")] [TestCase("float", "half", "#ambiguous")] [TestCase("double", "half", "double, float")] [TestCase("double", "double", "#ambiguous")] [TestCase("double", "bool", "#ambiguous")] [TestCase("double", "int", "double, int")] [TestCase("float2", "int", "float2, float")] [TestCase("float2", "half", "float2, float")] [TestCase("float2", "float", "float2, float")] [TestCase("float2", "double", "float2, float")] [TestCase("float3", "bool", "#ambiguous")] [TestCase("float3", "int", "float, int")] [TestCase("float3", "float", "#ambiguous")] [TestCase("int3", "float", "#ambiguous")] [TestCase("int3", "int", "#ambiguous")] [TestCase("float3", "double", "float, double")] [TestCase("float3x3", "bool", "float3x3, float")] [TestCase("float3x3", "half", "float3x3, float")] [TestCase("float3x3", "float", "float3x3, float")] [TestCase("float3x3", "double", "float3x3, float")] [TestCase("float", "int2", "float, int")] [TestCase("float", "half2", "#ambiguous")] [TestCase("float", "float2", "float, float")] [TestCase("float", "double2", "float, double")] [TestCase("float4x4", "float", "#ambiguous")] public void TestFunctionOverloadResolution2Args(string type1, string type2, string expectedMatchTypes) { var code = $@" int foo(int x, float y) {{ return 1; }} int foo(float x, float y) {{ return 2; }} int foo(double x, float y) {{ return 3; }} int foo(float x, int y) {{ return 4; }} int foo(float x, double y) {{ return 5; }} int foo(double x, int y) {{ return 6; }} int foo(int2 x, float y) {{ return 7; }} int foo(float2 x, float y) {{ return 8; }} int foo(double2 x, float y) {{ return 9; }} int foo(float3x3 x, float y) {{ return 10; }} void main() {{ foo({ExpressionTestUtility.GetValue(type1)}, {ExpressionTestUtility.GetValue(type2)}); }}"; var syntaxTree = SyntaxFactory.ParseSyntaxTree(SourceText.From(code)); var syntaxTreeSource = syntaxTree.Root.ToFullString(); Assert.AreEqual(code, syntaxTreeSource, $"Source should have been {code} but is {syntaxTreeSource}."); var expression = (FunctionInvocationExpressionSyntax) syntaxTree.Root.ChildNodes .OfType<FunctionDefinitionSyntax>() .Where(x => x.Name.GetName() == "main") .Select(x => ((ExpressionStatementSyntax) x.Body.Statements[0]).Expression) .First(); var compilation = new ShaderTools.Hlsl.Compilation.Compilation(syntaxTree); var semanticModel = compilation.GetSemanticModel(); var combinedDiagnostics = syntaxTree.GetDiagnostics().Concat(semanticModel.GetDiagnostics()).ToList(); foreach (var d in combinedDiagnostics) Debug.WriteLine(d); var invokedFunctionSymbol = (FunctionSymbol) semanticModel.GetSymbol(expression); var diagnostic = combinedDiagnostics.SingleOrDefault(x => x.Severity == DiagnosticSeverity.Error); var result = diagnostic == null ? $"{SymbolMarkup.ForSymbol(invokedFunctionSymbol.Parameters[0].ValueType)}, {SymbolMarkup.ForSymbol(invokedFunctionSymbol.Parameters[1].ValueType)}" : ExpressionTestUtility.GetErrorString(diagnostic.DiagnosticId); Assert.AreEqual(expectedMatchTypes, result, $"Expression should have matched the function overload '{expectedMatchTypes}' but it actually matched '{result}'."); } [TestCase("min", "float", "float", "float, float")] [TestCase("mul", "float4", "float4x4", "float4, float4x4")] [TestCase("mul", "float3", "float4x4", "float3, float3x4")] [TestCase("mul", "float4", "float3x4", "float1x3, float3x4")] [TestCase("mul", "float1", "float3x4", "float, float3x4")] [TestCase("mul", "float4", "float4x3", "float4, float4x3")] [TestCase("mul", "float4x3", "float3x4", "float4x3, float3x4")] [TestCase("dot", "int", "uint", "int1, int1")] public void TestIntrinsicFunctionOverloading(string function, string type1, string type2, string expectedMatchTypes) { var expressionCode = $"{function}(({type1}) 0, ({type2}) 0)"; var syntaxTree = SyntaxFactory.ParseExpression(expressionCode); var syntaxTreeSource = syntaxTree.Root.ToFullString(); Assert.AreEqual(expressionCode, syntaxTreeSource, $"Source should have been {expressionCode} but is {syntaxTreeSource}."); var expression = (ExpressionSyntax) syntaxTree.Root; var compilation = new ShaderTools.Hlsl.Compilation.Compilation(syntaxTree); var semanticModel = compilation.GetSemanticModel(); var combinedDiagnostics = syntaxTree.GetDiagnostics().Concat(semanticModel.GetDiagnostics()).ToList(); foreach (var d in combinedDiagnostics) Debug.WriteLine(d); var invokedFunctionSymbol = (FunctionSymbol) semanticModel.GetSymbol(expression); var diagnostic = combinedDiagnostics.SingleOrDefault(x => x.Severity == DiagnosticSeverity.Error); var result = diagnostic == null ? $"{SymbolMarkup.ForSymbol(invokedFunctionSymbol.Parameters[0].ValueType)}, {SymbolMarkup.ForSymbol(invokedFunctionSymbol.Parameters[1].ValueType)}" : ExpressionTestUtility.GetErrorString(diagnostic.DiagnosticId); Assert.AreEqual(expectedMatchTypes, result, $"Expression should have matched the function overload '{expectedMatchTypes}' but it actually matched '{result}'."); } } }<file_sep>/src/ShaderTools/Hlsl/Diagnostics/Diagnostic.cs using System.Globalization; using ShaderTools.Core.Diagnostics; using ShaderTools.Core.Text; namespace ShaderTools.Hlsl.Diagnostics { public sealed class Diagnostic : DiagnosticBase { public DiagnosticId DiagnosticId { get; } public Diagnostic(TextSpan textSpan, DiagnosticId diagnosticId, string message) : base(textSpan, message, DiagnosticFacts.GetSeverity(diagnosticId)) { DiagnosticId = diagnosticId; } public static Diagnostic Format(TextSpan textSpan, DiagnosticId diagnosticId, params object[] args) { var message = diagnosticId.GetMessage(); var formattedMessage = (message != null) ? string.Format(CultureInfo.CurrentCulture, message, args) : $"Missing diagnostic message for {diagnosticId}"; return new Diagnostic(textSpan, diagnosticId, formattedMessage); } } }<file_sep>/src/ShaderTools/Hlsl/Symbols/Symbol.cs using ShaderTools.Hlsl.Symbols.Markup; namespace ShaderTools.Hlsl.Symbols { public abstract class Symbol { public SymbolKind Kind { get; } public string Name { get; } public string Documentation { get; } public Symbol Parent { get; } internal Symbol(SymbolKind kind, string name, string documentation, Symbol parent) { Kind = kind; Name = name; Documentation = documentation; Parent = parent; } public sealed override string ToString() { return SymbolMarkup.ForSymbol(this).ToString(); } protected bool EqualsImpl(Symbol other) { return Kind == other.Kind && string.Equals(Name, other.Name) && (Parent == null) == (other.Parent == null) && (Parent == null || Parent.EqualsImpl(other.Parent)); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != GetType()) return false; return EqualsImpl((Symbol) obj); } public override int GetHashCode() { unchecked { var hashCode = (int) Kind; hashCode = (hashCode * 397) ^ Name.GetHashCode(); hashCode = (hashCode * 397) ^ (Parent?.GetHashCode() ?? 0); return hashCode; } } } }<file_sep>/src/ShaderTools.Tests/Unity/Parser/RoundtrippingTests.cs using System.IO; using NUnit.Framework; using ShaderTools.Core.Text; using ShaderTools.Tests.Unity.Support; using ShaderTools.Unity.Syntax; namespace ShaderTools.Tests.Unity.Parser { [TestFixture] public class RoundtrippingTests { [TestCaseSource(typeof(ShaderTestUtility), nameof(ShaderTestUtility.GetUnityTestShaders))] public void CanBuildUnitySyntaxTree(string testFile) { var sourceCode = File.ReadAllText(testFile); // Build syntax tree. var syntaxTree = SyntaxFactory.ParseUnitySyntaxTree( SourceText.From(sourceCode)); ShaderTestUtility.CheckForParseErrors(syntaxTree); // Check roundtripping. var roundtrippedText = syntaxTree.Root.ToFullString(); Assert.That(roundtrippedText, Is.EqualTo(sourceCode)); } } }<file_sep>/src/ShaderTools/Unity/Diagnostics/DiagnosticFacts.cs using ShaderTools.Core.Diagnostics; namespace ShaderTools.Unity.Diagnostics { internal static class DiagnosticFacts { public static DiagnosticSeverity GetSeverity(DiagnosticId id) { return DiagnosticSeverity.Error; } } }<file_sep>/src/ShaderTools.Tests/Hlsl/Support/InMemoryFileSystem.cs using System.Collections.Generic; using ShaderTools.Core.Text; using ShaderTools.Hlsl.Text; namespace ShaderTools.Tests.Hlsl.Support { internal sealed class InMemoryFileSystem : IIncludeFileSystem { private readonly Dictionary<string, string> _includes; public InMemoryFileSystem(Dictionary<string, string> includes) { _includes = includes; } public SourceText GetInclude(string path) { string include; return _includes.TryGetValue(path, out include) ? new StringText(include, path) : null; } } }<file_sep>/src/ShaderTools.VisualStudio.Tests/Hlsl/Tagging/Classification/SyntaxTaggerTests.cs using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Tagging; using NUnit.Framework; using ShaderTools.VisualStudio.Hlsl.Parsing; using ShaderTools.VisualStudio.Hlsl.Tagging.Classification; namespace ShaderTools.VisualStudio.Tests.Hlsl.Tagging.Classification { [TestFixture] internal class SyntaxTaggerTests : AsyncTaggerTestsBase<SyntaxTagger, IClassificationTag> { private HlslClassificationService _hlslClassificationService; protected override void OnTestFixtureSetUp() { _hlslClassificationService = Container.GetExportedValue<HlslClassificationService>(); } protected override SyntaxTagger CreateTagger(BackgroundParser backgroundParser, ITextBuffer textBuffer) { return new SyntaxTagger(_hlslClassificationService, backgroundParser); } } }<file_sep>/src/ShaderTools.VisualStudio/Hlsl/Navigation/GoToDefinitionProviders/IQuickInfoModelProvider.cs using ShaderTools.Core.Text; using ShaderTools.Hlsl.Compilation; using ShaderTools.Hlsl.Syntax; using ShaderTools.Hlsl.Text; namespace ShaderTools.VisualStudio.Hlsl.Navigation.GoToDefinitionProviders { internal interface IGoToDefinitionProvider { TextSpan? GetTargetSpan(SemanticModel semanticModel, SourceLocation position); } }<file_sep>/src/ShaderTools.Tests/Hlsl/Binding/UnaryExpressionTests.cs using System.Linq; using NUnit.Framework; using ShaderTools.Hlsl.Syntax; namespace ShaderTools.Tests.Hlsl.Binding { [TestFixture] public class UnaryExpressionTests { [TestCase("-", "float", "float")] [TestCase("!", "float2", "bool2")] public void TestPrefixUnaryOperatorTypeConversions(string opText, string argumentText, string expectedResult) { var argument = ExpressionTestUtility.GetValue(argumentText); var source = $"{opText}{argument}"; var syntaxTree = SyntaxFactory.ParseExpression(source); var syntaxTreeSource = syntaxTree.Root.ToString(); if (syntaxTreeSource != source) Assert.Fail($"Source should have been {syntaxTreeSource} but is {source}"); var expression = (PrefixUnaryExpressionSyntax)syntaxTree.Root; var compilation = new ShaderTools.Hlsl.Compilation.Compilation(syntaxTree); var semanticModel = compilation.GetSemanticModel(); var operandType = ExpressionTestUtility.GetExpressionTypeString(semanticModel.GetExpressionType(expression.Operand)); if (argumentText != operandType) Assert.Fail($"Operand should be of type '{argumentText}' but has type '{operandType}'"); var diagnostic = syntaxTree.GetDiagnostics().Concat(semanticModel.GetDiagnostics()).SingleOrDefault(); var expressionType = semanticModel.GetExpressionType(expression); var result = diagnostic == null ? ExpressionTestUtility.GetExpressionTypeString(expressionType) : ExpressionTestUtility.GetErrorString(diagnostic.DiagnosticId); Assert.AreEqual(expectedResult, result, $"Expression {source} should have evaluated to '{expectedResult}' but was '{result}'"); } } }<file_sep>/src/ShaderTools.VisualStudio/Hlsl/Util/Extensions/Extensions.cs using System; using System.Runtime.CompilerServices; using System.Threading; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using ShaderTools.Hlsl.Compilation; using ShaderTools.Hlsl.Parser; using ShaderTools.Hlsl.Syntax; using ShaderTools.Hlsl.Text; using ShaderTools.VisualStudio.Core.Text; using ShaderTools.VisualStudio.Core.Util; using ShaderTools.VisualStudio.Core.Util.Extensions; using ShaderTools.VisualStudio.Hlsl.Parsing; using ShaderTools.VisualStudio.Hlsl.Tagging.Classification; using ShaderTools.VisualStudio.Hlsl.Text; namespace ShaderTools.VisualStudio.Hlsl.Util.Extensions { internal static class Extensions { private static readonly ConditionalWeakTable<ITextSnapshot, SyntaxTree> CachedSyntaxTrees = new ConditionalWeakTable<ITextSnapshot, SyntaxTree>(); private static readonly ConditionalWeakTable<ITextSnapshot, SemanticModel> CachedSemanticModels = new ConditionalWeakTable<ITextSnapshot, SemanticModel>(); private static readonly object TextContainerKey = new object(); private static readonly object IncludeFileSystemKey = new object(); private static readonly object BackgroundParserKey = new object(); public static VisualStudioSourceTextContainer GetTextContainer(this ITextBuffer textBuffer) { return textBuffer.Properties.GetOrCreateSingletonProperty(TextContainerKey, () => new VisualStudioSourceTextContainer(textBuffer)); } public static IIncludeFileSystem GetIncludeFileSystem(this ITextBuffer textBuffer, VisualStudioSourceTextFactory sourceTextFactory) { return textBuffer.Properties.GetOrCreateSingletonProperty(IncludeFileSystemKey, () => new VisualStudioFileSystem(textBuffer.GetTextContainer(), sourceTextFactory)); } public static BackgroundParser GetBackgroundParser(this ITextBuffer textBuffer) { return textBuffer.Properties.GetOrCreateSingletonProperty(BackgroundParserKey, () => new BackgroundParser(textBuffer)); } public static SyntaxTagger GetSyntaxTagger(this ITextBuffer textBuffer) { return (SyntaxTagger) textBuffer.Properties.GetProperty(typeof(SyntaxTagger)); } public static SyntaxTree GetSyntaxTree(this ITextSnapshot snapshot, CancellationToken cancellationToken) { return CachedSyntaxTrees.GetValue(snapshot, key => { var sourceText = key.ToSourceText(); var options = new ParserOptions(); options.PreprocessorDefines.Add("__INTELLISENSE__"); var sourceTextFactory = VisualStudioSourceTextFactory.Instance ?? HlslPackage.Instance.AsVsServiceProvider().GetComponentModel().GetService<VisualStudioSourceTextFactory>(); var fileSystem = key.TextBuffer.GetIncludeFileSystem(sourceTextFactory); return SyntaxFactory.ParseSyntaxTree(sourceText, options, fileSystem, cancellationToken); }); } public static bool TryGetSemanticModel(this ITextSnapshot snapshot, CancellationToken cancellationToken, out SemanticModel semanticModel) { if (HlslPackage.Instance != null && !HlslPackage.Instance.Options.AdvancedOptions.EnableIntelliSense) { semanticModel = null; return false; } try { semanticModel = CachedSemanticModels.GetValue(snapshot, key => { try { var syntaxTree = key.GetSyntaxTree(cancellationToken); var compilation = new Compilation(syntaxTree); return compilation.GetSemanticModel(cancellationToken); } catch (OperationCanceledException) { throw; } catch (Exception ex) { Logger.Log($"Failed to create semantic model: {ex}"); return null; } }); } catch (OperationCanceledException) { semanticModel = null; } return semanticModel != null; } public static int GetPosition(this ITextView syntaxEditor, ITextSnapshot snapshot) { return syntaxEditor.Caret.Position.BufferPosition.TranslateTo(snapshot, PointTrackingMode.Negative); } // From https://github.com/dotnet/roslyn/blob/e39a3aeb1185ef0b349cad96a105969423065eac/src/EditorFeatures/Core/Shared/Extensions/ITextViewExtensions.cs#L278 public static int? GetDesiredIndentation(this ITextView textView, ISmartIndentationService smartIndentService, ITextSnapshotLine line) { var pointInView = textView.BufferGraph.MapUpToSnapshot(line.Start, PointTrackingMode.Positive, PositionAffinity.Successor, textView.TextSnapshot); if (!pointInView.HasValue) return null; var lineInView = textView.TextSnapshot.GetLineFromPosition(pointInView.Value.Position); return smartIndentService.GetDesiredIndentation(textView, lineInView); } } }<file_sep>/src/ShaderTools.VisualStudio/Hlsl/IntelliSense/Completion/CompletionProviders/ICompletionProvider.cs using System.Collections.Generic; using ShaderTools.Hlsl.Compilation; using ShaderTools.Hlsl.Syntax; namespace ShaderTools.VisualStudio.Hlsl.IntelliSense.Completion.CompletionProviders { internal interface ICompletionProvider { IEnumerable<CompletionItem> GetItems(SemanticModel semanticModel, SourceLocation position); } }<file_sep>/src/ShaderTools.VisualStudio/Hlsl/IntelliSense/QuickInfo/QuickInfoModelProviders/IQuickInfoModelProvider.cs using ShaderTools.Hlsl.Compilation; using ShaderTools.Hlsl.Syntax; namespace ShaderTools.VisualStudio.Hlsl.IntelliSense.QuickInfo.QuickInfoModelProviders { internal interface IQuickInfoModelProvider { int Priority { get; } QuickInfoModel GetModel(SemanticModel semanticModel, SourceLocation position); } }<file_sep>/src/ShaderTools.VisualStudio.Tests/Hlsl/Tagging/Outlining/OutliningTaggerTests.cs using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Tagging; using NUnit.Framework; using ShaderTools.VisualStudio.Hlsl.Parsing; using ShaderTools.VisualStudio.Hlsl.Tagging.Outlining; using ShaderTools.VisualStudio.Tests.Hlsl.Support; namespace ShaderTools.VisualStudio.Tests.Hlsl.Tagging.Outlining { [TestFixture] internal class OutliningTaggerTests : AsyncTaggerTestsBase<OutliningTagger, IOutliningRegionTag> { protected override OutliningTagger CreateTagger(BackgroundParser backgroundParser, ITextBuffer textBuffer) { return new OutliningTagger(textBuffer, backgroundParser, new FakeOptionsService()); } } }<file_sep>/src/ShaderTools.Tests/Hlsl/Binding/GlobalDeclarationTests.cs using System.Collections.Immutable; using System.Linq; using NUnit.Framework; using ShaderTools.Core.Text; using ShaderTools.Hlsl.Diagnostics; using ShaderTools.Hlsl.Syntax; using ShaderTools.Hlsl.Text; namespace ShaderTools.Tests.Hlsl.Binding { [TestFixture] public class GlobalDeclarationTests { [Test] public void DetectsRedefinitionAsVariable() { var code = @" struct foo {}; int foo;"; var syntaxTree = SyntaxFactory.ParseSyntaxTree(SourceText.From(code)); var compilation = new ShaderTools.Hlsl.Compilation.Compilation(syntaxTree); var semanticModel = compilation.GetSemanticModel(); var diagnostics = syntaxTree.GetDiagnostics().Concat(semanticModel.GetDiagnostics()).ToImmutableArray(); Assert.That(diagnostics, Has.Length.EqualTo(1)); Assert.That(diagnostics[0].DiagnosticId, Is.EqualTo(DiagnosticId.SymbolRedefined)); } [Test] public void DetectsRedefinitionAsFunction() { var code = @" struct foo {}; void foo();"; var syntaxTree = SyntaxFactory.ParseSyntaxTree(SourceText.From(code)); var compilation = new ShaderTools.Hlsl.Compilation.Compilation(syntaxTree); var semanticModel = compilation.GetSemanticModel(); var diagnostics = syntaxTree.GetDiagnostics().Concat(semanticModel.GetDiagnostics()).ToImmutableArray(); Assert.That(diagnostics, Has.Length.EqualTo(1)); Assert.That(diagnostics[0].DiagnosticId, Is.EqualTo(DiagnosticId.SymbolRedefined)); } [Test] public void DetectsUndeclaredVariable() { var code = @" void main() { int foo = a; }"; var syntaxTree = SyntaxFactory.ParseSyntaxTree(SourceText.From(code)); var compilation = new ShaderTools.Hlsl.Compilation.Compilation(syntaxTree); var semanticModel = compilation.GetSemanticModel(); var diagnostics = syntaxTree.GetDiagnostics().Concat(semanticModel.GetDiagnostics()).ToImmutableArray(); Assert.That(diagnostics, Has.Length.EqualTo(1)); Assert.That(diagnostics[0].DiagnosticId, Is.EqualTo(DiagnosticId.UndeclaredVariable)); } } }<file_sep>/src/ShaderTools.Tests/Hlsl/Parser/RoundtrippingTests.cs using System.IO; using NUnit.Framework; using ShaderTools.Core.Text; using ShaderTools.Hlsl.Syntax; using ShaderTools.Hlsl.Text; using ShaderTools.Tests.Hlsl.Support; namespace ShaderTools.Tests.Hlsl.Parser { [TestFixture] public class RoundtrippingTests { [TestCaseSource(typeof(ShaderTestUtility), nameof(ShaderTestUtility.GetTestShaders))] public void CanBuildSyntaxTree(string testFile) { var sourceCode = File.ReadAllText(testFile); // Build syntax tree. var syntaxTree = SyntaxFactory.ParseSyntaxTree(SourceText.From(sourceCode), fileSystem: new TestFileSystem(testFile)); ShaderTestUtility.CheckForParseErrors(syntaxTree); // Check roundtripping. var roundtrippedText = syntaxTree.Root.ToFullString(); Assert.That(roundtrippedText, Is.EqualTo(sourceCode)); } } }<file_sep>/src/ShaderTools.VisualStudio/Hlsl/Options/HlslFormattingIndentationOptionsPage.cs using System; using ShaderTools.Hlsl.Formatting; using ShaderTools.VisualStudio.Core.Options.Views; using ShaderTools.VisualStudio.Hlsl.Options.ViewModels; namespace ShaderTools.VisualStudio.Hlsl.Options { internal sealed class HlslFormattingIndentationOptionsPage : HlslOptionsPageBase<IndentationOptions> { protected override OptionsControlBase CreateControl(IServiceProvider serviceProvider) { return new OptionsPreviewControl(() => new FormattingIndentationViewModel(serviceProvider, Options)); } } }<file_sep>/src/ShaderTools.VisualStudio/Hlsl/Tagging/Squiggles/SyntaxErrorTagger.cs using System.Collections.Generic; using System.Threading; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Adornments; using Microsoft.VisualStudio.Text.Editor; using ShaderTools.Core.Diagnostics; using ShaderTools.VisualStudio.Core.Parsing; using ShaderTools.VisualStudio.Core.Tagging.Squiggles; using ShaderTools.VisualStudio.Hlsl.Options; using ShaderTools.VisualStudio.Hlsl.Parsing; using ShaderTools.VisualStudio.Hlsl.Util.Extensions; namespace ShaderTools.VisualStudio.Hlsl.Tagging.Squiggles { internal sealed class SyntaxErrorTagger : ErrorTagger { public SyntaxErrorTagger(ITextView textView, BackgroundParser backgroundParser, IHlslOptionsService optionsService) : base(PredefinedErrorTypeNames.SyntaxError, textView, optionsService) { backgroundParser.SubscribeToThrottledSyntaxTreeAvailable(BackgroundParserSubscriptionDelay.Medium, async x => await InvalidateTags(x.Snapshot, x.CancellationToken)); } protected override IEnumerable<DiagnosticBase> GetDiagnostics(ITextSnapshot snapshot, CancellationToken cancellationToken) { return snapshot.GetSyntaxTree(cancellationToken).GetDiagnostics(); } } }<file_sep>/src/ShaderTools.Tests/Unity/Support/ShaderTestUtility.cs using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using NUnit.Framework; using ShaderTools.Unity.Syntax; namespace ShaderTools.Tests.Unity.Support { public static class ShaderTestUtility { public static IEnumerable<TestCaseData> FindTestShaders(string rootFolder) { return Directory.GetFiles(rootFolder, "*.*", SearchOption.AllDirectories) .Where(x => { var ext = Path.GetExtension(x).ToLower(); return ext == ".shader"; }) .Select(x => new TestCaseData(x)); } internal static IEnumerable<TestCaseData> GetUnityTestShaders() { return FindTestShaders(@"Unity\Shaders"); } public static void CheckForParseErrors(SyntaxTree syntaxTree) { foreach (var diagnostic in syntaxTree.GetDiagnostics()) Debug.WriteLine(diagnostic.ToString()); Assert.That(syntaxTree.GetDiagnostics().Count(), Is.EqualTo(0)); } } }<file_sep>/src/ShaderTools.VisualStudio/Hlsl/Parsing/BackgroundParser.cs using System.Threading; using Microsoft.VisualStudio.Text; using ShaderTools.Hlsl.Compilation; using ShaderTools.VisualStudio.Core.Parsing; using ShaderTools.VisualStudio.Hlsl.Util.Extensions; namespace ShaderTools.VisualStudio.Hlsl.Parsing { internal sealed class BackgroundParser : BackgroundParserBase { public BackgroundParser(ITextBuffer textBuffer) : base(textBuffer) { } protected override void CreateSyntaxTree(ITextSnapshot snapshot, CancellationToken cancellationToken) { // Force creation of SyntaxTree. snapshot.GetSyntaxTree(cancellationToken); } protected override bool TryCreateSemanticModel(ITextSnapshot snapshot, CancellationToken cancellationToken) { // Force creation of SemanticModel. SemanticModel semanticModel; return snapshot.TryGetSemanticModel(cancellationToken, out semanticModel); } } }<file_sep>/src/ShaderTools.VisualStudio/ShaderLab/ErrorList/SyntaxErrorManager.cs using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using ShaderTools.Core.Diagnostics; using ShaderTools.VisualStudio.Core.ErrorList; using ShaderTools.VisualStudio.Core.Parsing; using ShaderTools.VisualStudio.Core.Util; using ShaderTools.VisualStudio.ShaderLab.Options; using ShaderTools.VisualStudio.ShaderLab.Parsing; using ShaderTools.VisualStudio.ShaderLab.Util.Extensions; namespace ShaderTools.VisualStudio.ShaderLab.ErrorList { internal sealed class SyntaxErrorManager : ErrorManager { public SyntaxErrorManager(BackgroundParser backgroundParser, ITextView textView, IShaderLabOptionsService optionsService, IServiceProvider serviceProvider, ITextDocumentFactoryService textDocumentFactoryService) : base(textView, optionsService, serviceProvider, textDocumentFactoryService) { backgroundParser.SubscribeToThrottledSyntaxTreeAvailable(BackgroundParserSubscriptionDelay.OnIdle, async x => await ExceptionHelper.TryCatchCancellation(() => { RefreshErrors(x.Snapshot, x.CancellationToken); return Task.FromResult(0); })); } protected override IEnumerable<DiagnosticBase> GetDiagnostics(ITextSnapshot snapshot, CancellationToken cancellationToken) { return snapshot.GetSyntaxTree(cancellationToken).GetDiagnostics(); } } }<file_sep>/src/ShaderTools.VisualStudio/Hlsl/Tagging/Squiggles/SemanticErrorTagger.cs using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Adornments; using Microsoft.VisualStudio.Text.Editor; using ShaderTools.Core.Diagnostics; using ShaderTools.Hlsl.Compilation; using ShaderTools.VisualStudio.Core.Parsing; using ShaderTools.VisualStudio.Core.Tagging.Squiggles; using ShaderTools.VisualStudio.Hlsl.Options; using ShaderTools.VisualStudio.Hlsl.Parsing; using ShaderTools.VisualStudio.Hlsl.Util.Extensions; namespace ShaderTools.VisualStudio.Hlsl.Tagging.Squiggles { internal sealed class SemanticErrorTagger : ErrorTagger { public SemanticErrorTagger(ITextView textView, BackgroundParser backgroundParser, IHlslOptionsService optionsService) : base(PredefinedErrorTypeNames.CompilerError, textView, optionsService) { backgroundParser.SubscribeToThrottledSemanticModelAvailable(BackgroundParserSubscriptionDelay.Medium, async x => await InvalidateTags(x.Snapshot, x.CancellationToken)); } protected override IEnumerable<DiagnosticBase> GetDiagnostics(ITextSnapshot snapshot, CancellationToken cancellationToken) { SemanticModel semanticModel; if (!snapshot.TryGetSemanticModel(cancellationToken, out semanticModel)) return Enumerable.Empty<DiagnosticBase>(); return semanticModel.GetDiagnostics(); } } }<file_sep>/src/ShaderTools/Hlsl/Syntax/SyntaxTree.cs using System; using System.Collections.Generic; using ShaderTools.Core.Text; using ShaderTools.Hlsl.Diagnostics; using ShaderTools.Hlsl.Parser; using ShaderTools.Hlsl.Text; namespace ShaderTools.Hlsl.Syntax { public sealed class SyntaxTree { private readonly List<FileSegment> _fileSegments; public SourceText Text { get; } public SyntaxNode Root { get; } internal SyntaxTree(SourceText text, Func<SyntaxTree, Tuple<SyntaxNode, List<FileSegment>>> parseFunc) { Text = text; var parsed = parseFunc(this); Root = parsed.Item1; _fileSegments = parsed.Item2; } public IEnumerable<Diagnostic> GetDiagnostics() { return Root.GetDiagnostics(); } public SourceLocation MapRootFilePosition(int position) { var runningTotal = 0; foreach (var fileSegment in _fileSegments) { if (fileSegment.Text.Filename == null && position < fileSegment.Start + fileSegment.Length) return new SourceLocation(runningTotal + (position - fileSegment.Start)); runningTotal += fileSegment.Length; } return new SourceLocation(runningTotal); } public SourceRange MapRootFileRange(TextSpan span) { return new SourceRange(MapRootFilePosition(span.Start), span.Length); } } }<file_sep>/src/ShaderTools.VisualStudio.Tests/Hlsl/Tagging/Squiggles/SyntaxErrorTaggerTests.cs using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Tagging; using NSubstitute; using NUnit.Framework; using ShaderTools.VisualStudio.Hlsl.Parsing; using ShaderTools.VisualStudio.Hlsl.Tagging.Squiggles; using ShaderTools.VisualStudio.Tests.Hlsl.Support; namespace ShaderTools.VisualStudio.Tests.Hlsl.Tagging.Squiggles { [TestFixture] internal class SyntaxErrorTaggerTests : AsyncTaggerTestsBase<SyntaxErrorTagger, IErrorTag> { protected override SyntaxErrorTagger CreateTagger(BackgroundParser backgroundParser, ITextBuffer textBuffer) { var textView = Substitute.For<ITextView>(); textView.TextSnapshot.Returns(textBuffer.CurrentSnapshot); return new SyntaxErrorTagger( textView, backgroundParser, new FakeOptionsService()); } protected override bool MustCreateTagSpans => false; } } <file_sep>/src/ShaderTools/Hlsl/Diagnostics/DiagnosticExtensions.cs using System.Collections.Generic; using System.Globalization; using System.Linq; using ShaderTools.Core.Text; using ShaderTools.Hlsl.Symbols; using ShaderTools.Hlsl.Syntax; using ShaderTools.Hlsl.Text; using ShaderTools.Properties; namespace ShaderTools.Hlsl.Diagnostics { internal static class DiagnosticExtensions { public static string GetMessage(this DiagnosticId diagnosticId) { return Resources.ResourceManager.GetString(diagnosticId.ToString()); } public static void Report(this ICollection<Diagnostic> diagnostics, TextSpan textSpan, DiagnosticId diagnosticId, params object[] args) { var diagnostic = Diagnostic.Format(textSpan, diagnosticId, args); diagnostics.Add(diagnostic); } #region Lexer errors public static void ReportIllegalInputCharacter(this ICollection<Diagnostic> diagnostics, TextSpan textSpan, char character) { diagnostics.Report(textSpan, DiagnosticId.IllegalInputCharacter, character); } public static void ReportUnterminatedComment(this ICollection<Diagnostic> diagnostics, TextSpan textSpan) { diagnostics.Report(textSpan, DiagnosticId.UnterminatedComment); } public static void ReportUnterminatedString(this ICollection<Diagnostic> diagnostics, TextSpan textSpan) { diagnostics.Report(textSpan, DiagnosticId.UnterminatedString); } public static void ReportInvalidInteger(this ICollection<Diagnostic> diagnostics, TextSpan textSpan, string tokenText) { diagnostics.Report(textSpan, DiagnosticId.InvalidInteger, tokenText); } public static void ReportInvalidReal(this ICollection<Diagnostic> diagnostics, TextSpan textSpan, string tokenText) { diagnostics.Report(textSpan, DiagnosticId.InvalidReal, tokenText); } public static void ReportInvalidOctal(this ICollection<Diagnostic> diagnostics, TextSpan textSpan, string tokenText) { diagnostics.Report(textSpan, DiagnosticId.InvalidOctal, tokenText); } public static void ReportInvalidHex(this ICollection<Diagnostic> diagnostics, TextSpan textSpan, string tokenText) { diagnostics.Report(textSpan, DiagnosticId.InvalidHex, tokenText); } public static void ReportNumberTooLarge(this ICollection<Diagnostic> diagnostics, TextSpan textSpan, string tokenText) { diagnostics.Report(textSpan, DiagnosticId.NumberTooLarge, tokenText); } #endregion #region Parser errors public static void ReportTokenExpected(this ICollection<Diagnostic> diagnostics, TextSpan span, SyntaxToken actual, SyntaxKind expected) { var actualText = actual.GetDisplayText(); var expectedText = expected.GetDisplayText(); diagnostics.Report(span, DiagnosticId.TokenExpected, actualText, expectedText); } public static void ReportTokenUnexpected(this ICollection<Diagnostic> diagnostics, TextSpan span, SyntaxToken actual) { var actualText = actual.GetDisplayText(); diagnostics.Report(span, DiagnosticId.TokenUnexpected, actualText); } public static void ReportNoVoidHere(this ICollection<Diagnostic> diagnostics, TextSpan textSpan) { diagnostics.Report(textSpan, DiagnosticId.NoVoidHere); } public static void ReportNoVoidParameter(this ICollection<Diagnostic> diagnostics, TextSpan textSpan) { diagnostics.Report(textSpan, DiagnosticId.NoVoidParameter); } #endregion #region Semantic errors public static void ReportUndeclaredType(this ICollection<Diagnostic> diagnostics, SyntaxNode type) { diagnostics.Report(type.GetTextSpanSafe(), DiagnosticId.UndeclaredType, type.ToStringIgnoringMacroReferences()); } public static void ReportUndeclaredFunction(this ICollection<Diagnostic> diagnostics, FunctionInvocationExpressionSyntax node, IEnumerable<TypeSymbol> argumentTypes) { var name = node.Name.ToStringIgnoringMacroReferences(); var argumentTypeList = string.Join(@", ", argumentTypes.Select(t => t.ToDisplayName())); diagnostics.Report(node.GetTextSpanSafe(), DiagnosticId.UndeclaredFunction, name, argumentTypeList); } public static void ReportUndeclaredNumericConstructor(this ICollection<Diagnostic> diagnostics, NumericConstructorInvocationExpressionSyntax node, IEnumerable<TypeSymbol> argumentTypes) { var name = node.Type.ToStringIgnoringMacroReferences(); var argumentTypeList = string.Join(@", ", argumentTypes.Select(t => t.ToDisplayName())); diagnostics.Report(node.GetTextSpanSafe(), DiagnosticId.UndeclaredFunction, name, argumentTypeList); } public static void ReportUndeclaredMethod(this ICollection<Diagnostic> diagnostics, MethodInvocationExpressionSyntax node, TypeSymbol declaringType, IEnumerable<TypeSymbol> argumentTypes) { var name = node.Name.ValueText; var declaringTypeName = declaringType.ToDisplayName(); var argumentTypeNames = string.Join(@", ", argumentTypes.Select(t => t.ToDisplayName())); diagnostics.Report(node.GetTextSpanRoot(), DiagnosticId.UndeclaredMethod, declaringTypeName, name, argumentTypeNames); } public static void ReportUndeclaredFunctionInNamespaceOrClass(this ICollection<Diagnostic> diagnostics, QualifiedDeclarationNameSyntax name) { var declaringTypeName = name.Left.ToStringIgnoringMacroReferences(); diagnostics.Report(name.GetTextSpanSafe(), DiagnosticId.UndeclaredFunctionInNamespaceOrClass, declaringTypeName, name.GetUnqualifiedName().Name.Text); } public static void ReportUndeclaredIndexer(this ICollection<Diagnostic> diagnostics, ElementAccessExpressionSyntax node, TypeSymbol declaringType, IEnumerable<TypeSymbol> argumentTypes) { var declaringTypeName = declaringType.ToDisplayName(); var argumentTypeNames = string.Join(@", ", argumentTypes.Select(t => t.ToDisplayName())); diagnostics.Report(node.GetTextSpanRoot(), DiagnosticId.UndeclaredIndexer, declaringTypeName, argumentTypeNames); } public static void ReportVariableNotDeclared(this ICollection<Diagnostic> diagnostics, SyntaxToken name) { diagnostics.Report(name.Span, DiagnosticId.UndeclaredVariable, name.ValueText); } public static void ReportUndeclaredField(this ICollection<Diagnostic> diagnostics, FieldAccessExpressionSyntax node, TypeSymbol type) { var typeName = type.ToDisplayName(); var propertyName = node.Name.ValueText; diagnostics.Report(node.GetTextSpanSafe(), DiagnosticId.UndeclaredField, typeName, propertyName); } public static void ReportUndeclaredNamespaceOrType(this ICollection<Diagnostic> diagnostics, QualifiedDeclarationNameSyntax node) { var typeName = node.Left.ToStringIgnoringMacroReferences(); diagnostics.Report(node.GetTextSpanSafe(), DiagnosticId.UndeclaredNamespaceOrType, typeName); } public static void ReportAmbiguousInvocation(this ICollection<Diagnostic> diagnostics, TextSpan span, InvocableSymbol symbol1, InvocableSymbol symbol2, IReadOnlyList<TypeSymbol> argumentTypes) { if (argumentTypes.Count > 0) { var displayTypes = string.Join(@", ", argumentTypes.Select(t => t.ToDisplayName())); diagnostics.Report(span, DiagnosticId.AmbiguousInvocation, symbol1, symbol2, displayTypes); } else { var message = string.Format(CultureInfo.CurrentCulture, "Invocation is ambiguous between '{0}' and '{1}'.", symbol1, symbol2); var diagnostic = new Diagnostic(span, DiagnosticId.AmbiguousInvocation, message); diagnostics.Add(diagnostic); } } public static void ReportAmbiguousField(this ICollection<Diagnostic> diagnostics, SyntaxToken name) { diagnostics.Report(name.Span, DiagnosticId.AmbiguousField, name.ValueText); } public static void ReportCannotConvert(this ICollection<Diagnostic> diagnostics, TextSpan span, TypeSymbol sourceType, TypeSymbol targetType) { var sourceTypeName = sourceType.ToDisplayName(); var targetTypeName = targetType.ToDisplayName(); diagnostics.Report(span, DiagnosticId.CannotConvert, sourceTypeName, targetTypeName); } public static void ReportAmbiguousName(this ICollection<Diagnostic> diagnostics, SyntaxToken name, IReadOnlyList<Symbol> candidates) { var symbol1 = candidates[0]; var symbol2 = candidates[1]; diagnostics.Report(name.Span, DiagnosticId.AmbiguousReference, name.ValueText, symbol1.Name, symbol2.Name); } public static void ReportAmbiguousType(this ICollection<Diagnostic> diagnostics, SyntaxToken name, IReadOnlyList<Symbol> candidates) { var symbol1 = candidates[0]; var symbol2 = candidates[1]; diagnostics.Report(name.Span, DiagnosticId.AmbiguousType, name.ValueText, symbol1.Name, symbol2.Name); } public static void ReportAmbiguousNamespaceOrType(this ICollection<Diagnostic> diagnostics, QualifiedDeclarationNameSyntax syntax, IReadOnlyList<Symbol> candidates) { var symbol1 = candidates[0]; var symbol2 = candidates[1]; diagnostics.Report(syntax.GetTextSpanSafe(), DiagnosticId.AmbiguousNamespaceOrType, syntax.ToStringIgnoringMacroReferences(), symbol1.Name, symbol2.Name); } public static void ReportInvocationRequiresParenthesis(this ICollection<Diagnostic> diagnostics, SyntaxToken name) { diagnostics.Report(name.Span, DiagnosticId.InvocationRequiresParenthesis, name.ValueText); } public static void ReportCannotApplyBinaryOperator(this ICollection<Diagnostic> diagnostics, SyntaxToken operatorToken, TypeSymbol leftType, TypeSymbol rightType) { var operatorName = operatorToken.Text; var leftTypeName = leftType.ToDisplayName(); var rightTypeName = rightType.ToDisplayName(); diagnostics.Report(operatorToken.Span, DiagnosticId.CannotApplyBinaryOperator, operatorName, leftTypeName, rightTypeName); } public static void ReportAmbiguousBinaryOperator(this ICollection<Diagnostic> diagnostics, SyntaxToken operatorToken, TypeSymbol leftType, TypeSymbol rightType) { var operatorName = operatorToken.Text; var leftTypeName = leftType.ToDisplayName(); var rightTypeName = rightType.ToDisplayName(); diagnostics.Report(operatorToken.Span, DiagnosticId.AmbiguousBinaryOperator, operatorName, leftTypeName, rightTypeName); } public static void ReportCannotApplyUnaryOperator(this ICollection<Diagnostic> diagnostics, SyntaxToken operatorToken, TypeSymbol type) { var operatorName = operatorToken.Text; var typeName = type.ToDisplayName(); diagnostics.Report(operatorToken.Span, DiagnosticId.CannotApplyUnaryOperator, operatorName, typeName); } public static void ReportAmbiguousUnaryOperator(this ICollection<Diagnostic> diagnostics, SyntaxToken operatorToken, TypeSymbol type) { var operatorName = operatorToken.Text; var typeName = type.ToDisplayName(); diagnostics.Report(operatorToken.Span, DiagnosticId.AmbiguousUnaryOperator, operatorName, typeName); } public static void ReportFunctionMissingImplementation(this ICollection<Diagnostic> diagnostics, FunctionInvocationExpressionSyntax syntax) { diagnostics.Report(syntax.Name.GetTextSpanSafe(), DiagnosticId.FunctionMissingImplementation, syntax.Name.ToStringIgnoringMacroReferences()); } public static void ReportMethodMissingImplementation(this ICollection<Diagnostic> diagnostics, MethodInvocationExpressionSyntax syntax) { diagnostics.Report(syntax.Name.Span, DiagnosticId.FunctionMissingImplementation, syntax.Name.Text); } public static void ReportSymbolRedefined(this ICollection<Diagnostic> diagnostics, TextSpan span, Symbol symbol) { diagnostics.Report(span, DiagnosticId.SymbolRedefined, symbol.Name); } public static void ReportLoopControlVariableConflict(this ICollection<Diagnostic> diagnostics, VariableDeclaratorSyntax syntax) { diagnostics.Report(syntax.Identifier.Span, DiagnosticId.LoopControlVariableConflict, syntax.Identifier.Text); } public static void ReportImplicitTruncation(this ICollection<Diagnostic> diagnostics, TextSpan span, TypeSymbol sourceType, TypeSymbol destinationType) { diagnostics.Report(span, DiagnosticId.ImplicitTruncation, sourceType.Name, destinationType.Name); } #endregion } }<file_sep>/src/ShaderTools/Hlsl/Text/IIncludeFileSystem.cs using ShaderTools.Core.Text; namespace ShaderTools.Hlsl.Text { public interface IIncludeFileSystem { SourceText GetInclude(string path); } }<file_sep>/src/ShaderTools.Tests/Hlsl/Support/TestFileSystem.cs using System.IO; using ShaderTools.Core.Text; using ShaderTools.Hlsl.Text; namespace ShaderTools.Tests.Hlsl.Support { public sealed class TestFileSystem : IIncludeFileSystem { private readonly string _parentDirectory; public TestFileSystem(string parentFile) { _parentDirectory = Path.GetDirectoryName(parentFile); } public SourceText GetInclude(string path) { return new StringText(File.ReadAllText(Path.Combine(_parentDirectory, path)), path); } } }<file_sep>/README.md # Shader Tools for Visual Studio [![Join the chat at https://gitter.im/tgjones/HlslTools](https://badges.gitter.im/tgjones/HlslTools.svg)](https://gitter.im/tgjones/HlslTools) A Visual Studio extension that provides enhanced support for editing High Level Shading Language (HLSL) files and Unity ShaderLab shaders. Shader Tools works with both Visual Studio 2015 and Visual Studio 2017. [![Build status](https://ci.appveyor.com/api/projects/status/4ykbwleeg5c8o1l4?svg=true)](https://ci.appveyor.com/project/tgjones/hlsltools) [![Issue Stats](http://www.issuestats.com/github/tgjones/hlsltools/badge/pr?style=flat-square)](http://www.issuestats.com/github/tgjones/hlsltools) [![Issue Stats](http://www.issuestats.com/github/tgjones/hlsltools/badge/issue?style=flat-square)](http://www.issuestats.com/github/tgjones/hlsltools) Download the extension at the [VS Gallery](https://visualstudiogallery.msdn.microsoft.com/75ddd3be-6eda-4433-a850-458b51186658) or get the [nightly build](http://vsixgallery.com/extension/7def6c01-a05e-42e6-953d-3fdea1891737/). See the [changelog](CHANGELOG.md) for changes and roadmap. ### Why use Shader Tools? Visual Studio itself includes basic support for editing HLSL files - and, with Visual Studio Tools for Unity installed, it also includes basic support for editing Unity shaders. In addition to those basic features, Shader Tools for Visual Studio includes many more navigational and editing features: <table> <thead> <tr> <th rowspan="2"></th> <th colspan="2">HLSL</th> <th colspan="2">Unity ShaderLab</th> </tr> <tr> <th>Visual Studio</th> <th>Shader Tools</th> <th>VS Tools for Unity</th> <th>Shader Tools</th> </tr> </thead> <tbody> <tr> <td>Syntax highlighting</td> <td>✓</td> <td>✓</td> <td>✓</td> <td>✓</td> </tr> <tr> <td>Automatic formatting</td> <td>✓</td> <td>✓</td> <td>✓</td> <td>✓</td> </tr> <tr> <td>Brace matching</td> <td>✓</td> <td>✓</td> <td>✓</td> <td>✓</td> </tr> <tr> <td>Brace completion</td> <td>✓</td> <td>✓</td> <td>✓</td> <td>✓</td> </tr> <tr> <td>Outlining</td> <td>✓</td> <td>✓</td> <td>✓</td> <td>✓</td> </tr> <tr> <td><a href="#statement-completion">Statement completion</a></td> <td></td> <td>✓</td> <td></td> <td></td> </tr> <tr> <td><a href="#signature-help">Signature help</a></td> <td></td> <td>✓</td> <td></td> <td></td> </tr> <tr> <td><a href="#reference-highlighting">Reference highlighting</a></td> <td></td> <td>✓</td> <td></td> <td></td> </tr> <tr> <td><a href="#navigation-bar">Navigation bar</a></td> <td></td> <td>✓</td> <td></td> <td></td> </tr> <tr> <td><a href="#navigate-to">Navigate to (Ctrl+,)</a></td> <td></td> <td>✓</td> <td></td> <td></td> </tr> <tr> <td><a href="#live-errors">Live errors</a></td> <td></td> <td>✓</td> <td></td> <td>✓</td> </tr> <tr> <td><a href="#go-to-definition">Go to definition</a></td> <td></td> <td>✓</td> <td></td> <td>✓</td> </tr> <tr> <td><a href="#quick-info">Quick info</a></td> <td></td> <td>✓</td> <td></td> <td></td> </tr> <tr> <td><a href="#preprocessor-support">Gray out code excluded by preprocessor</a></td> <td></td> <td>✓</td> <td></td> <td></td> </tr> <tr> <td><a href="#options">Language-specific preferences</a></td> <td></td> <td>✓</td> <td></td> <td>✓</td> </tr> </tbody> </table> There are more features [on the roadmap](CHANGELOG.md). ### Features #### Statement completion Just start typing, and Shader Tools will show you a list of the available symbols (variables, functions, etc.) at that location. You can manually trigger this with the usual shortcuts: `Ctrl+J`, `Ctrl+Space`, etc. ![Statement completion demo](art/statement-completion.gif) #### Signature help Signature help (a.k.a. parameter info) shows you all the overloads for a function call, along with information (from MSDN) about the function, its parameters, and return types. Typing an open parenthesis will trigger statement completion, as will the standard `Ctrl+Shift+Space` shortcut. Signature help is available for all HLSL functions and methods, including the older `tex2D`-style texture sampling functions, and the newer `Texture2D.Sample`-style methods. ![Signature help demo](art/signature-help.gif) #### Reference highlighting Placing the cursor within a symbol (local variable, function name, etc.) will cause all references to that symbol to be highlighted. Navigate between references using `Ctrl+Shift+Up` and `Ctrl+Shift+Down`. ![Reference highlighting demo](art/reference-highlighting.gif) #### Navigation bar ![Navigation bar demo](art/navigation-bar.gif) #### Navigate To Shader Tools supports Visual Studio's Navigate To feature. Activate it with `Ctrl+,`, and start typing the name of the variable, function, or other symbol that you want to find. ![Navigate To demo](art/navigate-to.gif) #### Live errors Shader Tools shows you syntax and semantic errors immediately. No need to wait till compilation! Errors are shown as squigglies and in the error list. ![Live errors demo](art/live-errors.gif) #### Go to definition Press F12 to go to a symbol definition. Go to definition works for variables, fields, functions, classes, macros, and more. ![Go to definition demo](art/go-to-definition.gif) #### Quick info Hover over almost anything (variable, field, function call, macro, semantic, type, etc.) to see a Quick Info tooltip. ![Quick info demo](art/quick-info.gif) #### Preprocessor support Shader Tools evaluates preprocessor directives as it parses your HLSL code, and grays out excluded code. If you want to make a code block visible to, or hidden from, Shader Tools, use the `__INTELLISENSE__` macro: ![__INTELLISENSE__ macro demo](art/intellisense-macro.gif) #### Options Configure HLSL- and ShaderLab-specific IntelliSense and formatting options. If you really want to, you can disable IntelliSense altogether and just use Shader Tools' other features. You can also set HLSL- and ShaderLab-specific highlighting colours in Tools > Options > Environment > Fonts and Colors. ![Options demo](art/options.gif) ### Extras #### The code Shader Tools includes [handwritten parsers for HLSL and ShaderLab](https://github.com/tgjones/HlslTools/blob/master/src/ShaderTools). It initially used an ANTLR lexer and parser, but the handwritten version was faster, and offered better error recovery. Shader Tools has a reasonable test suite - although it can certainly be improved. Amongst more granular tests, it includes a suite of 433 shaders, including all of the shaders from the DirectX and Nvidia SDKs, and Unity's built-in shaders. If you want to contribute gnarly source files that push HLSL and ShaderLab to its limit, that would be great! #### Syntax visualizer Inspired by Roslyn, Shader Tools includes a syntax visualizer for HLSL source files. It's primarily of interest to Shader Tools developers, but may be of interest to language nerds, so it's included in the main extension. Open it using `View > Other Windows > HLSL Syntax Visualizer`. ![Syntax visualizer demo](art/syntax-visualizer.gif) ### Getting involved You can ask questions in our [Gitter room](https://gitter.im/tgjones/HlslTools). If you find a bug or want to request a feature, [create an issue here ](https://github.com/tgjones/HlslTools/issues). You can find me on Twitter at [@\_tim_jones\_](https://twitter.com/_tim_jones_) and I tweet about Shader Tools using the [#shadertools](https://twitter.com/hashtag/shadertools) hashtag. Contributions are always welcome. [Please read the contributing guide first.](CONTRIBUTING.md) ### Maintainer(s) * [@tgjones](https://github.com/tgjones) ### Acknowledgements * Much of the code structure, and some of the actual code, comes from [Roslyn](https://github.com/dotnet/roslyn). * [NQuery-vnext](https://github.com/terrajobst/nquery-vnext) is a nice example of a simplified Roslyn-style API, and Shader Tools borrows some of its ideas and code. * [Node.js Tools for Visual Studio](https://github.com/Microsoft/nodejstools) and [Python Tools for Visual Studio](https://github.com/Microsoft/PTVS) are amongst the best examples of how to build a language service for Visual Studio, and were a great help. * [ScriptSharp](https://github.com/nikhilk/scriptsharp) is one of the older open-source .NET-related compilers, and is still a great example of how to structure a compiler. * [LangSvcV2](https://github.com/tunnelvisionlabs/LangSvcV2) includes many nice abstractions for some of the more complicated parts of Visual Studio's language service support. <file_sep>/src/ShaderTools.Tests/Hlsl/Binding/FunctionDeclarationTests.cs using System.Collections.Immutable; using System.Linq; using NUnit.Framework; using ShaderTools.Core.Text; using ShaderTools.Hlsl.Diagnostics; using ShaderTools.Hlsl.Syntax; using ShaderTools.Hlsl.Text; namespace ShaderTools.Tests.Hlsl.Binding { [TestFixture] public class FunctionDeclarationTests { [Test] public void DetectsFunctionRedefinition() { var code = @" void foo() {} void foo() {}"; var syntaxTree = SyntaxFactory.ParseSyntaxTree(SourceText.From(code)); var compilation = new ShaderTools.Hlsl.Compilation.Compilation(syntaxTree); var semanticModel = compilation.GetSemanticModel(); var diagnostics = syntaxTree.GetDiagnostics().Concat(semanticModel.GetDiagnostics()).ToImmutableArray(); Assert.That(diagnostics, Has.Length.EqualTo(1)); Assert.That(diagnostics[0].DiagnosticId, Is.EqualTo(DiagnosticId.SymbolRedefined)); } [Test] public void AllowsFunctionOverloads() { var code = @" void foo(int x) {} void foo() {}"; var syntaxTree = SyntaxFactory.ParseSyntaxTree(SourceText.From(code)); var compilation = new ShaderTools.Hlsl.Compilation.Compilation(syntaxTree); var semanticModel = compilation.GetSemanticModel(); var diagnostics = syntaxTree.GetDiagnostics().Concat(semanticModel.GetDiagnostics()).ToImmutableArray(); Assert.That(diagnostics, Is.Empty); } [Test] public void AllowsMultipleMatchingFunctionDeclarations() { var code = @" void foo(); void foo();"; var syntaxTree = SyntaxFactory.ParseSyntaxTree(SourceText.From(code)); var compilation = new ShaderTools.Hlsl.Compilation.Compilation(syntaxTree); var semanticModel = compilation.GetSemanticModel(); var diagnostics = syntaxTree.GetDiagnostics().Concat(semanticModel.GetDiagnostics()).ToImmutableArray(); Assert.That(diagnostics, Is.Empty); } [Test] public void AllowsMissingFunctionImplementationIfUnused() { var code = @"void foo();"; var syntaxTree = SyntaxFactory.ParseSyntaxTree(SourceText.From(code)); var compilation = new ShaderTools.Hlsl.Compilation.Compilation(syntaxTree); var semanticModel = compilation.GetSemanticModel(); var diagnostics = syntaxTree.GetDiagnostics().Concat(semanticModel.GetDiagnostics()).ToImmutableArray(); Assert.That(diagnostics, Is.Empty); } [Test] public void DetectsMissingFunctionImplementation() { var code = @" void foo(); void main() { foo(); }"; var syntaxTree = SyntaxFactory.ParseSyntaxTree(SourceText.From(code)); var compilation = new ShaderTools.Hlsl.Compilation.Compilation(syntaxTree); var semanticModel = compilation.GetSemanticModel(); var diagnostics = syntaxTree.GetDiagnostics().Concat(semanticModel.GetDiagnostics()).ToImmutableArray(); Assert.That(diagnostics, Has.Length.EqualTo(1)); Assert.That(diagnostics[0].DiagnosticId, Is.EqualTo(DiagnosticId.FunctionMissingImplementation)); } } }<file_sep>/src/ShaderTools.VisualStudio.Tests/Hlsl/Tagging/Classification/SemanticTaggerTests.cs using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Tagging; using NUnit.Framework; using ShaderTools.VisualStudio.Hlsl.Parsing; using ShaderTools.VisualStudio.Hlsl.Tagging.Classification; namespace ShaderTools.VisualStudio.Tests.Hlsl.Tagging.Classification { [TestFixture] internal class SemanticTaggerTests : AsyncTaggerTestsBase<SemanticTagger, IClassificationTag> { private HlslClassificationService _hlslClassificationService; protected override void OnTestFixtureSetUp() { _hlslClassificationService = Container.GetExportedValue<HlslClassificationService>(); } protected override SemanticTagger CreateTagger(BackgroundParser backgroundParser, ITextBuffer textBuffer) { return new SemanticTagger(_hlslClassificationService, backgroundParser); } } }<file_sep>/src/ShaderTools/Core/Diagnostics/DiagnosticBase.cs using System.Globalization; using ShaderTools.Core.Diagnostics; using ShaderTools.Core.Text; namespace ShaderTools.Core.Diagnostics { public abstract class DiagnosticBase { public TextSpan Span { get; } public string Message { get; } public DiagnosticSeverity Severity { get; } protected DiagnosticBase(TextSpan textSpan, string message, DiagnosticSeverity severity) { Span = textSpan; Message = message; Severity = severity; } public override string ToString() { return $"{Span} {Message}"; } } }<file_sep>/src/ShaderTools.VisualStudio/Core/Tagging/Squiggles/ErrorTagger.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Tagging; using ShaderTools.Core.Diagnostics; using ShaderTools.VisualStudio.Core.Options; namespace ShaderTools.VisualStudio.Core.Tagging.Squiggles { internal abstract class ErrorTagger : AsyncTagger<IErrorTag> { private readonly string _errorType; private readonly ITextView _textView; private readonly IOptionsService _optionsService; private bool _squigglesEnabled; protected ErrorTagger(string errorType, ITextView textView, IOptionsService optionsService) { _errorType = errorType; _textView = textView; _optionsService = optionsService; optionsService.OptionsChanged += OnOptionsChanged; textView.Closed += OnViewClosed; OnOptionsChanged(this, EventArgs.Empty); } private async void OnOptionsChanged(object sender, EventArgs e) { _squigglesEnabled = _optionsService.EnableErrorReporting && _optionsService.EnableSquiggles; await InvalidateTags(_textView.TextSnapshot, CancellationToken.None); } protected ITagSpan<IErrorTag> CreateTagSpan(ITextSnapshot snapshot, DiagnosticBase diagnostic, bool squigglesEnabled) { var span = new Span(diagnostic.Span.Start, diagnostic.Span.Length); var snapshotSpan = new SnapshotSpan(snapshot, span); var errorTag = new ErrorTag(_errorType, diagnostic.Message); var errorTagSpan = new TagSpan<IErrorTag>(snapshotSpan, errorTag); return errorTagSpan; } private void OnViewClosed(object sender, EventArgs e) { _optionsService.OptionsChanged -= OnOptionsChanged; var view = (IWpfTextView)sender; view.Closed -= OnViewClosed; } protected override Tuple<ITextSnapshot, List<ITagSpan<IErrorTag>>> GetTags(ITextSnapshot snapshot, CancellationToken cancellationToken) { if (!_squigglesEnabled) return Tuple.Create(snapshot, new List<ITagSpan<IErrorTag>>()); var tagSpans = GetDiagnostics(snapshot, cancellationToken) .Where(x => x.Span.IsInRootFile) .Select(d => CreateTagSpan(snapshot, d, _squigglesEnabled)) .Where(x => x != null) .ToList(); return Tuple.Create(snapshot, tagSpans); } protected abstract IEnumerable<DiagnosticBase> GetDiagnostics(ITextSnapshot snapshot, CancellationToken cancellationToken); } }<file_sep>/src/ShaderTools.Tests/Hlsl/Symbols/IntrinsicTypesTests.cs using NUnit.Framework; using ShaderTools.Hlsl.Symbols; namespace ShaderTools.Tests.Hlsl.Symbols { [TestFixture] public class IntrinsicTypesTests { [Test] public void VectorTypesHaveCorrectFields() { var float1Type = IntrinsicTypes.Float1; Assert.That(float1Type.Members, Has.Length.EqualTo(9)); Assert.That(float1Type.Members[0].Name, Is.EqualTo("x")); Assert.That(float1Type.Members[1].Name, Is.EqualTo("xx")); Assert.That(float1Type.Members[2].Name, Is.EqualTo("xxx")); Assert.That(float1Type.Members[3].Name, Is.EqualTo("xxxx")); Assert.That(float1Type.Members[4].Name, Is.EqualTo("r")); Assert.That(float1Type.Members[5].Name, Is.EqualTo("rr")); Assert.That(float1Type.Members[6].Name, Is.EqualTo("rrr")); Assert.That(float1Type.Members[7].Name, Is.EqualTo("rrrr")); var float2Type = IntrinsicTypes.Float2; Assert.That(float2Type.Members, Has.Length.EqualTo(61)); Assert.That(float2Type.Members[0].Name, Is.EqualTo("x")); Assert.That(float2Type.Members[1].Name, Is.EqualTo("y")); Assert.That(float2Type.Members[2].Name, Is.EqualTo("xx")); Assert.That(float2Type.Members[3].Name, Is.EqualTo("xy")); Assert.That(float2Type.Members[4].Name, Is.EqualTo("yx")); Assert.That(float2Type.Members[5].Name, Is.EqualTo("yy")); Assert.That(float2Type.Members[6].Name, Is.EqualTo("xxx")); Assert.That(float2Type.Members[7].Name, Is.EqualTo("xxy")); Assert.That(float2Type.Members[8].Name, Is.EqualTo("xyx")); Assert.That(float2Type.Members[9].Name, Is.EqualTo("xyy")); Assert.That(float2Type.Members[10].Name, Is.EqualTo("yxx")); Assert.That(float2Type.Members[11].Name, Is.EqualTo("yxy")); Assert.That(float2Type.Members[12].Name, Is.EqualTo("yyx")); Assert.That(float2Type.Members[13].Name, Is.EqualTo("yyy")); Assert.That(float2Type.Members[14].Name, Is.EqualTo("xxxx")); Assert.That(float2Type.Members[15].Name, Is.EqualTo("xxxy")); Assert.That(float2Type.Members[16].Name, Is.EqualTo("xxyx")); Assert.That(float2Type.Members[17].Name, Is.EqualTo("xxyy")); Assert.That(float2Type.Members[18].Name, Is.EqualTo("xyxx")); Assert.That(float2Type.Members[19].Name, Is.EqualTo("xyxy")); Assert.That(float2Type.Members[20].Name, Is.EqualTo("xyyx")); Assert.That(float2Type.Members[21].Name, Is.EqualTo("xyyy")); Assert.That(float2Type.Members[22].Name, Is.EqualTo("yxxx")); Assert.That(float2Type.Members[23].Name, Is.EqualTo("yxxy")); Assert.That(float2Type.Members[24].Name, Is.EqualTo("yxyx")); Assert.That(float2Type.Members[25].Name, Is.EqualTo("yxyy")); Assert.That(float2Type.Members[26].Name, Is.EqualTo("yyxx")); Assert.That(float2Type.Members[27].Name, Is.EqualTo("yyxy")); Assert.That(float2Type.Members[28].Name, Is.EqualTo("yyyx")); Assert.That(float2Type.Members[29].Name, Is.EqualTo("yyyy")); Assert.That(float2Type.Members[30].Name, Is.EqualTo("r")); Assert.That(float2Type.Members[59].Name, Is.EqualTo("gggg")); var float3Type = IntrinsicTypes.Float3; Assert.That(float3Type.Members, Has.Length.EqualTo(241)); var float4Type = IntrinsicTypes.Float4; Assert.That(float4Type.Members, Has.Length.EqualTo(681)); } [Test] public void MatrixTypesHaveCorrectFields() { var matrix1x1Type = IntrinsicTypes.Float1x1; Assert.That(matrix1x1Type.Members, Has.Length.EqualTo(9)); Assert.That(matrix1x1Type.Members[0].Name, Is.EqualTo("_m00")); Assert.That(matrix1x1Type.Members[1].Name, Is.EqualTo("_m00_m00")); Assert.That(matrix1x1Type.Members[2].Name, Is.EqualTo("_m00_m00_m00")); Assert.That(matrix1x1Type.Members[3].Name, Is.EqualTo("_m00_m00_m00_m00")); Assert.That(matrix1x1Type.Members[4].Name, Is.EqualTo("_11")); Assert.That(matrix1x1Type.Members[5].Name, Is.EqualTo("_11_11")); Assert.That(matrix1x1Type.Members[6].Name, Is.EqualTo("_11_11_11")); Assert.That(matrix1x1Type.Members[7].Name, Is.EqualTo("_11_11_11_11")); var matrix1x2Type = IntrinsicTypes.Float1x2; Assert.That(matrix1x2Type.Members, Has.Length.EqualTo(61)); Assert.That(matrix1x1Type.Members[0].Name, Is.EqualTo("_m00")); Assert.That(matrix1x2Type.Members[1].Name, Is.EqualTo("_m01")); Assert.That(matrix1x2Type.Members[2].Name, Is.EqualTo("_m00_m00")); Assert.That(matrix1x2Type.Members[3].Name, Is.EqualTo("_m00_m01")); Assert.That(matrix1x2Type.Members[4].Name, Is.EqualTo("_m01_m00")); Assert.That(matrix1x2Type.Members[5].Name, Is.EqualTo("_m01_m01")); Assert.That(matrix1x2Type.Members[6].Name, Is.EqualTo("_m00_m00_m00")); var matrix2x2Type = IntrinsicTypes.Float2x2; Assert.That(matrix2x2Type.Members, Has.Length.EqualTo(681)); var matrix4x4Type = IntrinsicTypes.Float4x4; Assert.That(matrix4x4Type.Members, Has.Length.EqualTo(139809)); } } }<file_sep>/src/ShaderTools.VisualStudio/Properties/AssemblyInfo.cs using System; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using ShaderTools.VisualStudio.Hlsl; [assembly: AssemblyTitle("Shader Tools for Visual Studio")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("<NAME>")] [assembly: AssemblyProduct("Shader Tools for Visual Studio")] [assembly: AssemblyCopyright("Copyright © 2015-2016 <NAME>")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: CLSCompliant(false)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyVersion(HlslPackage.Version)] [assembly: AssemblyFileVersion(HlslPackage.Version)] [assembly: InternalsVisibleTo("ShaderTools.VisualStudio.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100db0e6b6325cc8d19c80ca770a04910ef5fa65f56adf2b3b5edf9941d151fa4441fb64c68f93b61491fe730fc97a0fff117482b91476b55310e7ef8b90dc0f88974fabbff0f410fbe5a709df50ba1892e01152656f590e1e1670d7ba006708dba2a4410217ba5a478d499e2d08748b9e2ee09a03e97100c9a5d2218c90ebfc9b9")] [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")]<file_sep>/src/ShaderTools.Tests/Hlsl/Compilation/SemanticModelTests.cs using System.Diagnostics; using System.IO; using System.Linq; using NUnit.Framework; using ShaderTools.Core.Diagnostics; using ShaderTools.Core.Text; using ShaderTools.Hlsl.Symbols; using ShaderTools.Hlsl.Syntax; using ShaderTools.Tests.Hlsl.Support; namespace ShaderTools.Tests.Hlsl.Compilation { [TestFixture] public class SemanticModelTests { [TestCaseSource(typeof(ShaderTestUtility), nameof(ShaderTestUtility.GetTestShaders))] public void CanGetSemanticModel(string testFile) { var sourceCode = File.ReadAllText(testFile); // Build syntax tree. var syntaxTree = SyntaxFactory.ParseSyntaxTree(SourceText.From(sourceCode), fileSystem: new TestFileSystem(testFile)); ShaderTestUtility.CheckForParseErrors(syntaxTree); // Get semantic model. var compilation = new ShaderTools.Hlsl.Compilation.Compilation(syntaxTree); var semanticModel = compilation.GetSemanticModel(); Assert.That(semanticModel, Is.Not.Null); foreach (var diagnostic in semanticModel.GetDiagnostics()) Debug.WriteLine(diagnostic); Assert.That(semanticModel.GetDiagnostics().Count(x => x.Severity == DiagnosticSeverity.Error), Is.EqualTo(0)); } [Test] public void SemanticModelForStructAndFunction() { var syntaxTree = SyntaxFactory.ParseSyntaxTree(SourceText.From(@" struct MyStruct { float a; int b; }; void MyFunc() { MyStruct s; s.a = 1.0; }")); var compilation = new ShaderTools.Hlsl.Compilation.Compilation(syntaxTree); var semanticModel = compilation.GetSemanticModel(); var structDefinition = (TypeDeclarationStatementSyntax) syntaxTree.Root.ChildNodes[0]; var functionDefinition = (FunctionDefinitionSyntax) syntaxTree.Root.ChildNodes[1]; var variableDeclaration = (VariableDeclarationStatementSyntax) functionDefinition.Body.Statements[0]; var assignmentStatement = (ExpressionStatementSyntax) functionDefinition.Body.Statements[1]; var structSymbol = semanticModel.GetDeclaredSymbol((StructTypeSyntax) structDefinition.Type); Assert.That(structSymbol, Is.Not.Null); Assert.That(structSymbol.Name, Is.EqualTo("MyStruct")); Assert.That(structSymbol.Members, Has.Length.EqualTo(2)); var functionSymbol = semanticModel.GetDeclaredSymbol(functionDefinition); Assert.That(functionSymbol, Is.Not.Null); Assert.That(functionSymbol.Name, Is.EqualTo("MyFunc")); Assert.That(functionSymbol.ReturnType, Is.EqualTo(IntrinsicTypes.Void)); var variableSymbol = semanticModel.GetDeclaredSymbol(variableDeclaration.Declaration.Variables[0]); Assert.That(variableSymbol, Is.Not.Null); Assert.That(variableSymbol.Name, Is.EqualTo("s")); Assert.That(variableSymbol.ValueType, Is.Not.Null); Assert.That(variableSymbol.ValueType, Is.EqualTo(structSymbol)); var assignmentExpressionType = semanticModel.GetExpressionType(assignmentStatement.Expression); Assert.That(assignmentExpressionType, Is.Not.Null); Assert.That(assignmentExpressionType, Is.EqualTo(IntrinsicTypes.Float)); } [Test] public void SemanticModelForTypedef() { var syntaxTree = SyntaxFactory.ParseSyntaxTree(SourceText.From(@" typedef float2 Point; Point p;")); var compilation = new ShaderTools.Hlsl.Compilation.Compilation(syntaxTree); var semanticModel = compilation.GetSemanticModel(); foreach (var diagnostic in semanticModel.GetDiagnostics()) Debug.WriteLine(diagnostic); Assert.That(semanticModel.GetDiagnostics().Count(x => x.Severity == DiagnosticSeverity.Error), Is.EqualTo(0)); var typedefStatement = (TypedefStatementSyntax) syntaxTree.Root.ChildNodes[0]; var variableDeclaration = (VariableDeclarationStatementSyntax) syntaxTree.Root.ChildNodes[1]; var typeAliasSymbol = semanticModel.GetDeclaredSymbol(typedefStatement.Declarators[0]); Assert.That(typeAliasSymbol, Is.Not.Null); Assert.That(typeAliasSymbol.Name, Is.EqualTo("Point")); var variableSymbol = semanticModel.GetDeclaredSymbol(variableDeclaration.Declaration.Variables[0]); Assert.That(variableSymbol, Is.Not.Null); Assert.That(variableSymbol.Name, Is.EqualTo("p")); Assert.That(variableSymbol.ValueType, Is.Not.Null); Assert.That(variableSymbol.ValueType, Is.EqualTo(typeAliasSymbol)); } } }<file_sep>/src/ShaderTools/Unity/Diagnostics/DiagnosticExtensions.cs using System.Collections.Generic; using System.Linq; using ShaderTools.Core.Text; using ShaderTools.Properties; using ShaderTools.Unity.Syntax; namespace ShaderTools.Unity.Diagnostics { internal static class DiagnosticExtensions { public static string GetMessage(this DiagnosticId diagnosticId) { return Resources.ResourceManager.GetString(diagnosticId.ToString()); } public static void Report(this ICollection<Diagnostic> diagnostics, TextSpan textSpan, DiagnosticId diagnosticId, params object[] args) { var diagnostic = Diagnostic.Format(textSpan, diagnosticId, args); diagnostics.Add(diagnostic); } #region Lexer errors public static void ReportIllegalInputCharacter(this ICollection<Diagnostic> diagnostics, TextSpan textSpan, char character) { diagnostics.Report(textSpan, DiagnosticId.IllegalInputCharacter, character); } public static void ReportUnterminatedComment(this ICollection<Diagnostic> diagnostics, TextSpan textSpan) { diagnostics.Report(textSpan, DiagnosticId.UnterminatedComment); } public static void ReportUnterminatedString(this ICollection<Diagnostic> diagnostics, TextSpan textSpan) { diagnostics.Report(textSpan, DiagnosticId.UnterminatedString); } public static void ReportInvalidInteger(this ICollection<Diagnostic> diagnostics, TextSpan textSpan, string tokenText) { diagnostics.Report(textSpan, DiagnosticId.InvalidInteger, tokenText); } public static void ReportInvalidReal(this ICollection<Diagnostic> diagnostics, TextSpan textSpan, string tokenText) { diagnostics.Report(textSpan, DiagnosticId.InvalidReal, tokenText); } public static void ReportInvalidOctal(this ICollection<Diagnostic> diagnostics, TextSpan textSpan, string tokenText) { diagnostics.Report(textSpan, DiagnosticId.InvalidOctal, tokenText); } public static void ReportInvalidHex(this ICollection<Diagnostic> diagnostics, TextSpan textSpan, string tokenText) { diagnostics.Report(textSpan, DiagnosticId.InvalidHex, tokenText); } public static void ReportNumberTooLarge(this ICollection<Diagnostic> diagnostics, TextSpan textSpan, string tokenText) { diagnostics.Report(textSpan, DiagnosticId.NumberTooLarge, tokenText); } #endregion #region Parser errors public static void ReportTokenExpected(this ICollection<Diagnostic> diagnostics, TextSpan span, SyntaxToken actual, SyntaxKind expected) { var actualText = actual.GetDisplayText(); var expectedText = expected.GetDisplayText(); diagnostics.Report(span, DiagnosticId.TokenExpected, actualText, expectedText); } public static void ReportTokenExpectedMultipleChoices(this ICollection<Diagnostic> diagnostics, TextSpan span, SyntaxToken actual, IEnumerable<SyntaxKind> expected) { var actualText = actual.GetDisplayText(); var expectedText = string.Join(", ", expected.Select(x => $"'{x.GetDisplayText()}'")); diagnostics.Report(span, DiagnosticId.TokenExpectedMultipleChoices, actualText, expectedText); } public static void ReportTokenUnexpected(this ICollection<Diagnostic> diagnostics, TextSpan span, SyntaxToken actual) { var actualText = actual.GetDisplayText(); diagnostics.Report(span, DiagnosticId.TokenUnexpected, actualText); } #endregion #region Semantic errors #endregion } }<file_sep>/src/ShaderTools/Hlsl/Diagnostics/DiagnosticFacts.cs using ShaderTools.Core.Diagnostics; namespace ShaderTools.Hlsl.Diagnostics { internal static class DiagnosticFacts { public static DiagnosticSeverity GetSeverity(DiagnosticId id) { switch (id) { case DiagnosticId.LoopControlVariableConflict: case DiagnosticId.ImplicitTruncation: return DiagnosticSeverity.Warning; default: return DiagnosticSeverity.Error; } } } }<file_sep>/src/ShaderTools.VisualStudio.Tests/Hlsl/Support/VsShaderTestUtility.cs using System.Collections.Generic; using NUnit.Framework; using ShaderTools.Tests.Hlsl.Support; namespace ShaderTools.VisualStudio.Tests.Hlsl.Support { internal static class VsShaderTestUtility { public static IEnumerable<TestCaseData> GetTestShaders() { return ShaderTestUtility.FindTestShaders("../../../ShaderTools.Tests/Hlsl/Shaders"); } } }<file_sep>/src/ShaderTools.VisualStudio/Hlsl/Options/HlslOptionsPageBase.cs using ShaderTools.VisualStudio.Core.Options; namespace ShaderTools.VisualStudio.Hlsl.Options { internal abstract class HlslOptionsPageBase<TOptions> : OptionsPageBase<IHlslOptionsService, TOptions> where TOptions : class, new() { } }<file_sep>/src/ShaderTools.VisualStudio/Hlsl/Navigation/EditorNavigationSourceProvider.cs using System.ComponentModel.Composition; using Microsoft.VisualStudio.Text; using ShaderTools.VisualStudio.Hlsl.Glyphs; using ShaderTools.VisualStudio.Hlsl.Util.Extensions; namespace ShaderTools.VisualStudio.Hlsl.Navigation { [Export] internal class EditorNavigationSourceProvider { [Import] public DispatcherGlyphService GlyphService { get; private set; } public EditorNavigationSource TryCreateEditorNavigationSource(ITextBuffer textBuffer) { return textBuffer.Properties.GetOrCreateSingletonProperty( () => { var result = new EditorNavigationSource(textBuffer, textBuffer.GetBackgroundParser(), GlyphService); result.Initialize(); return result; }); } } }<file_sep>/src/ShaderTools/Hlsl/Text/DummyFileSystem.cs using System; using ShaderTools.Core.Text; namespace ShaderTools.Hlsl.Text { internal sealed class DummyFileSystem : IIncludeFileSystem { public SourceText GetInclude(string path) { throw new NotSupportedException(); } } }<file_sep>/src/ShaderTools.VisualStudio/Core/ErrorList/IErrorListHelper.cs using System; using ShaderTools.Core.Diagnostics; using ShaderTools.Core.Text; namespace ShaderTools.VisualStudio.Core.ErrorList { internal interface IErrorListHelper : IDisposable { void AddError(DiagnosticBase diagnostic, TextSpan span); void Clear(); } }
b575492262582c6f76204a5f95fdc7e8a840102a
[ "Markdown", "C#" ]
41
C#
tylearymf/HlslTools
e5a5c4ce693ede02a39711b3e06e6926c98f01f5
434b50a21843ed8275ec5b639de9811e58989dbf
refs/heads/master
<file_sep># Laravel Document api # Установка - Клонировать репозиторий ```sh git clone https://github.com/nipler/laravel_api_test.git ``` - Запустить composer ```sh composer install ``` - Выполнить миграции ```sh php artisan migrate ``` <file_sep><?php namespace App\Providers; use Illuminate\Support\ServiceProvider; class ValidatorServiceProvider extends ServiceProvider { public function boot() { $this->app['validator']->extend('uuid', function ($attribute, $value, $parameters) { return preg_match('/^[a-f0-9]{8}\-[a-f0-9]{4}\-[a-f0-9]{4}\-[a-f0-9]{4}\-[a-f0-9]{12}$/', $value); }); } public function register() { // } } <file_sep><?php namespace App\Http\Controllers\Api\V1; use App\Http\Controllers\Controller; use App\Http\Requests\DocumentRequest; use App\Documents; use Ramsey\Uuid\Uuid; class DocumentsController extends Controller { /** * получить список документов с пагинацией * * @return App\Documents */ public function index(DocumentRequest $request) { $perPage = $request->input('perPage'); $documents = Documents::select() ->orderBy('id', 'desc') ->paginate($perPage); return [ 'document'=>$documents->items(), 'pagination' => [ 'page' => $documents->currentPage(), 'perPage' => $documents->perPage(), 'total' => $documents->total() ] ]; } /** * Создаем черновик документа * * @param App\Http\Requests\DocumentRequest $request * @return App\Documents */ public function draft(DocumentRequest $request) { if ($request->isMethod('post')) { $document = new Documents; $document->uuid = Uuid::uuid4(); $document->status = 'draft'; $document->payload = new \stdClass ; $document->save(); return ['document'=>$document]; } } /** * редактировать документ * * @param App\Http\Requests\DocumentRequest $request * @param UUID $id * @return App\Documents */ public function patch(DocumentRequest $request, $id) { // Если валидация не прошла то отдаем стутус 400 if (isset($request->validator) && $request->validator->fails()) { return response()->json($request->validator->messages(), 400); } $document = Documents::where('uuid', $id)->firstOrFail(); if($document->status == "draft") { $document->payload = $request->payload; $document->save(); } else { return response()->json("Record already published", 400); } return ['document'=>$document]; } /** * // получить документ по id * * @param uuid $id * @return App\Documents */ public function show($id) { $document = Documents::where('uuid', $id)->firstOrFail(); return ['document'=>$document]; } /** * опубликовать документ * * @param App\Http\Requests\DocumentRequest $request * @param uuid $id * @return \Illuminate\Http\Response */ public function publish(DocumentRequest $request, $id) { $document = Documents::where('uuid', $id)->firstOrFail(); if($document->status == "draft") { $document->status = "published"; $document->save(); } return ['document'=>$document]; } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Documents extends Model { protected $fillable = ['uuid', 'status', 'payload', 'created_at', 'updated_at']; protected $hidden = ['id']; /** * payload преобразуем в json и обратно * * @var array */ protected $casts = [ 'payload' => 'object', ]; } <file_sep><?php namespace App\Http\Requests; use Illuminate\Http\Request; use Illuminate\Foundation\Http\FormRequest; class DocumentRequest extends FormRequest { public $validator = null; public function wantsJson() { return true; } /** * Переопределяем метод * * @return bool */ protected function failedValidation(\Illuminate\Contracts\Validation\Validator $validator) { $this->validator = $validator; } /** * Просим отдаватьвсе в json * * @return bool */ public function authorize() { return $this->isJson(); } /** * Устанавливаем правила валидации * * @return array */ public function rules(Request $request) { $rules = [ // 'id' => ['required', 'string', 'uuid'], // 'payload' => ['required'], ]; switch ($this->getMethod()) { case 'POST': /* $segments = $this->segments(); if(isset($segments[4]) && $segments[4] == "publish") { } */ break; case 'PATCH': $rules = [ 'payload' => ['required'], ]; break; } return $rules; } /** * Устанавливаем сообщения при ошибке * * @return array */ public function messages() { return [ 'id.uuid' => 'ID невалидный uuid', 'id.string' => 'ID не является строкой', 'id.required' => 'ID не может быть пустым', 'payload.required' => 'Payload не может быть пустым', ]; } /** * Преобразуем json запрос в нужный формат * * @return array */ public function all($keys = null){ $json = parent::json()->all(); if(!isset($json['document'])) return []; if(empty($keys)){ return $json['document']; } return collect($json['document'])->only($keys)->toArray(); } }
f6f6c06afa69da8040e530eee83429a73b0c2672
[ "Markdown", "PHP" ]
5
Markdown
nipler/laravel_api_test
cce0e9739a4c50323691c97d11585b39d9e5dff3
3c0e5d9e976965363891fae1fd05215efb4a11ca
refs/heads/main
<file_sep>using Domain.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Business.TravelPlan.Interfaces { public interface IUserTravelPlanService { Task<IEnumerable<Guid>> GetTravelersForActivityAsync(Guid travelPlanId); Task<IEnumerable<Guid>> GetUserTravelPlanIDsAsync(Guid userId); Task<bool> Delete(UserTravelPlan userTPToRemove); } } <file_sep>using Domain.DTOs; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Business.TravelPlan.Interfaces { public interface ITPActivityService { Task<TravelPlanActivityDto> CreateAsync(TravelPlanActivityDto activityDto, Guid userId); Task<TravelPlanActivityDto> EditAsync(TravelPlanActivityDto activityDto, Guid userId); Task<bool> DeleteAsync(Guid activityId, Guid userId); Task<TravelPlanActivityDto> GetAsync(Guid activityId); Task<List<TravelPlanActivityDto>> ListAsync(Guid travelPlanId); } } <file_sep>using Business.TravelPlan; using Business.TravelPlan.Interfaces; using DataAccess.CustomExceptions; using DataAccess.Repositories.Interfaces; using Microsoft.EntityFrameworkCore; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using Persistence; using System; using System.Threading.Tasks; using DTOs = Domain.DTOs; using Models = Domain.Models; namespace TravelogApi.Tests.Business.TravelPlan { [TestClass] public class TPActivityServiceTests { private readonly MockRepository _mockRepo = new MockRepository(MockBehavior.Strict); private DTOs.TravelPlanActivityDto _genericActivityDTO; private Guid _emptyTPID; private Guid _emptyUserId; private DbContextOptions<AppDbContext> _dbOptions; //gets called before each test [TestInitialize] public void Initialize() { _emptyTPID = new Guid(); _emptyUserId = new Guid(); _genericActivityDTO = new DTOs.TravelPlanActivityDto() { TravelPlanId = _emptyTPID, Name = "Activity 1", StartTime = new DateTime(), EndTime = new DateTime().AddHours(1), Location = new DTOs.LocationDto() { Address = "Some Place", Latitude = 123.451, Longitude = 543.210 }, Category = "Food" }; _dbOptions = new DbContextOptionsBuilder<AppDbContext>().UseInMemoryDatabase(databaseName: "TravelogApi").Options; } [TestMethod] public async Task CreateAsync_ValidActivity_ReturnsActivity() { var newActivity = new Models.TravelPlanActivity { Name = _genericActivityDTO.Name, StartTime = _genericActivityDTO.StartTime, EndTime = _genericActivityDTO.EndTime, Category = _genericActivityDTO.Category, Location = new Models.Location { Address = _genericActivityDTO.Location.Address, Latitude = _genericActivityDTO.Location.Latitude, Longitude = _genericActivityDTO.Location.Longitude, }, HostId = _emptyUserId, TravelPlanId = _genericActivityDTO.TravelPlanId }; var travelPlanDto = new DTOs.TravelPlanDto(); var tpService = _mockRepo.Create<ITravelPlanService>(); var tpActivityRepo = _mockRepo.Create<ITravelPlanActivityRepository>(); //arrange tpService.Setup((tps) => tps.GetAsync(_emptyTPID, false, false)).ReturnsAsync(travelPlanDto); tpActivityRepo.Setup((tpa) => tpa.CreateAsync(It.IsAny<Models.TravelPlanActivity>())).ReturnsAsync(newActivity); //act using (var context = new AppDbContext(_dbOptions)) { var tpActivityService = new TPActivityService(context, tpService.Object, tpActivityRepo.Object); var result = await tpActivityService.CreateAsync(_genericActivityDTO, _emptyUserId); //verify Assert.IsNotNull(result); Assert.IsTrue(result is DTOs.TravelPlanActivityDto); } } [TestMethod] [ExpectedException(typeof(Exception))] public async Task CreateAsync_InvalidTPId_ThrowsException() { DTOs.TravelPlanDto travelPlanDto = null; var tpService = _mockRepo.Create<ITravelPlanService>(); var tpActivityRepo = _mockRepo.Create<ITravelPlanActivityRepository>(); //arrange tpService.Setup((tps) => tps.GetAsync(_emptyTPID, false, false)).ReturnsAsync(travelPlanDto); //act using (var context = new AppDbContext(_dbOptions)) { var tpActivityService = new TPActivityService(context, tpService.Object, tpActivityRepo.Object); var result = await tpActivityService.CreateAsync(_genericActivityDTO, _emptyUserId); //verify } } [TestMethod] [ExpectedException(typeof(Exception))] public async Task EditAsync_InvalidActivityID_ThrowsException() { var tpService = _mockRepo.Create<ITravelPlanService>(); var tpActivityRepo = _mockRepo.Create<ITravelPlanActivityRepository>(); Models.TravelPlanActivity nullTPActivity = null; //arrange tpActivityRepo.Setup((tpa) => tpa.GetAsync(It.IsAny<Guid>())).ReturnsAsync(nullTPActivity); //act using (var context = new AppDbContext(_dbOptions)) { var tpActivityService = new TPActivityService(context, tpService.Object, tpActivityRepo.Object); var result = await tpActivityService.EditAsync(_genericActivityDTO, _emptyUserId); //verify } } [TestMethod] [ExpectedException(typeof(InsufficientRightsException))] public async Task EditAsync_UserNotHost_ThrowsInsufficientRightsException() { var tpService = _mockRepo.Create<ITravelPlanService>(); var tpActivityRepo = _mockRepo.Create<ITravelPlanActivityRepository>(); var tpActivityToEdit = new Models.TravelPlanActivity { HostId = Guid.NewGuid() }; //arrange tpActivityRepo.Setup((tpa) => tpa.GetAsync(It.IsAny<Guid>())).ReturnsAsync(tpActivityToEdit); //act using (var context = new AppDbContext(_dbOptions)) { var tpActivityService = new TPActivityService(context, tpService.Object, tpActivityRepo.Object); var result = await tpActivityService.EditAsync(_genericActivityDTO, _emptyUserId); //verify } } [TestMethod] [ExpectedException(typeof(InsufficientRightsException))] public async Task DeleteAsync_UserNotHost_ThrowsInsufficientRightsException() { var tpService = _mockRepo.Create<ITravelPlanService>(); var tpActivityRepo = _mockRepo.Create<ITravelPlanActivityRepository>(); var tpActivityToDelete = new Models.TravelPlanActivity { HostId = Guid.NewGuid() }; //arrange tpActivityRepo.Setup((tpa) => tpa.GetAsync(It.IsAny<Guid>())).ReturnsAsync(tpActivityToDelete); //act using (var context = new AppDbContext(_dbOptions)) { var tpActivityService = new TPActivityService(context, tpService.Object, tpActivityRepo.Object); var result = await tpActivityService.EditAsync(_genericActivityDTO, _emptyUserId); //verify } } } }<file_sep>using DataAccess.Common.Enums; using DataAccess.CustomExceptions; using DataAccess.Repositories.Interfaces; using Domain.DTOs; using Domain.Models; using Microsoft.EntityFrameworkCore; using Persistence; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace DataAccess.Repositories { public class TravelPlanRepository : ITravelPlanRepository { private readonly AppDbContext _dbContext; private readonly IUserRepository _userRepository; private readonly ITravelPlanStatusRepository _travelPlanStatusRepository; public TravelPlanRepository(AppDbContext dbContext, IUserRepository userRepository, ITravelPlanStatusRepository travelPlanStatusRepository) { _dbContext = dbContext; _userRepository = userRepository; _travelPlanStatusRepository = travelPlanStatusRepository; } public async Task<bool> AddTravelerAsync(Guid travelPlanId, Guid userToAddId) { try { //check if travelplan exists var travelPlan = await _dbContext.TravelPlans.FindAsync(travelPlanId); if (travelPlan == null) throw new Exception("Travel Plan Not Found"); var newUserTravelPlan = new UserTravelPlan { UserId = userToAddId, TravelPlanId = travelPlanId }; //could throw exception if traveler is already added to travel plan bc of the composite key constraint _dbContext.UserTravelPlans.Add(newUserTravelPlan); var isSuccessful = await _dbContext.SaveChangesAsync() > 0; return isSuccessful; } catch { throw; } } public async Task<TravelPlan> CreateAsync(TravelPlan newTravelPlan) { try { await _dbContext.TravelPlans.AddAsync(newTravelPlan); var isSuccessful = await _dbContext.SaveChangesAsync() > 0; if (isSuccessful) { return newTravelPlan; } throw new Exception("Problem Editing Travel Plan"); } catch (Exception exc) { throw; } } public async Task<bool> DeleteAsync(TravelPlan travelPlanToDelete) { try { //let EF core cascade delete and delete relations with dependent tables via collection nav properties _dbContext.Remove(travelPlanToDelete); var isSuccessful = await _dbContext.SaveChangesAsync() > 0; return isSuccessful; } catch (Exception) { throw; } } //public async Task<TravelPlanDto> EditAsync(TravelPlanDto travelPlanDto, Guid userId) //{ // try // { // var travelPlanToEdit = await _dbContext.TravelPlans.FindAsync(travelPlanDto.Id); // if (travelPlanToEdit == null) throw new Exception("Travel Plan Not Found"); // if (travelPlanToEdit.CreatedById != userId) throw new InsufficientRightsException("Insufficient rights to edit Travel Plan"); // //map here // travelPlanToEdit.TravelPlanId = travelPlanDto.Id; // travelPlanToEdit.Name = travelPlanDto.Name; // travelPlanToEdit.StartDate = travelPlanDto.StartDate; // travelPlanToEdit.EndDate = travelPlanDto.EndDate; // travelPlanToEdit.Description = travelPlanDto.Description; // if (!_dbContext.ChangeTracker.HasChanges()) return travelPlanDto; // var isSuccessful = await _dbContext.SaveChangesAsync() > 0; // if (isSuccessful) // { // return new TravelPlanDto(travelPlanToEdit); // } // throw new Exception("Problem Editing Travel Plan"); // } // catch (Exception) // { // throw; // } //} //public async Task<bool> UpdateTPStatus(TravelPlan travelPlanToEdit, int status) //{ // if (!_dbContext.ChangeTracker.HasChanges()) // { // return true; // } // else // { // var isSuccessful = await _dbContext.SaveChangesAsync() > 0; // return isSuccessful; // } //} public async Task<TravelPlan> GetAsync(Guid travelPlanId, bool includeUTP = false) { try { TravelPlan travelPlan; if(includeUTP) { travelPlan = await _dbContext.TravelPlans.Where((tp) => tp.TravelPlanId == travelPlanId) .Include(tp => tp.UserTravelPlans) .FirstOrDefaultAsync(); } else { travelPlan = await _dbContext.TravelPlans.FindAsync(travelPlanId); } var travelPlanDto = new TravelPlanDto(travelPlan); var tpStatus = await _dbContext.TravelPlanStatuses.Where(tps => tps.UniqStatus == (TravelPlanStatusEnum)travelPlan.TravelPlanStatusId) .FirstOrDefaultAsync(); travelPlanDto.TravelPlanStatus = new TravelPlanStatusDto { UniqStatus = tpStatus.UniqStatus, Description = tpStatus.Description }; return travelPlan; } catch { throw; } } public async Task<List<TravelPlan>> GetTravelPlansWithFilterAsync(IEnumerable<Guid> travelPlanIDs, int? status = null) { var travelPlans = new List<TravelPlan>(); //if null, aka not specified, get all, //else get specific if (status == null) { travelPlans = await _dbContext.TravelPlans.Where((tp) => travelPlanIDs.Contains(tp.TravelPlanId)) .OrderBy((tp) => tp.StartDate).ToListAsync(); } else if (Enum.IsDefined(typeof(TravelPlanStatusEnum), status)) { travelPlans = await _dbContext.TravelPlans.Where((tp) => travelPlanIDs.Contains(tp.TravelPlanId) && tp.TravelPlanStatusId == status) .OrderBy((tp) => tp.StartDate).ToListAsync(); } return travelPlans; } } }<file_sep>using Business.TravelPlan; using Business.TravelPlan.Interfaces; using DataAccess.Repositories; using DataAccess.Repositories.Interfaces; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.IdentityModel.Logging; using Persistence; namespace TravelogApi { public class Startup { public IConfiguration Configuration { get; } public Startup(IConfiguration configuration) { Configuration = configuration; } public void ConfigureServices(IServiceCollection services) { var connectionString = Configuration.GetConnectionString("TravelogApi"); services.AddDbContext<AppDbContext>(options => options.UseSqlServer(connectionString)); services.AddCors(options => { //allows any requests from localhost;3000 to get into app //without this requests from any origin will not be allowed to hit //this api options.AddPolicy("TravelogCorsPolicy", policy => { policy .AllowAnyHeader() .AllowAnyMethod() .WithOrigins("http://localhost:3000") .WithExposedHeaders("WWW-Authenticate") .AllowCredentials(); }); }); //use the jwtbearer auth services.AddAuthentication("TravelogBearerAuth") .AddJwtBearer("TravelogBearerAuth", config => { config.Authority = Configuration["IdentityServerUrl"]; //who we are, needed by server to check whether token is for this resource config.Audience = "TravelogApi"; }); //repos services.AddScoped<ITravelPlanRepository, TravelPlanRepository>(); services.AddScoped<IUserRepository, UserRepository>(); services.AddScoped<IUserTravelPlanRepository, UserTravelPlanRepository>(); services.AddScoped<ITravelPlanActivityRepository, TravelPlanActivityRepository>(); services.AddScoped<IPlanInvitationRepository, PlanInvitationRepository>(); services.AddScoped<ITravelPlanStatusRepository, TravelPlanStatusRepository>(); services.AddScoped<ITPAnnouncementRepository, TPAnnouncementRepository>(); //bus services services.AddScoped<ITravelPlanService, TravelPlanService>(); services.AddScoped<ITravelPlanInvitationService, TravelPlanInvitationService>(); services.AddScoped<ITravelPlanStatusService, TravelPlanStatusService>(); services.AddScoped<IUserTravelPlanService, UserTravelPlanService>(); services.AddScoped<ITPActivityService, TPActivityService>(); services.AddScoped<ITPAnnouncementService, TPAnnouncementService>(); services.AddScoped<ITravelPlanInvitationService, TravelPlanInvitationService>(); services.AddControllers(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { IdentityModelEventSource.ShowPII = true; app.UseDeveloperExceptionPage(); } app.UseRouting(); app.UseCors("TravelogCorsPolicy"); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapDefaultControllerRoute(); }); } } }<file_sep>using Dapper; using DataAccess.CustomExceptions; using DataAccess.Repositories.Interfaces; using Domain.DTOs; using Domain.Models; using Microsoft.Data.SqlClient; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Persistence; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace DataAccess.Repositories { public class PlanInvitationRepository : IPlanInvitationRepository { private readonly AppDbContext _dbContext; private readonly IUserRepository _userRepository; private readonly ITravelPlanRepository _travelPlanRepository; public string ConnectionString { get; } public PlanInvitationRepository(AppDbContext dbContext, IUserRepository userRepository, ITravelPlanRepository travelPlanRepository, IConfiguration configuration) { _dbContext = dbContext; _userRepository = userRepository; _travelPlanRepository = travelPlanRepository; ConnectionString = configuration.GetConnectionString("TravelogApi"); } public async Task DeleteInvitation(PlanInvitation invitation) { try { //accepting means remove the invitation from table _dbContext.PlanInvitations.Remove(invitation); var result = await _dbContext.SaveChangesAsync(); if (result <= 0) { //log here throw new Exception("Could not save invitation changes"); } } catch (Exception) { throw; } } public async Task InviteUser(PlanInvitation newInvitation) { try { _dbContext.PlanInvitations.Add(newInvitation); var result = await _dbContext.SaveChangesAsync(); if (result <= 0) { throw new Exception("Could not add invitation in db"); } } catch (DbUpdateException exc) { if (exc.InnerException is SqlException sqlExc) { switch (sqlExc.Number) { //2627 is unique id already exists case 2627: throw new UniqueConstraintException("Invitation has already been sent"); default: throw; } } } catch (Exception exc) { throw; } } public async Task<List<PlanInvitationDto>> List(Guid loggedInUserId) { try { //get invitations const string PLAN_INVITATIONS_FOR_USER_SQL = @"SELECT INV.ID, TP.NAME as TravelPlanName, INV.INVITEEID as InviteeId, INV.INVITEDBYID as InvitedById, TP.TRAVELPLANID as TravelPlanId, INV.CREATED as CreatedDate, INV.EXPIRATION as ExpirationDate FROM PLANINVITATIONS INV INNER JOIN TRAVELPLANS TP ON TP.TRAVELPLANID = INV.TRAVELPLANID WHERE INV.INVITEEID=@loggedInUserId"; List<PlanInvitationDto> userInvitations; using (SqlConnection connection = new SqlConnection(ConnectionString)) { var enumerablInvs = await connection .QueryAsync<PlanInvitationDto>(PLAN_INVITATIONS_FOR_USER_SQL, new { loggedInUserId = loggedInUserId }); userInvitations = enumerablInvs.ToList(); } return userInvitations; } catch { throw; } } public async Task<PlanInvitation> GetInvitation(int invitationId) { try { var invitation = await _dbContext.PlanInvitations.FindAsync(invitationId); return invitation; } catch (Exception) { throw; } } } }<file_sep>using Business.TravelPlan; using Business.TravelPlan.Interfaces; using DataAccess.Common.Enums; using DataAccess.CustomExceptions; using DataAccess.Repositories.Interfaces; using Microsoft.EntityFrameworkCore; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using Persistence; using System; using System.Threading.Tasks; using Models = Domain.Models; using DTOs = Domain.DTOs; using System.Collections.Generic; namespace TravelogApi.Tests.Business.TravelPlan { [TestClass] public class TravelPlanServiceTests { private readonly MockRepository _mockRepo = new MockRepository(MockBehavior.Strict); private DbContextOptions<AppDbContext> _dbOptions; private Guid _emptyTPId; private Guid _emptyUserId; [TestInitialize] public void Initialize() { _emptyTPId = new Guid(); _emptyUserId = new Guid(); _dbOptions = new DbContextOptionsBuilder<AppDbContext>().UseInMemoryDatabase(databaseName: "TravelogApi").Options; } [TestMethod] [ExpectedException(typeof(Exception))] public async Task SetStatus_InvalidStatus_ThrowsException() { var loggedInUserId = _emptyUserId; var tpRepo = _mockRepo.Create<ITravelPlanRepository>(); var userRepo = _mockRepo.Create<IUserRepository>(); var userTPService = _mockRepo.Create<IUserTravelPlanService>(); var tpStatusService = _mockRepo.Create<ITravelPlanStatusService>(); int invalidStatus = 123; //act using (var context = new AppDbContext(_dbOptions)) { var tpService = new TravelPlanService(tpRepo.Object, userRepo.Object, userTPService.Object, tpStatusService.Object, context); var result = await tpService.SetStatusAsync(loggedInUserId, _emptyUserId, invalidStatus); } } [TestMethod] [ExpectedException(typeof(Exception))] public async Task SetStatus_InvalidTravelPlan_ThrowsException() { var loggedInUserId = _emptyUserId; var tpRepo = _mockRepo.Create<ITravelPlanRepository>(); var userRepo = _mockRepo.Create<IUserRepository>(); var userTPService = _mockRepo.Create<IUserTravelPlanService>(); var tpStatusService = _mockRepo.Create<ITravelPlanStatusService>(); int invalidStatus = (int)TravelPlanStatusEnum.Archived; var tpToEdit = new Models.TravelPlan(); //arrange tpRepo.Setup((tpr) => tpr.GetAsync(It.IsAny<Guid>(), false)).ReturnsAsync(tpToEdit); //act using (var context = new AppDbContext(_dbOptions)) { var tpService = new TravelPlanService(tpRepo.Object, userRepo.Object, userTPService.Object, tpStatusService.Object, context); var result = await tpService.SetStatusAsync(loggedInUserId, _emptyUserId, invalidStatus); } } [TestMethod] [ExpectedException(typeof(InsufficientRightsException))] public async Task SetStatus_UserIsNotCreator_ThrowsInsufficientRightsException() { var loggedInUserId = _emptyUserId; var tpRepo = _mockRepo.Create<ITravelPlanRepository>(); var userRepo = _mockRepo.Create<IUserRepository>(); var userTPService = _mockRepo.Create<IUserTravelPlanService>(); var tpStatusService = _mockRepo.Create<ITravelPlanStatusService>(); int status = (int)TravelPlanStatusEnum.Archived; var tpToEdit = new Models.TravelPlan() { CreatedById = Guid.NewGuid() }; //arrange tpRepo.Setup((tpr) => tpr.GetAsync(It.IsAny<Guid>(), false)).ReturnsAsync(tpToEdit); //act using (var context = new AppDbContext(_dbOptions)) { var tpService = new TravelPlanService(tpRepo.Object, userRepo.Object, userTPService.Object, tpStatusService.Object, context); var result = await tpService.SetStatusAsync(loggedInUserId, _emptyUserId, status); } } [TestMethod] [ExpectedException(typeof(Exception))] public async Task RemoveTraveler_InvalidTravelPlan_ThrowsException() { var loggedInUserId = _emptyUserId; var tpRepo = _mockRepo.Create<ITravelPlanRepository>(); var userRepo = _mockRepo.Create<IUserRepository>(); var userTPService = _mockRepo.Create<IUserTravelPlanService>(); var tpStatusService = _mockRepo.Create<ITravelPlanStatusService>(); Models.TravelPlan nullTP = null; //arrange tpRepo.Setup((tpr) => tpr.GetAsync(_emptyTPId, true)).ReturnsAsync(nullTP); //act using (var context = new AppDbContext(_dbOptions)) { var tpService = new TravelPlanService(tpRepo.Object, userRepo.Object, userTPService.Object, tpStatusService.Object, context); var result = await tpService.RemoveTraveler(loggedInUserId, "someUsername", _emptyTPId); } } [TestMethod] public async Task RemoveTraveler_InvalidTraveler_ReturnsTrue() { var loggedInUserId = _emptyUserId; var userName = "someUsername"; var tpRepo = _mockRepo.Create<ITravelPlanRepository>(); var userRepo = _mockRepo.Create<IUserRepository>(); var userTPService = _mockRepo.Create<IUserTravelPlanService>(); var tpStatusService = _mockRepo.Create<ITravelPlanStatusService>(); Models.TravelPlan travelPlan = new Models.TravelPlan(); DTOs.UserDto nullUser = null; //arrange tpRepo.Setup((tpr) => tpr.GetAsync(_emptyTPId, true)).ReturnsAsync(travelPlan); userRepo.Setup((ur) => ur.GetUserAsync(userName)).ReturnsAsync(nullUser); //act using (var context = new AppDbContext(_dbOptions)) { var tpService = new TravelPlanService(tpRepo.Object, userRepo.Object, userTPService.Object, tpStatusService.Object, context); var result = await tpService.RemoveTraveler(loggedInUserId, userName, _emptyTPId); Assert.IsTrue(result); } } [TestMethod] public async Task RemoveTraveler_UserTravelPlanNotExists_ReturnsTrue() { var loggedInUserId = _emptyUserId; var userName = "someUsername"; var tpRepo = _mockRepo.Create<ITravelPlanRepository>(); var userRepo = _mockRepo.Create<IUserRepository>(); var userTPService = _mockRepo.Create<IUserTravelPlanService>(); var tpStatusService = _mockRepo.Create<ITravelPlanStatusService>(); Models.TravelPlan travelPlan = new Models.TravelPlan(); travelPlan.UserTravelPlans = null; DTOs.UserDto user = new DTOs.UserDto(); //arrange tpRepo.Setup((tpr) => tpr.GetAsync(_emptyTPId, true)).ReturnsAsync(travelPlan); userRepo.Setup((ur) => ur.GetUserAsync(userName)).ReturnsAsync(user); //act using (var context = new AppDbContext(_dbOptions)) { var tpService = new TravelPlanService(tpRepo.Object, userRepo.Object, userTPService.Object, tpStatusService.Object, context); var result = await tpService.RemoveTraveler(loggedInUserId, userName, _emptyTPId); Assert.IsTrue(result); } } [TestMethod] [ExpectedException(typeof(Exception))] public async Task RemoveTraveler_HostRemoveThemslves_ThrowsException() { var loggedInUserId = _emptyUserId; var userName = "someUsername"; var tpRepo = _mockRepo.Create<ITravelPlanRepository>(); var userRepo = _mockRepo.Create<IUserRepository>(); var userTPService = _mockRepo.Create<IUserTravelPlanService>(); var tpStatusService = _mockRepo.Create<ITravelPlanStatusService>(); Models.TravelPlan travelPlan = new Models.TravelPlan(); travelPlan.CreatedById = _emptyUserId; //user to remove is the host var userTPToRemove = new Models.UserTravelPlan { UserId = _emptyUserId }; travelPlan.UserTravelPlans = new List<Models.UserTravelPlan> { userTPToRemove }; DTOs.UserDto user = new DTOs.UserDto(); user.Id = _emptyUserId.ToString(); //arrange tpRepo.Setup((tpr) => tpr.GetAsync(_emptyTPId, true)).ReturnsAsync(travelPlan); userRepo.Setup((ur) => ur.GetUserAsync(userName)).ReturnsAsync(user); userTPService.Setup(utp => utp.Delete(It.IsAny<Models.UserTravelPlan>())).ReturnsAsync(true); //act using (var context = new AppDbContext(_dbOptions)) { var tpService = new TravelPlanService(tpRepo.Object, userRepo.Object, userTPService.Object, tpStatusService.Object, context); var result = await tpService.RemoveTraveler(loggedInUserId, userName, _emptyTPId); } } [TestMethod] [ExpectedException(typeof(InsufficientRightsException))] public async Task RemoveTraveler_UserNotHostRemoveOtherTraveler_ThrowsInsufficientRIghtsException() { var loggedInUserId = _emptyUserId; var userName = "someUsername"; var tpRepo = _mockRepo.Create<ITravelPlanRepository>(); var userRepo = _mockRepo.Create<IUserRepository>(); var userTPService = _mockRepo.Create<IUserTravelPlanService>(); var tpStatusService = _mockRepo.Create<ITravelPlanStatusService>(); Models.TravelPlan travelPlan = new Models.TravelPlan(); //user is not the host and user to remove is not themselves travelPlan.CreatedById = Guid.NewGuid(); var userTPToRemove = new Models.UserTravelPlan { UserId = Guid.NewGuid() }; travelPlan.UserTravelPlans = new List<Models.UserTravelPlan> { userTPToRemove }; DTOs.UserDto user = new DTOs.UserDto(); user.Id = userTPToRemove.UserId.ToString(); //arrange tpRepo.Setup((tpr) => tpr.GetAsync(_emptyTPId, true)).ReturnsAsync(travelPlan); userRepo.Setup((ur) => ur.GetUserAsync(userName)).ReturnsAsync(user); userTPService.Setup(utp => utp.Delete(It.IsAny<Models.UserTravelPlan>())).ReturnsAsync(true); //act using (var context = new AppDbContext(_dbOptions)) { var tpService = new TravelPlanService(tpRepo.Object, userRepo.Object, userTPService.Object, tpStatusService.Object, context); var result = await tpService.RemoveTraveler(loggedInUserId, userName, _emptyTPId); } } } }<file_sep>using DataAccess.Common.Enums; using Domain.Models; using System.Collections.Generic; using System.Threading.Tasks; namespace DataAccess.Repositories.Interfaces { public interface ITravelPlanStatusRepository { Task<List<TravelPlanStatus>> ListAsync(); Task<TravelPlanStatus> GetStatusAsync(TravelPlanStatusEnum status); } }<file_sep>using Business.TravelPlan.Interfaces; using DataAccess.Common.Enums; using DataAccess.Repositories.Interfaces; using Domain.DTOs; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Business.TravelPlan { public class TravelPlanStatusService : ITravelPlanStatusService { private readonly ITravelPlanStatusRepository _travelPlanStatusRepository; public TravelPlanStatusService(ITravelPlanStatusRepository travelPlanStatusRepository) { _travelPlanStatusRepository = travelPlanStatusRepository; } public async Task<TravelPlanStatusDto> GetStatusAsync(TravelPlanStatusEnum status) { var tpStatus = await _travelPlanStatusRepository.GetStatusAsync(status); var tpStatusDto = new TravelPlanStatusDto() { Description = tpStatus.Description, UniqStatus = tpStatus.UniqStatus }; return tpStatusDto; } public async Task<List<TravelPlanStatusDto>> ListAsync() { var tpStatuses = await _travelPlanStatusRepository.ListAsync(); var tpStatusDtos = tpStatuses.Select(tps => new TravelPlanStatusDto() { UniqStatus = tps.UniqStatus, Description = tps.Description }).ToList(); return tpStatusDtos; } } } <file_sep>using DataAccess.Common.Enums; using Domain.DTOs; using System.Collections.Generic; using System.Threading.Tasks; namespace Business.TravelPlan.Interfaces { public interface ITravelPlanStatusService { Task<List<TravelPlanStatusDto>> ListAsync(); Task<TravelPlanStatusDto> GetStatusAsync(TravelPlanStatusEnum status); } }<file_sep>using Domain.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DataAccess.Repositories.Interfaces { public interface IUserTravelPlanRepository { Task<IEnumerable<Guid>> GetTravelersForActivityAsync(Guid travelPlanId); Task<IEnumerable<Guid>> GetUserTravelPlanIDsAsync(Guid userId); Task<bool> Delete(UserTravelPlan userTPToRemove); } } <file_sep>using Domain.DTOs; using Domain.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DataAccess.Repositories.Interfaces { public interface IPlanInvitationRepository { Task InviteUser(PlanInvitation newInvitation); Task<PlanInvitation> GetInvitation(int invitationId); Task<List<PlanInvitationDto>> List(Guid loggedInUserId); Task DeleteInvitation(PlanInvitation invitation); } } <file_sep>using Domain.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Domain.DTOs { public class TPAnnouncementDto { public Guid Id { get; set; } public string Title { get; set; } public string Description { get; set; } public DateTime CreatedDate { get; set; } public Guid CreatedById { get; set; } public Guid TravelPlanId { get; set; } public Guid? TravelPlanActivityId { get; set; } public TPAnnouncementDto() { } public TPAnnouncementDto(TPAnnouncement tpAnnouncement) { this.Id = tpAnnouncement.Id; this.Title = tpAnnouncement.Title; this.Description = tpAnnouncement.Description; this.CreatedDate = DateTime.SpecifyKind(tpAnnouncement.CreatedDate, DateTimeKind.Utc); this.CreatedById = tpAnnouncement.CreatedById; this.TravelPlanId = tpAnnouncement.TravelPlanId; this.TravelPlanActivityId = tpAnnouncement.TravelPlanActivityId; } } } <file_sep>using Business.TravelPlan.Interfaces; using DataAccess.CustomExceptions; using DataAccess.Repositories.Interfaces; using Domain.DTOs; using Microsoft.AspNetCore.Mvc; using System; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; namespace TravelogApi.Controllers { public class TravelPlanActivityController : Controller { private readonly ITPActivityService _activityService; private readonly IUserTravelPlanService _userTravelPlanService; public TravelPlanActivityController(ITPActivityService activityService, IUserTravelPlanService userTravelPlanService) { _activityService = activityService; _userTravelPlanService = userTravelPlanService; } [HttpPost] public async Task<IActionResult> Create([FromBody] TravelPlanActivityDto activityDto) { try { var userId = HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value; var newActivity = await _activityService.CreateAsync(activityDto, new Guid(userId)); return Ok(newActivity); } catch (Exception exc) { return BadRequest(); } } [HttpPut] public async Task<IActionResult> Edit([FromBody] TravelPlanActivityDto activityDto) { try { var userId = HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value; var editedActivityDto = await _activityService.EditAsync(activityDto, new Guid(userId)); return Ok(editedActivityDto); } catch (InsufficientRightsException insufRights) { return BadRequest(new { message = insufRights.Message }); } catch (Exception exc) { return BadRequest(); } } [HttpDelete] public async Task<IActionResult> Delete([FromQuery] string id) { try { var userId = HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value; var isSuccessful = await _activityService.DeleteAsync(new Guid(id), new Guid(userId)); if (!isSuccessful) return StatusCode(500); return Ok(); } catch (InsufficientRightsException insufRights) { return BadRequest(new { message = insufRights.Message }); } catch (Exception exc) { return BadRequest(); } } [HttpGet] public async Task<IActionResult> Details([FromQuery] string id) { var activityDto = await _activityService.GetAsync(new Guid(id)); return Ok(activityDto); } [HttpGet] public async Task<IActionResult> List([FromQuery] string id) { try { var userId = HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value; var travelPlanId = new Guid(id); var travelers = await _userTravelPlanService.GetTravelersForActivityAsync(travelPlanId); if(travelers.Count() == 0) { //travel plan doesn't exist return BadRequest(new { Message = "Error occurred retrieving activities for travel plan" }); } if (!travelers.Contains(new Guid(userId))) { return Forbid(); } var lstActivityDto = await _activityService.ListAsync(travelPlanId); return Ok(lstActivityDto); } catch { return BadRequest(); } } } }<file_sep>using Domain.DTOs; using Domain.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DataAccess.Repositories.Interfaces { public interface ITravelPlanActivityRepository { Task<TravelPlanActivity> CreateAsync(TravelPlanActivity newActivity); Task<bool> DeleteAsync(TravelPlanActivity activityToDelete); Task<TravelPlanActivity> GetAsync(Guid activityId); Task<List<TravelPlanActivity>> ListAsync(Guid travelPlanId); } } <file_sep>using Business.TravelPlan.Interfaces; using DataAccess.Repositories.Interfaces; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json.Linq; using System; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; namespace TravelogApi.Controllers { public class InviteController : Controller { private readonly ITravelPlanInvitationService _travelPlanInvitationService; public InviteController(ITravelPlanInvitationService travelPlanInvitationService) { _travelPlanInvitationService = travelPlanInvitationService; } public async Task<IActionResult> List() { try { var loggedInUserId = HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value; var userInvitations = await _travelPlanInvitationService.List(new Guid(loggedInUserId)); return Ok(userInvitations); } catch (Exception) { return BadRequest(); } } [HttpPost] public async Task<IActionResult> Accept(int inviteId) { try { var loggedInUserId = HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value; await _travelPlanInvitationService.AcceptInvitation(new Guid(loggedInUserId), inviteId); return Ok(); } catch { return BadRequest(); } } [HttpPost] public async Task<IActionResult> Decline(int inviteId) { try { var loggedInUserId = HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value; await _travelPlanInvitationService.DeclineInvitation(new Guid(loggedInUserId), inviteId); return Ok(); } catch { return BadRequest(); } } } }<file_sep>using DataAccess.Common.Enums; using Domain.DTOs; using Domain.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DataAccess.Repositories.Interfaces { public interface ITravelPlanRepository { Task<TravelPlan> CreateAsync(TravelPlan newTravelPlan); //Task<TravelPlanDto> EditAsync(TravelPlanDto travelPlanDto, Guid userId); Task<bool> AddTravelerAsync(Guid travelPlanId, Guid userToAddId); Task<bool> DeleteAsync(TravelPlan travelPlanToDelete); Task<TravelPlan> GetAsync(Guid travelPlanId, bool includeUTP = false); Task<List<TravelPlan>> GetTravelPlansWithFilterAsync(IEnumerable<Guid> travelPlanIDs, int? status = null); //Task<bool> UpdateTPStatus(TravelPlan travelPlanToEdit, int status); } } <file_sep>using Domain.DTOs; using Domain.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DataAccess.Repositories.Interfaces { public interface ITPAnnouncementRepository { Task<AnnouncementEnvelope> ListAsync(Guid travelPlanId, int limit, int offset); Task<TPAnnouncement> GetAsync(Guid announcementId); Task<bool> DeleteAsync(TPAnnouncement announcementToDelete); Task<TPAnnouncement> CreateAsync(TPAnnouncement newAnnouncement); } } <file_sep>using Business.TravelPlan.Interfaces; using DataAccess.CustomExceptions; using DataAccess.Repositories.Interfaces; using Domain.DTOs; using Domain.Models; using Persistence; using System; using System.Threading.Tasks; namespace Business.TravelPlan { public class TPAnnouncementService : ITPAnnouncementService { private readonly AppDbContext _dbContext; private readonly ITravelPlanService _travelPlanService; private readonly ITPAnnouncementRepository _announcementRepository; public TPAnnouncementService(AppDbContext dbContext, ITravelPlanService travelPlanService, ITPAnnouncementRepository announcementRepository) { _dbContext = dbContext; _travelPlanService = travelPlanService; _announcementRepository = announcementRepository; } public async Task<TPAnnouncementDto> CreateAsync(TPAnnouncementDto announcementDto, Guid loggedInUserId) { try { var tpToAnnounceTo = await _travelPlanService.GetAsync(announcementDto.TravelPlanId); if (tpToAnnounceTo.CreatedById != loggedInUserId) { throw new InsufficientRightsException("User doesn't have rights to delete"); } var newAnnouncement = new TPAnnouncement { Title = announcementDto.Title, Description = announcementDto.Description, CreatedDate = DateTime.UtcNow, CreatedById = loggedInUserId, TravelPlanId = announcementDto.TravelPlanId, TravelPlanActivityId = announcementDto.TravelPlanActivityId }; var addedAnnouncement = await _announcementRepository.CreateAsync(newAnnouncement); return new TPAnnouncementDto(addedAnnouncement); } catch (Exception) { throw; } } public async Task<bool> DeleteAsync(Guid announcementId, Guid loggedInUserId) { try { //get list of announcements for travel plan var announcementToDelete = await _announcementRepository.GetAsync(announcementId); if (announcementToDelete == null) { return true; } if (announcementToDelete.CreatedById != loggedInUserId) { throw new InsufficientRightsException("User doesn't have rights to delete"); } var isSuccessful = await _announcementRepository.DeleteAsync(announcementToDelete); return isSuccessful; } catch (Exception) { throw; } } public async Task<TPAnnouncementDto> EditAsync(TPAnnouncementDto announcementDto, Guid loggedInUserId) { try { //validate announcement exists var announcementToEdit = await _announcementRepository.GetAsync(announcementDto.Id); if (announcementToEdit == null) { throw new CommonException("Invalid Announcement"); } //validate logged in user is even able to make an announcement to travel plan var tpToAnnounceTo = await _travelPlanService.GetAsync(announcementDto.TravelPlanId); if (tpToAnnounceTo.CreatedById != loggedInUserId) { throw new InsufficientRightsException("User doesn't have rights to delete"); } announcementToEdit.Title = announcementDto.Title; announcementToEdit.Description = announcementDto.Description; announcementToEdit.CreatedDate = announcementDto.CreatedDate; //probably create a new column for updated date var isSuccessful = await _dbContext.SaveChangesAsync() > 0; if (isSuccessful) { return new TPAnnouncementDto(announcementToEdit); } throw new CommonException("Problem occurred creating announcement"); } catch (Exception) { throw; } } public async Task<TPAnnouncementDto> GetAsync(Guid announcementId) { try { var announcement = await _announcementRepository.GetAsync(announcementId); if (announcement == null) { throw new CommonException("Invalid Announcement"); } return new TPAnnouncementDto(announcement); } catch (Exception) { throw; } } public async Task<AnnouncementEnvelope> ListAsync(Guid travelPlanId, int limit, int offset) { try { var tPlan = await _travelPlanService.GetAsync(travelPlanId); if (tPlan == null) { throw new CommonException("Invalid TravelPlan"); } var annEnvelope = await _announcementRepository.ListAsync(travelPlanId, limit, offset); return annEnvelope; } catch (Exception) { throw; } } } }<file_sep>using DataAccess.Common.Enums; using DataAccess.Repositories.Interfaces; using Domain.DTOs; using Domain.Models; using Microsoft.EntityFrameworkCore; using Persistence; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace DataAccess.Repositories { public class TravelPlanStatusRepository : ITravelPlanStatusRepository { private readonly AppDbContext _dbContext; public TravelPlanStatusRepository(AppDbContext dbContext) { _dbContext = dbContext; } public async Task<List<TravelPlanStatus>> ListAsync() { var tpStatuses = await _dbContext.TravelPlanStatuses.ToListAsync(); return tpStatuses; } public async Task<TravelPlanStatus> GetStatusAsync(TravelPlanStatusEnum status) { var tpStatus = await _dbContext.TravelPlanStatuses.Where((tps) => tps.UniqStatus == status).FirstOrDefaultAsync(); return tpStatus; } } }<file_sep>using Business.TravelPlan.Interfaces; using Microsoft.AspNetCore.Mvc; using System.Threading.Tasks; namespace TravelogApi.Controllers { public class TravelPlanStatusController : Controller { private readonly ITravelPlanStatusService _travelPlanStatusService; public TravelPlanStatusController(ITravelPlanStatusService travelPlanStatusService) { _travelPlanStatusService = travelPlanStatusService; } public async Task<IActionResult> List() { try { var statuses = await _travelPlanStatusService.ListAsync(); return Ok(statuses); } catch { throw; } } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Domain.DTOs { public class AnnouncementEnvelope { public List<TPAnnouncementDto> AnnouncementDtos { get; set; } public int AnnouncementCount { get; set; } } } <file_sep>using Business.TravelPlan.Interfaces; using DataAccess.Common.Enums; using DataAccess.CustomExceptions; using DataAccess.Repositories.Interfaces; using Domain.DTOs; using Microsoft.AspNetCore.Mvc; using System; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; namespace TravelogApi.Controllers { //[Authorize] public class TravelPlanController : Controller { private readonly ITravelPlanService _travelPlanService; private readonly IUserRepository _userRepository; private readonly IUserTravelPlanService _userTravelPlanService; private readonly ITravelPlanInvitationService _travelPlanInvitationService; public TravelPlanController(IUserRepository userRepository, IUserTravelPlanService userTravelPlanService, ITravelPlanInvitationService travelPlanInvitationService, ITravelPlanService travelPlanService) { _userRepository = userRepository; _userTravelPlanService = userTravelPlanService; _travelPlanInvitationService = travelPlanInvitationService; _travelPlanService = travelPlanService; } [HttpPost] public async Task<IActionResult> Create([FromBody] TravelPlanDto travelPlanDto) { try { var userId = HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value; var newTravelPlan = await _travelPlanService.CreateAsync(travelPlanDto, new Guid(userId)); return Ok(newTravelPlan); } catch (Exception exc) { return BadRequest(); } } [HttpPut] public async Task<IActionResult> Edit([FromBody] TravelPlanDto travelPlanDto) { try { var userId = HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value; var editedTravelPlanDto = await _travelPlanService.EditAsync(travelPlanDto, new Guid(userId)); return Ok(editedTravelPlanDto); } catch (InsufficientRightsException insufRights) { return BadRequest(new { Message = insufRights.Message }); } catch (Exception exc) { return BadRequest(); } } [HttpPost] public async Task<IActionResult> SetStatus([FromQuery] string id, [FromQuery] int status) { try { var userId = HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value; var tpIdAndStatusDto = await _travelPlanService.SetStatusAsync(new Guid(id), new Guid(userId), status); return Ok(tpIdAndStatusDto); } catch (InsufficientRightsException insufRights) { return BadRequest(new { Message = insufRights.Message }); } catch (Exception exc) { return BadRequest(new { Message = "Error occurred updating status" }); } } [HttpDelete] public async Task<IActionResult> Delete([FromQuery] string id) { try { var userId = HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value; var isSuccessful = await _travelPlanService.DeleteAsync(new Guid(id), new Guid(userId)); if (!isSuccessful) return StatusCode(500); return Ok(); } catch (InsufficientRightsException insufRights) { return BadRequest(new { Message = insufRights.Message }); } catch (Exception exc) { return BadRequest(); } } [HttpGet] public async Task<IActionResult> Details([FromQuery] string id) { try { var travelPlanId = new Guid(id); var userId = HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value; var travelers = await _userTravelPlanService.GetTravelersForActivityAsync(travelPlanId); if (!travelers.Contains(new Guid(userId))) { return Forbid(); } var userTravelers = await _userRepository.GetUsersAsync(travelers); var travelPlanDTO = await _travelPlanService.GetAsync(travelPlanId, includeStatus: true); travelPlanDTO.Travelers = userTravelers.ToList(); return Ok(travelPlanDTO); } catch { return BadRequest(); } } [HttpGet] public async Task<IActionResult> List([FromQuery] int? status = null) { try { var loggedInUserId = HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value; var lstTravelPlanDTO = await _travelPlanService.ListAsync(new Guid(loggedInUserId), status); return Ok(lstTravelPlanDTO); } catch (Exception) { return BadRequest(); } } [HttpPost] public async Task<IActionResult> RemoveTraveler(string travelerUsername, Guid travelPlanId) { try { var loggedInUserId = HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value; var isSuccessful = await _travelPlanService.RemoveTraveler(new Guid(loggedInUserId), travelerUsername, travelPlanId); if (!isSuccessful) { return BadRequest(new { Message = "Could not remove traveler" }); } return Ok(); } catch (InsufficientRightsException insufRights) { return BadRequest(new { Message = insufRights.Message }); } catch (Exception exc) { return BadRequest(new { Message = "An error occurred sending invitation" }); } } [HttpPost] public async Task<IActionResult> CreateInvitation(string inviteeUsername, Guid travelPlanId) { try { var loggedInUserId = HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value; await _travelPlanInvitationService.InviteUser(new Guid(loggedInUserId), inviteeUsername, travelPlanId); return Ok(); } catch (InsufficientRightsException insufRights) { return BadRequest(new { Message = insufRights.Message }); } catch (UserNotFoundException notFoundExc) { return BadRequest(new { Message = notFoundExc.Message }); } catch (UniqueConstraintException uniqExc) { return BadRequest(new { Message = uniqExc.Message }); } catch (CommonException commExc) { return BadRequest(new { Message = commExc.Message }); } catch (Exception exc) { return BadRequest(new { Message = "An error occurred sending invitation" }); } } } }<file_sep>using Domain.DTOs; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Business.TravelPlan.Interfaces { public interface ITPAnnouncementService { Task<AnnouncementEnvelope> ListAsync(Guid travelPlanId, int limit, int offset); Task<TPAnnouncementDto> GetAsync(Guid announcementId); Task<bool> DeleteAsync(Guid announcementId, Guid loggedInUserId); Task<TPAnnouncementDto> CreateAsync(TPAnnouncementDto announcementDto, Guid loggedInUserId); Task<TPAnnouncementDto> EditAsync(TPAnnouncementDto announcementDto, Guid loggedInUserId); } } <file_sep>using Business.TravelPlan.Interfaces; using DataAccess.CustomExceptions; using DataAccess.Repositories.Interfaces; using Domain.DTOs; using Domain.Models; using Persistence; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Business.TravelPlan { public class TPActivityService : ITPActivityService { private readonly AppDbContext _dbContext; private readonly ITravelPlanService _travelPlanService; private readonly ITravelPlanActivityRepository _travelPlanActivityRepository; public TPActivityService(AppDbContext dbContext, ITravelPlanService travelPlanService, ITravelPlanActivityRepository travelPlanActivityRepository) { _dbContext = dbContext; _travelPlanService = travelPlanService; _travelPlanActivityRepository = travelPlanActivityRepository; } public async Task<TravelPlanActivityDto> CreateAsync(TravelPlanActivityDto activityDto, Guid userId) { try { var travelPlan = await _travelPlanService.GetAsync(activityDto.TravelPlanId); if (travelPlan == null) throw new Exception("Travel Plan Not Found"); //map here var newActivity = new TravelPlanActivity { Name = activityDto.Name, StartTime = activityDto.StartTime, EndTime = activityDto.EndTime, Category = activityDto.Category, Location = new Location { Address = activityDto.Location.Address, Latitude = activityDto.Location.Latitude, Longitude = activityDto.Location.Longitude, }, HostId = userId, TravelPlanId = activityDto.TravelPlanId }; var addedActivity = await _travelPlanActivityRepository.CreateAsync(newActivity); return new TravelPlanActivityDto(addedActivity); } catch (Exception) { throw; } } public async Task<bool> DeleteAsync(Guid activityId, Guid userId) { try { var activityToDelete = await _travelPlanActivityRepository.GetAsync(activityId); if (activityToDelete == null) { //log maybe? return true; } if (activityToDelete.HostId != userId) throw new InsufficientRightsException("Insufficient rights to delete activity"); var isSuccessful = await _travelPlanActivityRepository.DeleteAsync(activityToDelete); return isSuccessful; } catch (Exception) { throw; } } public async Task<TravelPlanActivityDto> EditAsync(TravelPlanActivityDto activityDto, Guid userId) { try { var activityToEdit = await _travelPlanActivityRepository.GetAsync(activityDto.Id); if (activityToEdit == null) throw new Exception("Activity not found"); if (activityToEdit.HostId != userId) throw new InsufficientRightsException("Insufficient rights to edit activity"); //map lib here activityToEdit.Name = activityDto.Name; activityToEdit.StartTime = activityDto.StartTime; activityToEdit.EndTime = activityDto.EndTime; activityToEdit.Location.Address = activityDto.Location.Address; activityToEdit.Location.Longitude = activityDto.Location.Longitude; activityToEdit.Location.Latitude = activityDto.Location.Latitude; activityToEdit.Category = activityDto.Category; var isSuccessful = await _dbContext.SaveChangesAsync() > 0; if (isSuccessful) { return new TravelPlanActivityDto(activityToEdit); } throw new Exception("Error saving changes"); } catch (Exception) { throw; } } public async Task<TravelPlanActivityDto> GetAsync(Guid activityId) { try { var activity = await _travelPlanActivityRepository.GetAsync(activityId); return new TravelPlanActivityDto(activity); } catch (Exception) { throw; } } public async Task<List<TravelPlanActivityDto>> ListAsync(Guid travelPlanId) { try { var lstActivities = await _travelPlanActivityRepository.ListAsync(travelPlanId); var lstActivityDto = lstActivities.Select((a) => new TravelPlanActivityDto(a)).ToList(); return lstActivityDto; } catch (Exception) { throw; }; } } }<file_sep>using Business.TravelPlan.Interfaces; using DataAccess.CustomExceptions; using DataAccess.Repositories.Interfaces; using Domain.DTOs; using Domain.Models; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace Business.TravelPlan { public class TravelPlanInvitationService : ITravelPlanInvitationService { private readonly IPlanInvitationRepository _planInvitationRepository; private readonly ITravelPlanService _travelPlanService; private readonly ITravelPlanRepository _travelPlanRepository; private readonly IUserRepository _userRepository; public TravelPlanInvitationService(IPlanInvitationRepository planInvitationRepository, ITravelPlanService travelPlanService, ITravelPlanRepository travelPlanRepository, IUserRepository userRepository) { _planInvitationRepository = planInvitationRepository; _travelPlanService = travelPlanService; _travelPlanRepository = travelPlanRepository; _userRepository = userRepository; } public async Task AcceptInvitation(Guid invitee, int invitationId) { //get invitation var invitation = await _planInvitationRepository.GetInvitation(invitationId); if (invitation?.InviteeId != invitee) { throw new Exception("Cannot accept invitation"); } var isSuccessful = await _travelPlanService.AddTravelerAsync(invitation.TravelPlanId, invitee); if (isSuccessful) { await _planInvitationRepository.DeleteInvitation(invitation); } } public async Task DeclineInvitation(Guid invitee, int invitationId) { try { var invitation = await _planInvitationRepository.GetInvitation(invitationId); //validate decline if (invitation == null) { return; } if (invitation?.InviteeId != invitee) { throw new Exception("Cannot delete invitation"); } await _planInvitationRepository.DeleteInvitation(invitation); } catch { throw; } } public async Task InviteUser(Guid inviter, string inviteeUsername, Guid travelPlanId) { try { var travelPlan = await _travelPlanRepository.GetAsync(travelPlanId, includeUTP: true); //validate the inviter is the host if (travelPlan.CreatedById != inviter) { //log here throw new InsufficientRightsException("User doesn't have rights to add to travelplan"); } //validate invitee exists var userToInvite = await _userRepository.GetUserAsync(inviteeUsername); if (userToInvite == null) { //log here throw new UserNotFoundException("User to add does not exist"); } //check if user to invite is already part of plan if (travelPlan.UserTravelPlans.Exists((utp) => utp.TravelPlanId == new Guid(userToInvite.Id))) { throw new CommonException("User is already a traveler!"); } var newInvitation = new PlanInvitation { Created = DateTime.UtcNow, Expiration = DateTime.UtcNow.AddDays(7), InvitedById = inviter, InviteeId = new Guid(userToInvite.Id), TravelPlanId = travelPlanId }; await _planInvitationRepository.InviteUser(newInvitation); } catch (Exception) { throw; } } public async Task<IEnumerable<PlanInvitationDto>> List(Guid loggedInUserId) { try { //validate user var currUser = await _userRepository.GetUserAsync(loggedInUserId); if (currUser == null) { //log here throw new UserNotFoundException("User to add does not exist"); } var userInvitations = await _planInvitationRepository.List(loggedInUserId); if (userInvitations == null) { return new List<PlanInvitationDto>(); } //get the inviters username foreach (var inv in userInvitations) { var inviterUser = await _userRepository.GetUserAsync(inv.InvitedById); if (inviterUser == null) { userInvitations.Remove(inv); } inv.InviterUsername = inviterUser.UserName; } return userInvitations; } catch (Exception) { throw; } } } }<file_sep>using Business.TravelPlan.Interfaces; using DataAccess.Repositories.Interfaces; using Domain.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Business.TravelPlan { public class UserTravelPlanService : IUserTravelPlanService { private readonly IUserTravelPlanRepository _userTravelPlanRepository; public UserTravelPlanService(IUserTravelPlanRepository userTravelPlanRepository) { _userTravelPlanRepository = userTravelPlanRepository; } public async Task<bool> Delete(UserTravelPlan userTPToRemove) { try { var isSuccessful = await _userTravelPlanRepository.Delete(userTPToRemove); return isSuccessful; } catch (Exception) { throw; } } public async Task<IEnumerable<Guid>> GetTravelersForActivityAsync(Guid travelPlanId) { try { var travelerIDs = await _userTravelPlanRepository.GetTravelersForActivityAsync(travelPlanId); return travelerIDs; } catch { throw; } } public async Task<IEnumerable<Guid>> GetUserTravelPlanIDsAsync(Guid userId) { try { var travelPlanIDs = await _userTravelPlanRepository.GetUserTravelPlanIDsAsync(userId); return travelPlanIDs; } catch (Exception) { throw; } } } } <file_sep>using DataAccess.CustomExceptions; using DataAccess.Repositories.Interfaces; using Domain.DTOs; using Domain.Models; using Microsoft.EntityFrameworkCore; using Persistence; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace DataAccess.Repositories { public class TravelPlanActivityRepository : ITravelPlanActivityRepository { private readonly AppDbContext _dbContext; public TravelPlanActivityRepository(AppDbContext dbContext) { _dbContext = dbContext; } public async Task<TravelPlanActivity> CreateAsync(TravelPlanActivity newActivity) { try { _dbContext.TravelPlanActivities.Add(newActivity); var isSuccessful = await _dbContext.SaveChangesAsync() > 0; if (isSuccessful) { return newActivity; } throw new Exception("Error saving changes"); } catch (Exception) { throw; } } public async Task<bool> DeleteAsync(TravelPlanActivity activityToDelete) { try { _dbContext.TravelPlanActivities.Remove(activityToDelete); var isSuccessful = await _dbContext.SaveChangesAsync() > 0; return isSuccessful; } catch (Exception) { throw; } } public async Task<TravelPlanActivity> GetAsync(Guid activityId) { try { var activity = await _dbContext.TravelPlanActivities.Include(tpa => tpa.Location).FirstOrDefaultAsync(tpa => tpa.TravelPlanActivityId == activityId); if (activity == null) throw new Exception("Activity Not Found"); return activity; } catch { throw; } } public async Task<List<TravelPlanActivity>> ListAsync(Guid travelPlanId) { try { //get all activities for a given travel plan var lstActivities = await _dbContext.TravelPlanActivities .Include(tpa => tpa.Location) .Where((tpa) => tpa.TravelPlanId == travelPlanId) .OrderBy(a => a.StartTime).ToListAsync(); return lstActivities; } catch { throw; } } } }<file_sep>using Domain.DTOs; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Business.TravelPlan.Interfaces { public interface ITravelPlanInvitationService { Task InviteUser(Guid inviter, string inviteeUsername, Guid TravelPlanId); Task<IEnumerable<PlanInvitationDto>> List(Guid loggedInUserId); Task AcceptInvitation(Guid invitee, int invitationId); Task DeclineInvitation(Guid invitee, int invitationId); } } <file_sep>using DataAccess.CustomExceptions; using DataAccess.Repositories.Interfaces; using Domain.DTOs; using Domain.Models; using Microsoft.EntityFrameworkCore; using Persistence; using System; using System.Linq; using System.Threading.Tasks; namespace DataAccess.Repositories { public class TPAnnouncementRepository : ITPAnnouncementRepository { private readonly AppDbContext _dbContext; public TPAnnouncementRepository(AppDbContext dbContext, ITravelPlanRepository travelPlanRepository) { _dbContext = dbContext; } public async Task<TPAnnouncement> CreateAsync(TPAnnouncement newAnnouncement) { try { _dbContext.TPAnnouncements.Add(newAnnouncement); var isSuccessful = await _dbContext.SaveChangesAsync() > 0; if (isSuccessful) { return newAnnouncement; } throw new CommonException("Problem occurred creating announcement"); } catch (Exception) { throw; } } public async Task<bool> DeleteAsync(TPAnnouncement announcementToDelete) { try { _dbContext.TPAnnouncements.Remove(announcementToDelete); var isSuccessful = await _dbContext.SaveChangesAsync() > 0; return isSuccessful; } catch (Exception exc) { throw; } } public async Task<TPAnnouncement> GetAsync(Guid announcementId) { try { //get list of announcements for travel plan var announcement = await _dbContext.TPAnnouncements.FindAsync(announcementId); if (announcement == null) { throw new CommonException("Invalid Announcement"); } return announcement; } catch (Exception exc) { throw; } } public async Task<AnnouncementEnvelope> ListAsync(Guid travelPlanId, int limit, int offset) { try { //get list of announcements for travel plan var annQueryable = _dbContext.TPAnnouncements .Where((tpa) => tpa.TravelPlanId == travelPlanId) .OrderByDescending((tpa) => tpa.CreatedDate) .AsQueryable(); var announcements = await annQueryable .Skip(offset) .Take(limit) .ToListAsync(); var announcementDTOs = announcements.Select((a) => new TPAnnouncementDto(a)).ToList(); return new AnnouncementEnvelope { AnnouncementDtos = announcementDTOs, AnnouncementCount = annQueryable.Count() }; } catch (Exception exc) { throw; } } } }<file_sep>using Business.TravelPlan.Interfaces; using DataAccess.CustomExceptions; using DataAccess.Repositories.Interfaces; using Domain.DTOs; using Microsoft.AspNetCore.Mvc; using System; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; namespace TravelogApi.Controllers { [Route("/TravelPlan/[controller]/[action]")] public class AnnouncementController : Controller { private readonly ITPAnnouncementService _announcementService; public AnnouncementController(ITPAnnouncementService announcementService) { _announcementService = announcementService; } [HttpGet] public async Task<IActionResult> List([FromQuery] Guid travelPlanId, [FromQuery] int limit = 5, [FromQuery] int offset = 0) { try { var announcements = await _announcementService.ListAsync(travelPlanId, limit, offset); return Ok(announcements); } catch (Exception) { return BadRequest(new { Message = "Error Occurred" }); } } [HttpDelete] public async Task<IActionResult> Delete([FromQuery] Guid announcementId) { try { var userId = HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value; var isSuccessful = await _announcementService.DeleteAsync(announcementId, new Guid(userId)); if (isSuccessful) { return Ok(); } return BadRequest(new { Message = "Error Occurred" }); } catch (InsufficientRightsException insufExc) { return BadRequest(new { Message = insufExc.Message }); } catch (CommonException commExc) { return BadRequest(new { Message = commExc.Message }); } catch (Exception) { return BadRequest(new { Message = "Error Occurred" }); } } [HttpPost] public async Task<IActionResult> Create([FromBody] TPAnnouncementDto announcementDto) { try { var userId = HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value; var announcement = await _announcementService.CreateAsync(announcementDto, new Guid(userId)); return Ok(announcement); } catch (InsufficientRightsException insufExc) { return BadRequest(new { Message = insufExc.Message }); } catch (CommonException commExc) { return BadRequest(new { Message = commExc.Message }); } catch (Exception) { return BadRequest(new { Message = "Error Occurred" }); } } [HttpPut] public async Task<IActionResult> Edit([FromBody] TPAnnouncementDto announcementDto) { try { var userId = HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value; var announcement = await _announcementService.EditAsync(announcementDto, new Guid(userId)); return Ok(announcement); } catch (InsufficientRightsException insufExc) { return BadRequest(new { Message = insufExc.Message }); } catch (CommonException commExc) { return BadRequest(new { Message = commExc.Message }); } catch (Exception) { return BadRequest(new { Message = "Error Occurred" }); } } } }<file_sep>using Domain.DTOs; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Business.TravelPlan.Interfaces { public interface ITravelPlanService { Task<TravelPlanDto> CreateAsync(TravelPlanDto travelPlanDto, Guid userId); Task<TravelPlanDto> EditAsync(TravelPlanDto travelPlanDto, Guid userId); Task<Dictionary<string, TravelPlanStatusDto>> SetStatusAsync(Guid travelPlanId, Guid userId, int status); Task<bool> AddTravelerAsync(Guid travelPlanId, Guid userToAddId); Task<bool> DeleteAsync(Guid travelPlanId, Guid userId); Task<TravelPlanDto> GetAsync(Guid travelPlanId, bool includeUTP = false, bool includeStatus = false); Task<List<TravelPlanDto>> ListAsync(Guid userId, int? status = null); Task<bool> RemoveTraveler(Guid loggedInUserId, string travelerUsername, Guid travelPlanId); } } <file_sep>using Dapper; using DataAccess.Repositories.Interfaces; using Domain.Models; using Microsoft.Data.SqlClient; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Persistence; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace DataAccess.Repositories { public class UserTravelPlanRepository : IUserTravelPlanRepository { private readonly AppDbContext _dbContext; public string ConnectionString { get; } public UserTravelPlanRepository(IConfiguration configuration, AppDbContext dbContext) { this.ConnectionString = configuration.GetConnectionString("TravelogApi"); _dbContext = dbContext; } public async Task<IEnumerable<Guid>> GetTravelersForActivityAsync(Guid travelPlanId) { const string GET_TRAVELERS_SQL = @"SELECT USERID FROM USERTRAVELPLANS WHERE TRAVELPLANID = @Id"; using (SqlConnection connection = new SqlConnection(ConnectionString)) { //use string literals and let dapper handle parameterized querying var travelerIDs = await connection.QueryAsync<Guid>(GET_TRAVELERS_SQL, new { Id = travelPlanId }); return travelerIDs; } } public async Task<IEnumerable<Guid>> GetUserTravelPlanIDsAsync(Guid userId) { //get travel plans associated with the user, whether they created it or just belong it var userTravelPlanIds = await _dbContext.UserTravelPlans.Where(utp => utp.UserId == userId).Select((utp) => utp.TravelPlanId).ToListAsync(); return userTravelPlanIds; } public async Task<bool> Delete(UserTravelPlan userTPToRemove) { //remove entry tying user to TP _dbContext.UserTravelPlans.Remove(userTPToRemove); var isSuccessful = await _dbContext.SaveChangesAsync() > 0; return isSuccessful; } } } <file_sep>using Business.TravelPlan.Interfaces; using DataAccess.Common.Enums; using DataAccess.CustomExceptions; using DataAccess.Repositories.Interfaces; using Domain.DTOs; using Domain.Models; using Persistence; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Business.TravelPlan { public class TravelPlanService : ITravelPlanService { private readonly ITravelPlanRepository _travelPlanRepository; private readonly IUserRepository _userRepository; private readonly IUserTravelPlanService _userTravelPlanService; private readonly ITravelPlanStatusService _travelPlanStatusService; private readonly AppDbContext _dbContext; public TravelPlanService(ITravelPlanRepository travelPlanRepository, IUserRepository userRepository, IUserTravelPlanService userTravelPlanService, ITravelPlanStatusService travelPlanStatusService, AppDbContext dbContext) { _travelPlanRepository = travelPlanRepository; _userRepository = userRepository; _userTravelPlanService = userTravelPlanService; _travelPlanStatusService = travelPlanStatusService; _dbContext = dbContext; } public async Task<bool> AddTravelerAsync(Guid travelPlanId, Guid userToAddId) { try { //check if user exists var userExists = await _userRepository.DoesUserExistAsync(userToAddId); if (!userExists) throw new Exception("Invalid User Id"); var isSuccessful = await _travelPlanRepository.AddTravelerAsync(travelPlanId, userToAddId); return isSuccessful; } catch (Exception) { throw; } } public async Task<TravelPlanDto> CreateAsync(TravelPlanDto travelPlanDto, Guid userId) { try { //map here var newTravelPlan = new Domain.Models.TravelPlan { Name = travelPlanDto.Name, Description = travelPlanDto.Description, StartDate = travelPlanDto.StartDate, EndDate = travelPlanDto.EndDate, CreatedById = userId, TravelPlanStatusId = (int)TravelPlanStatusEnum.Created, //add jxn, auto adds to UTP table UserTravelPlans = new List<UserTravelPlan> { new UserTravelPlan { UserId = userId } } }; var tp = await _travelPlanRepository.CreateAsync(newTravelPlan); return new TravelPlanDto(tp); } catch (Exception) { throw; } } public async Task<bool> DeleteAsync(Guid travelPlanId, Guid userId) { try { var travelPlanToDelete = await _travelPlanRepository.GetAsync(travelPlanId); if (travelPlanToDelete == null) return true; if (travelPlanToDelete.CreatedById != userId) throw new InsufficientRightsException("Insufficient rights to delete Travel Plan"); var isSuccessful = await _travelPlanRepository.DeleteAsync(travelPlanToDelete); return isSuccessful; } catch (Exception) { throw; } } public async Task<TravelPlanDto> EditAsync(TravelPlanDto travelPlanDto, Guid userId) { try { var travelPlanToEdit = await _travelPlanRepository.GetAsync(travelPlanDto.Id); if (travelPlanToEdit == null) throw new Exception("Travel Plan Not Found"); if (travelPlanToEdit.CreatedById != userId) throw new InsufficientRightsException("Insufficient rights to edit Travel Plan"); //map here travelPlanToEdit.TravelPlanId = travelPlanDto.Id; travelPlanToEdit.Name = travelPlanDto.Name; travelPlanToEdit.StartDate = travelPlanDto.StartDate; travelPlanToEdit.EndDate = travelPlanDto.EndDate; travelPlanToEdit.Description = travelPlanDto.Description; if (!_dbContext.ChangeTracker.HasChanges()) return travelPlanDto; var isSuccessful = await _dbContext.SaveChangesAsync() > 0; if (isSuccessful) { return new TravelPlanDto(travelPlanToEdit); } throw new Exception("Problem Editing Travel Plan"); } catch (Exception) { throw; } } public async Task<TravelPlanDto> GetAsync(Guid travelPlanId, bool includeUTP = false, bool includeStatus = false) { var travelPlan = await _travelPlanRepository.GetAsync(travelPlanId, includeUTP); if (travelPlan == null) throw new Exception("Travel Plan not found"); var travelPlanDto = new TravelPlanDto(travelPlan); if (includeStatus) { var tpStatus = await _travelPlanStatusService.GetStatusAsync((TravelPlanStatusEnum)travelPlan.TravelPlanStatusId); travelPlanDto.TravelPlanStatus = new TravelPlanStatusDto { UniqStatus = tpStatus.UniqStatus, Description = tpStatus.Description }; } return travelPlanDto; } public async Task<List<TravelPlanDto>> ListAsync(Guid userId, int? status = null) { try { //get travel plans associated with the user, whether they created it or just belong it var userTravelPlanIds = await _userTravelPlanService.GetUserTravelPlanIDsAsync(userId); var travelPlans = await _travelPlanRepository.GetTravelPlansWithFilterAsync(userTravelPlanIds, status); List<TravelPlanDto> lstTravelPlanDto = new List<TravelPlanDto>(); foreach (var tp in travelPlans) { var tpDto = new TravelPlanDto(tp); var tpStatus = await _travelPlanStatusService.GetStatusAsync((TravelPlanStatusEnum)tp.TravelPlanStatusId); tpDto.TravelPlanStatus = new TravelPlanStatusDto { UniqStatus = tpStatus.UniqStatus, Description = tpStatus.Description }; lstTravelPlanDto.Add(tpDto); } return lstTravelPlanDto; } catch (Exception) { throw; } } public async Task<bool> RemoveTraveler(Guid loggedInUserId, string travelerUsername, Guid travelPlanId) { try { var travelPlan = await _travelPlanRepository.GetAsync(travelPlanId, true); if (travelPlan == null) { throw new Exception("Travel Plan Not Found"); } //validate traveler to remove var travelerToRemove = await _userRepository.GetUserAsync(travelerUsername); if (travelerToRemove == null) { return true; } var userTPToRemove = travelPlan.UserTravelPlans?.Where((utp) => utp.UserId.ToString() == travelerToRemove.Id).FirstOrDefault(); //if user actually was never part of the utp then just return if (userTPToRemove == null) { return true; } var isUserHost = loggedInUserId == travelPlan.CreatedById; if(isUserHost && loggedInUserId == userTPToRemove.UserId) { throw new Exception("Host can't remove themselves from plan"); } var userNotHostButIsTraveler = !isUserHost && loggedInUserId == userTPToRemove.UserId; //hosts have delete rights or the travelers want to remove themselves if (isUserHost || userNotHostButIsTraveler) { var isSuccessful = await _userTravelPlanService.Delete(userTPToRemove); return isSuccessful; } else { throw new InsufficientRightsException("Insufficient rights to Travel Plan"); } } catch (Exception) { throw; } } public async Task<Dictionary<string, TravelPlanStatusDto>> SetStatusAsync(Guid travelPlanId, Guid userId, int status) { try { if (!Enum.IsDefined(typeof(TravelPlanStatusEnum), status)) { throw new Exception("Problem Setting Status of Travel Plan"); } var travelPlanToEdit = await _travelPlanRepository.GetAsync(travelPlanId); if (travelPlanToEdit == null) throw new Exception("Travel Plan Not Found"); if (travelPlanToEdit.CreatedById != userId) throw new InsufficientRightsException("Insufficient rights to edit Travel Plan"); travelPlanToEdit.TravelPlanStatusId = status; var isSuccessful = await _dbContext.SaveChangesAsync() > 0; if (isSuccessful) { var tpStatus = await _travelPlanStatusService.GetStatusAsync((TravelPlanStatusEnum)status); return new Dictionary<string, TravelPlanStatusDto> { { travelPlanId.ToString(), new TravelPlanStatusDto { UniqStatus = tpStatus.UniqStatus, Description = tpStatus.Description } } }; } throw new Exception("Problem occurred saving status of Travel Plan"); } catch (Exception) { throw; } } } }<file_sep>#build stage FROM mcr.microsoft.com/dotnet/core/sdk:3.1 as build WORKDIR /app #restore our project and deps WORKDIR /app COPY *.sln . COPY ./TravelogApi/*.csproj ./TravelogApi/ COPY ./Domain/*.csproj ./Domain/ COPY ./DataAccess/*.csproj ./DataAccess/ COPY ./Persistence/*.csproj ./Persistence/ COPY ./Business/*.csproj ./Business/ COPY ./TravelogApi.Tests/*.csproj ./TravelogApi.Tests/ RUN dotnet restore #copy rest and publish COPY ./TravelogApi/. ./TravelogApi/ COPY ./Domain/. ./Domain COPY ./DataAccess/. ./DataAccess/ COPY ./Persistence/. ./Persistence/ COPY ./Business/. ./Business/ COPY ./TravelogApi.Tests/. ./TravelogApi.Tests/ RUN dotnet publish -c release -o out #start our app stage FROM mcr.microsoft.com/dotnet/core/aspnet:3.1 WORKDIR /app COPY --from=build /app/out . ENTRYPOINT [ "dotnet", "TravelogApi.dll" ]
25a1c36e3eea53230c5ea3d0201769e5861559f2
[ "C#", "Dockerfile" ]
35
C#
kheneahm-ares/travelog-webapi
db2b9cd47d381fbd037dff207ea45b0457636af3
641340aabab78d3e1bb4ee36c38e89b1a8608858
refs/heads/master
<file_sep> #include <linux/netdevice.h> #include <linux/ethtool.h> #if IFNAMSIZ != 16 #error "IFNAMSIZ != 16 is not supported" #endif #define MAX_QUEUE_NUM 1024 /** * This union is use to store name of the specified interface * and read it as two different data types */ union name_buf{ char name[IFNAMSIZ]; struct { u64 hi; u64 lo; }name_int; }; /* data retrieved in tracepoints */ struct queue_data{ u64 total_pkt_len; u32 num_pkt; u32 size_64B; u32 size_512B; u32 size_2K; u32 size_16K; u32 size_64K; }; /* array of length 1 for device name */ BPF_ARRAY(name_map, union name_buf, 1); /* table for transmit & receive packets */ BPF_HASH(tx_q, u16, struct queue_data, MAX_QUEUE_NUM); BPF_HASH(rx_q, u16, struct queue_data, MAX_QUEUE_NUM); static inline int name_filter(struct sk_buff* skb){ /* get device name from skb */ union name_buf real_devname; struct net_device *dev; bpf_probe_read(&dev, sizeof(skb->dev), ((char *)skb + offsetof(struct sk_buff, dev))); bpf_probe_read(&real_devname, IFNAMSIZ, dev->name); int key=0; union name_buf *leaf = name_map.lookup(&key); if(!leaf){ return 0; } if((leaf->name_int).hi != real_devname.name_int.hi || (leaf->name_int).lo != real_devname.name_int.lo){ return 0; } return 1; } static void updata_data(struct queue_data *data, u64 len){ data->total_pkt_len += len; data->num_pkt ++; if(len / 64 == 0){ data->size_64B ++; } else if(len / 512 == 0){ data->size_512B ++; } else if(len / 2048 == 0){ data->size_2K ++; } else if(len / 16384 == 0){ data->size_16K ++; } else if(len / 65536 == 0){ data->size_64K ++; } } TRACEPOINT_PROBE(net, net_dev_start_xmit){ /* read device name */ struct sk_buff* skb = (struct sk_buff*)args->skbaddr; if(!name_filter(skb)){ return 0; } /* update table */ u16 qid = skb->queue_mapping; struct queue_data newdata; __builtin_memset(&newdata, 0, sizeof(newdata)); struct queue_data *data = tx_q.lookup_or_try_init(&qid, &newdata); if(!data){ return 0; } updata_data(data, skb->len); return 0; } TRACEPOINT_PROBE(net, netif_receive_skb){ struct sk_buff* skb = (struct sk_buff*)args->skbaddr; if(!name_filter(skb)){ return 0; } u16 qid = skb->queue_mapping; struct queue_data newdata; __builtin_memset(&newdata, 0, sizeof(newdata)); struct queue_data *data = rx_q.lookup_or_try_init(&qid, &newdata); if(!data){ return 0; } updata_data(data, skb->len); return 0; }
eccd2be4051f7ec3d7bb595cc866b808e8c9ca74
[ "C" ]
1
C
bbara/bcc
1294ec6bd3cd9b514ae02fc4a3a1cc8bce772d95
3950e378ffb22fa6e982ed348fc755c82e28a2fc
refs/heads/master
<file_sep>package hello; import counter.LongAdderCounter; import counter.SimpleCounter; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * The Web Service provides three APIs: * 1. /hello * 2. /twilio * 3. /count * 3 will return the total number of http get requests * Created by Yuwen on 11/19/15. */ @RestController public class HelloController { private SimpleCounter simpleCounter = new SimpleCounter(); @RequestMapping("/hello") public String hello(){ simpleCounter.increment(); return new String("Welcome!"); } @RequestMapping("/twilio") public String twilio(){ simpleCounter.increment(); return new String("Hello Twilio!"); } @RequestMapping("/count") public String totalCount(){ simpleCounter.increment(); return new String("Total number of requests is: " + simpleCounter.get()); } } <file_sep>package test; import counter.AtomicLongCounter; import counter.Counter; import counter.LongAdderCounter; import java.util.ArrayList; import java.util.Date; import java.util.List; import counter.SimpleCounter; import org.junit.Test; import static org.junit.Assert.*; /** * Created by Yuwen on 11/19/15. */ public class MyTest { private LongAdderCounter longAdderCounter = new LongAdderCounter(); private SimpleCounter simpleCounter = new SimpleCounter(); private AtomicLongCounter atomicLongCounter = new AtomicLongCounter(); // Three test threads are started every second private int numThread = 100000; // Number of counts per thread private int wordLoad = 10000; @Test public void Compare(){ long simpleDuration = setUp(simpleCounter); long longAdderDuration = setUp(longAdderCounter); long atomicLongDuration = setUp(atomicLongCounter); System.out.println("SimpleCounter duration is: " + simpleDuration); System.out.println("LongAdderCounter duration is: " + longAdderDuration); System.out.println("AtomicLongCounter duration is: " + atomicLongDuration); } public long setUp(Counter counter){ long begin = new Date().getTime(); List<Thread> threadList = new ArrayList<Thread>(); for(int i = 0; i < numThread; i++){ Thread t = new Thread(new Increment(counter, wordLoad)); threadList.add(t); t.start(); } try { for (int i = 0; i < threadList.size(); i++) { threadList.get(i).join(); } }catch (InterruptedException e){ e.printStackTrace(); } new Thread(new GetValue(counter)).run(); assertEquals(numThread * wordLoad, counter.get()); long end = new Date().getTime(); return end - begin; } private class Increment implements Runnable{ private int workLoad; private Counter counter; public Increment(Counter c, int init){ workLoad = init; counter = c; } public void run(){ for(int i = 0; i < workLoad; i++) { counter.increment(); } } } private class GetValue implements Runnable{ private Counter counter; public GetValue(Counter counter){ this.counter = counter; } public void run(){ try { Thread.sleep(10); System.out.println("Count number is " + counter.get()); }catch (InterruptedException e){ e.printStackTrace(); } } } } <file_sep>rootProject.name = 'SimpleCounter' <file_sep># SimpleCounter ## There are three implementations: 1. My implementation is SimpleCounter, which keeps a counter for each thread, indexed by a concurrent hashmap 2. LongAdderCounter is based on LongAdder, which implements a similar method with mine 3. AtomicLongCounter is based on AtomicLong, which is a lock protected long ## Test Counters Result The expected performance: LongAdderCounter is better than SimpleCounter, given its more efficient implementations. And SimpleCounter is better the AtomicLongCounter. As expected, an example on my machine gives the following results for 100,000 threads, each of which generates 10,000 counts: ``` Count number is 1000000000 Count number is 1000000000 Count number is 1000000000 SimpleCounter duration is: 14705 LongAdderCounter duration is: 8750 AtomicLongCounter duration is: 26153 ``` The time unit is milliseconds The test framework is Junit ## Test Web Service In the command line, please run the following command to start the Springboot application: > java -jar SimpleCounter-0.1.0.jar Then visit in any browser: ``` http://localhost:8080/hello http://localhost:8080/twilio http://localhost:8080/count ``` When you visit /count api, the page will shows the total number of counts
0d13154e1e44f2200754249ab70674a7570399d7
[ "Markdown", "Java", "Gradle" ]
4
Java
littleday/SimpleCounter
53710cf2780c2ea253116ac675fc93f47043856d
773c444e6799f430c80ef0d5452e7a2bcee70f1f
refs/heads/master
<file_sep>package ug.sharma.nov8eva import android.content.Intent import android.net.Uri import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Toast import com.bumptech.glide.Glide import kotlinx.android.synthetic.main.activity_full_article.* class FullArticle : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_full_article) datafromFirst() } private fun datafromFirst() { val image=intent.getStringExtra("img") val title=intent.getStringExtra("title") val desc=intent.getStringExtra("desc") val full=intent.getStringExtra("full") Glide.with(this).load(image).into(img1) title1.text=title.toString() descr1.text=desc.toString() btnFullArticle.setOnClickListener { var intent1= Intent(Intent.ACTION_VIEW, Uri.parse(full)) startActivity(intent1) } btnAdd.setOnClickListener { var intent1 = Intent(this, DataStorage::class.java) Toast.makeText(this,"data saved temporary",Toast.LENGTH_SHORT).show() intent1.putExtra("img", image) intent1.putExtra("title", title) intent1.putExtra("desc", desc) startActivity(intent1) } } }<file_sep>package ug.sharma.nov8eva.network import retrofit2.Retrofit import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory import ug.sharma.nov8eva.api.ApiClient object network { private const val base="https://newsapi.org/" fun getDataByNetwork():ApiClient{ val builder=Retrofit.Builder() .baseUrl(base) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava3CallAdapterFactory.create()) .build() return builder.create(ApiClient::class.java) } }<file_sep>package ug.sharma.nov8eva.mainrepo import io.reactivex.rxjava3.core.Observable import ug.sharma.nov8eva.model.ResponseDTO import ug.sharma.nov8eva.network.network class MainRepo { fun getDataByRepo():Observable<ResponseDTO>{ return network.getDataByNetwork().getDataByApi() } }<file_sep>package ug.sharma.nov8eva.recycler import android.view.View import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import ug.sharma.nov8eva.R import ug.sharma.nov8eva.listener.NewsListener import ug.sharma.nov8eva.model.Article class Holderr(var itemView: View,val clicklistener:NewsListener) : RecyclerView.ViewHolder(itemView) { fun setdata(article: Article,pos:Int) { val image = itemView.findViewById<ImageView>(R.id.img) val title = itemView.findViewById<TextView>(R.id.title) val date = itemView.findViewById<TextView>(R.id.date) val desc = itemView.findViewById<TextView>(R.id.descr) title.text=article.title date.text=article.publishedAt desc.text=article.description Glide.with(image).load(article.urlToImage).into(image) itemView.setOnClickListener { clicklistener.onNews(article,adapterPosition) } } }<file_sep>package ug.sharma.nov8eva import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import com.bumptech.glide.Glide import kotlinx.android.synthetic.main.activity_data_storage.* import kotlinx.android.synthetic.main.activity_full_article.* import ug.sharma.nov8eva.model.Article class DataStorage : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_data_storage) add() } fun add() { val image=intent.getStringExtra("img") val title=intent.getStringExtra("title") Glide.with(this).load(image).into(imggg) Title.text=title.toString() } }<file_sep>package ug.sharma.nov8eva.recycler import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import ug.sharma.nov8eva.R import ug.sharma.nov8eva.listener.NewsListener import ug.sharma.nov8eva.model.Article class Adpterr(val article: List<Article>,var clicklistener:NewsListener):RecyclerView.Adapter<Holderr>() { override fun onCreateViewHolder(parent: ViewGroup, viewtype: Int): Holderr { val view=LayoutInflater.from(parent.context).inflate(R.layout.item_design,parent,false) return Holderr(view,clicklistener) } override fun onBindViewHolder(holder: Holderr, position: Int) { var article:Article=article[position] holder.setdata(article,position) } override fun getItemCount(): Int { return article.size } }<file_sep>package ug.sharma.nov8eva import android.content.Intent import android.net.Uri import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.provider.ContactsContract.Intents.Insert.ACTION import android.util.Log import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.LinearLayoutManager import kotlinx.android.synthetic.main.activity_main.* import ug.sharma.nov8eva.listener.NewsListener import ug.sharma.nov8eva.mainuimodel.MainUiModel import ug.sharma.nov8eva.mainview.MainViewModel import ug.sharma.nov8eva.model.Article import ug.sharma.nov8eva.model.ResponseDTO import ug.sharma.nov8eva.recycler.Adpterr import java.util.Collections.emptyList class MainActivity : AppCompatActivity(),NewsListener{ private lateinit var mainViewModel: MainViewModel private var list=emptyList<Article>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) mainViewModel=ViewModelProvider(this).get(MainViewModel::class.java) mainViewModel.CallApiByView() mainViewModel.liveData.observe(this, { when (it) { is MainUiModel.onSucess -> { list = it.responseDTO.articles setrecycler() } is MainUiModel.onError -> { Log.d("umang", it.error) } } }) } private fun setrecycler() { val Madapter=Adpterr(list,this) val linearLayoutManager=LinearLayoutManager(this) recycler.adapter=Madapter recycler.layoutManager=linearLayoutManager } override fun onNews(article: Article, Position: Int) { var intent=Intent(this@MainActivity,FullArticle::class.java) intent.putExtra("img",article.urlToImage) intent.putExtra("full",article.url) intent.putExtra("title",article.title) intent.putExtra("desc",article.description) startActivity(intent) } }<file_sep>package ug.sharma.nov8eva.listener import ug.sharma.nov8eva.model.Article interface NewsListener { fun onNews(article: Article, Position: Int) }<file_sep>package ug.sharma.nov8eva.mainview import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers import io.reactivex.rxjava3.core.Observer import io.reactivex.rxjava3.disposables.Disposable import io.reactivex.rxjava3.schedulers.Schedulers import ug.sharma.nov8eva.mainrepo.MainRepo import ug.sharma.nov8eva.mainuimodel.MainUiModel import ug.sharma.nov8eva.model.ResponseDTO class MainViewModel : ViewModel() { private val mainRepo=MainRepo() private val mutableLiveData=MutableLiveData<MainUiModel>() val liveData:LiveData<MainUiModel> =mutableLiveData private lateinit var disposable: Disposable fun CallApiByView(){ mainRepo.getDataByRepo().subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()).subscribe(object : Observer<ResponseDTO>{ override fun onSubscribe(d: Disposable) { disposable=d } override fun onNext(t: ResponseDTO) { mutableLiveData.value=MainUiModel.onSucess(t) } override fun onError(e: Throwable) { } override fun onComplete() { } }) } }<file_sep>package ug.sharma.nov8eva.api import io.reactivex.rxjava3.core.Observable import io.reactivex.rxjava3.core.Observer import retrofit2.Call import retrofit2.http.GET import retrofit2.http.Query import ug.sharma.nov8eva.model.ResponseDTO interface ApiClient { //https://newsapi.org/v2/everything?q=tesla&from=2021-11-08&sortBy=popularity&apiKey=<KEY> @GET("v2/everything?q=political&from=2021-11-08&sortBy=popularity&apiKey=<KEY>") fun getDataByApi():Observable<ResponseDTO> @GET("v2/everything?q=political&from=2021-11-08&sortBy=popularity&apiKey=<KEY>") fun getDataByBase(): Call<ResponseDTO> }<file_sep>package ug.sharma.nov8eva.mainuimodel import ug.sharma.nov8eva.model.ResponseDTO sealed class MainUiModel { data class onSucess(var responseDTO: ResponseDTO):MainUiModel() data class onError(var error:String):MainUiModel() }
5a3ee5bc67da4997f91d8a48d31276def1735a75
[ "Kotlin" ]
11
Kotlin
umangsh28/MVVM_with_Retrofit
5fba05da362f537a7a49af7ec4a8f142aa8c4e1f
d0c240b1cfc57923337592778edd0830a76b7189
refs/heads/master
<repo_name>andrei-radzetski/simple-logistics-server<file_sep>/app/dictionary/dictionary-routing.js const ctrl = require('./dictionary-controller') const Routing = require('../rest').Routing const Route = require('../rest').Route const namespase = '/dictionaries' const routes = [ { method: Route.GET, path: '/', protection: 'admin', handler: (req, res, next) => ctrl.find(req, res, next) }, { method: Route.POST, path: '/', protection: 'admin', handler: (req, res, next) => ctrl.create(req, res, next) }, { method: Route.DELETE, path: '/:id', protection: 'admin', handler: (req, res, next) => ctrl.remove(req, res, next) }, { method: Route.GET, path: '/filter', protection: 'admin', handler: (req, res, next) => ctrl.filter(req, res, next) }, { method: Route.GET, path: '/types', protection: 'admin', handler: (req, res, next) => ctrl.types(req, res, next) }, { method: Route.GET, path: '/languages', handler: (req, res, next) => ctrl.languages(req, res, next) }, { method: Route.GET, path: '/countries', handler: (req, res, next) => ctrl.countries(req, res, next) }, { method: Route.GET, path: '/request/kinds', handler: (req, res, next) => ctrl.requestKinds(req, res, next) }, { method: Route.GET, path: '/request/servives', handler: (req, res, next) => ctrl.requestServices(req, res, next) }, { method: Route.GET, path: '/transports', handler: (req, res, next) => ctrl.trasports(req, res, next) } ] module.exports = (app) => { new Routing(app, namespase, routes).commit() } <file_sep>/app/store/index.js module.exports = { db: require('./store'), AbstractService: require('./abstract-service') } <file_sep>/app/logger/index.js const log4js = require('log4js') const config = require('../config') log4js.configure(config.get('log4js')) /** * Get logger by module name, if module is undefined, logger name will be [default]. * * @param {Object} module - Module meta data. * @returns {Logger} */ module.exports = function (module) { let name = module ? module.filename : '[default]' let key = '/app/' /* application path */ let keyIndex = name.indexOf(key) name = keyIndex !== -1 ? '[' + name.substr(keyIndex + 1) + ']' : name return log4js.getLogger(name) } <file_sep>/app/rest/abstract-controller.js const RestUtil = require('../rest/rest-util') const ParamsValidator = require('../validation/params-validator') const ParamValidator = require('../validation/param-validator') const logger = require('../logger')(module) /** * @abstract */ class AbstractController { /** * @param {AbstractService} service */ constructor (service) { if (new.target === AbstractController) { throw new TypeError('Cannot construct abstract instances directly.') } if (service == null) { throw new TypeError('Service must be defined.') } this.service = service } /** * @abstract * @returns {Observable<Object>} */ validateCreateParams(params) { throw new TypeError('"validateCreate" must be overridden.') } /** * Create response. * * @param {Object} response - data for the response. * @param {Error} error * @param {string} message - error message * @returns {Object} */ createResponseBoby (response, error, message) { return RestUtil.createResponseBoby(response, error, message) } /** * Find object by id. * * @param {Object} req - server request * @param {Object} res - server response */ findById (req, res, next) { if (typeof this.service.findById !== 'function') { throw new TypeError('Service doesn\'t have "findById" method.') } let ths = this new ParamsValidator([ { name: 'id', value: req.params.id, type: ParamValidator.OBJECT_ID, required: true } ]).validate() .flatMap(result => ths.service.findById(result.id)) .flatMap(data => RestUtil.dataToResponse(data)) .subscribe( data => res.json(ths.createResponseBoby(data)), err => next(err)) } /** * Get list of all objects. * * @param {Object} req - server request * @param {Object} res - server response * @param {function} next */ find (req, res, next) { if (typeof this.service.find !== 'function') { throw new TypeError('Service doesn\'t have "find" method.') } // TODO: Unchecked url params logger.warn('Unchecked url params') let ths = this this.service.find({}) .flatMap(data => RestUtil.dataToResponse(data)) .subscribe( data => res.json(ths.createResponseBoby(data)), err => next(err)) } /** * Create new object. * * @param {Object} req - server request * @param {Object} res - server response * @param {function} next */ create(req, res, next) { if (typeof this.service.create !== 'function') { throw new TypeError('Service doesn\'t have "create" method.') } let ths = this this.validateCreateParams(req.body) .flatMap(params => ths.service.create(params)) .flatMap((model, numAffected) => RestUtil.dataToResponse(model)) .subscribe( data => res.json(ths.createResponseBoby(data)), err => next(err)) } /** * Update object by id. * * @param {Object} req - server request * @param {Object} res - server response * @param {function} next */ update (req, res, next) { if (typeof this.service.update !== 'function') { throw new TypeError('Service doesn\'t have "update" method.') } // TODO: Unchecked req.body logger.warn('Unchecked req.body') let ths = this new ParamsValidator([ { name: 'id', value: req.params.id, type: ParamValidator.OBJECT_ID, required: true } ]).validate() .flatMap(result => ths.service.update(result.id, req.body)) .flatMap(data => RestUtil.dataToResponse(data)) .subscribe( data => res.json(ths.createResponseBoby(data)), err => next(err)) } /** * Remove object by id. * * @param {Object} req - server request * @param {Object} res - server response * @param {function} next */ remove (req, res, next) { if (typeof this.service.remove !== 'function') { throw new TypeError('Service doesn\'t have "remove" method.') } let ths = this new ParamsValidator([ { name: 'id', value: req.params.id, type: ParamValidator.OBJECT_ID, required: true } ]).validate() .flatMap(result => ths.service.remove(result.id)) .flatMap(data => RestUtil.dataToResponse(data)) .subscribe( data => res.json(ths.createResponseBoby(data)), err => next(err)) } } module.exports = AbstractController <file_sep>/app/index.js const logger = require('./logger')(module) const db = require('./store').db const server = require('./server').server(__dirname) const init = require('./server/init') db.connect() .flatMap(() => server.run()) .subscribe( () => {}, err => logger.error(err), () => logger.info('System was started.') /* init() */ )<file_sep>/app/auth/auth-controller.js const Observable = require('rx').Observable const RestUtil = require('../rest/rest-util') const userService = require('../user/user-service') const tokenService = require('../token/token-service') const ParamsValidator = require('../validation/params-validator') const ParamValidator = require('../validation/param-validator') const HttpError401 = require('../rest/error/http-error-401') class AuthController { /** * Login. * * @param {Object} req - server request * @param {Object} res - server response * @param {function} next */ login (req, res, next) { let ths = this let params = {} new ParamsValidator([ { name: 'login', value: req.body.username, type: ParamValidator.STRING, required: true }, { name: 'password', value: req.body.password, type: ParamValidator.STRING, required: true }, { name: 'remember', value: req.body.remember, type: ParamValidator.BOOLEAN } ]).validate() .flatMap(result => { params = result return userService.findByLogin(params.login) }) .flatMap(user => ths._checkUser(user, params.password)) .flatMap(user => tokenService.create(user, params.remember)) .flatMap(token => tokenService.get(token)) .flatMap(token => RestUtil.dataToResponse(token)) .subscribe( token => res.json(RestUtil.createResponseBoby(token, false)), err => next(err)) } /** * Logout. * * @param {Object} req - server request * @param {Object} res - server response * @param {function} next */ logout (req, res, next) { tokenService.disable(req.user.token) .subscribe( token => res.json(RestUtil.createResponseBoby(null, false)), err => next(err)) } /** * */ _checkUser (user, password) { if (!user) { return Observable.throw(new HttpError401('User not found.')) } return user.comparePassword(password) .flatMap(isMatch => isMatch ? Observable.return(user) : Observable.throw(new HttpError401('Incorrect password.'))) } } module.exports = new AuthController() <file_sep>/app/geo/geo-controller.js const geoService = require('./geo-service') const RestUtil = require('../rest/rest-util') class GeoController { /** * @param {Object} req - server request * @param {Object} res - server response * @param {function} next */ find(req, res, next) { geoService.find(req.params.name) .subscribe( data => res.json(RestUtil.createResponseBoby(data)), err => next(err)) } } module.exports = new GeoController()<file_sep>/app/message/message-service.js const AbstractService = require('../store').AbstractService const Message = require('./message') const Rx = require('rx') class MessageService extends AbstractService { constructor() { super(Message) } /** * @returns {Observable<Message>} */ createNewInstance(data) { return Rx.Observable.return(new Message(data)); } find(params, projection, options) { let self = this return Rx.Observable.create(observer => { self.clazz .find(params, projection, options) .populate('sender') .populate('recipient') .exec((err, msg) => { if (err) { observer.onError(err) } else { observer.onNext(msg) observer.onCompleted() } }); }); } /** * Get object by id. * * @param {string|ObjectId} id - the identifier of the desired object. * @returns {Observable<Object>} */ findById(id) { let self = this return Rx.Observable.create(observer => { self.clazz .findById(id) .populate('sender') .populate('recipient') .exec((err, msg) => { if (err) { observer.onError(err) } else { observer.onNext(msg) observer.onCompleted() } }); }); } read(id, recipient) { let body = { read: true } let cond = { _id: id, recipient: recipient } let options = { new: true } let source = Rx.Observable.fromNodeCallback(this.clazz.findOneAndUpdate, this.clazz) return source(cond, body, options) } } module.exports = new MessageService()<file_sep>/app/rest/rest-util.js const Rx = require('rx') class RestUtil { /** * Create response. * * @param {Object} response - data for the response. * @param {Error} error * @param {string} message - error message * @param {nubmber} code - internal error code * @returns {Object} */ static createResponseBoby (response, error, message, code) { return error ? { response: null, error: true, message: message, internalCode: code } : { response: response, error: false } } static addCountToBody(response, count) { response.count = count return response } /** * Create error response. * * @param {string} message - error message. * @param {nubmber} code - internal error code. * @returns {Object} */ static createErrorResBoby (message, code) { return RestUtil.createResponseBoby(null, true, message, code) } /** * Create response from error. * * @param {Error} error - error. * @returns {Object} */ static createResBobyFromError (error) { return RestUtil.createErrorResBoby(error.message, error.code) } /** * Convert object or list of objects to response. * Object have to have "toResponse" method. * * @param {Object|Array<Object>} data * * @returns {Observable<Object>|Observable<Array<Object>>} */ static dataToResponse (data) { return Array.isArray(data) ? Rx.Observable.from(data).map(el => el.toResponse()).toArray() : Rx.Observable.return(data ? data.toResponse() : null) } } module.exports = RestUtil <file_sep>/app/request/request.js const mongoose = require('mongoose') const Point = require('../point/point') const properties = { kind: { type: String, required: true }, service: { type: String, required: true }, seatsNumber: { type: Number, required: true }, transport: { type: String, required: true }, name: { type: String }, width: { type: Number }, height: { type: Number }, length: { type: Number }, weight: { type: Number }, displayEmail: { type: Boolean, default: false, required: true }, displayPhone: { type: Boolean, default: false, required: true }, points: [ 'Point' ], user: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true }, comment: { type: String }, enabled: { type: Boolean, default: true }, creationDate: { type: Date, default: new Date(), required: true } } const schema = new mongoose.Schema(properties) schema.methods = { /** * Convert object of this class to simple response object. * * @return {object} */ toResponse: function () { let obj = {} obj.id = this._id obj.kind = this.kind obj.service = this.service obj.seatsNumber = this.seatsNumber obj.transport = this.transport obj.name = this.name obj.width = this.width obj.height = this.height obj.length = this.length obj.weight = this.weight obj.displayEmail = this.displayEmail obj.displayPhone = this.displayPhone if(this.user._id) { obj.user = this.user._id obj.userName = this.user.getFullName() obj.phone = this.displayPhone ? this.user.phone : undefined obj.email = this.displayEmail ? this.user.email : undefined } else { obj.user = obj.user } obj.comment = this.comment obj.enabled = this.enabled obj.creationDate = this.creationDate obj.points = []; for(let point of this.points) { obj.points.push(Point.toResponse(point)) } return obj } } schema.pre('save', function (next) { for(let i = 0; i < this.points.length; i++) { this.points[i].length = this.points.length } next() }) module.exports = mongoose.model('Request', schema) <file_sep>/app/message/message.js const mongoose = require('mongoose') const properties = { sender: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true }, recipient: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true }, text: { type: String, required: true, maxlength: 1000 }, date: { type: Date, default: new Date(), required: true }, read: { type: Boolean, default: false } } const schema = new mongoose.Schema(properties) schema.methods = { /** * Convert object of this class to simple response object. * * @return {object} */ toResponse: function (extended) { let obj = {} obj.id = this._id; if(this.sender._id) { obj.sender = this.sender._id; obj.senderName = this.sender.getFullName(); } else { obj.sender = this.sender; } if(this.recipient._id) { obj.recipient = this.recipient._id; obj.recipientName = this.recipient.getFullName(); } else { obj.recipient = this.recipient; } obj.text = this.text; obj.date = this.date; obj.read = this.read; return obj } } module.exports = mongoose.model('Message', schema) <file_sep>/app/server/server.js const bodyParser = require('body-parser') const config = require('../config') const express = require('express') const logger = require('../logger')(module) const namespace = require('express-namespace') const Rx = require('rx') const errorsHandler = require('./errors-handler') const cors = require('cors') const app = express() /** * Define all middleware here. */ function defineMiddleware () { app.use(bodyParser.json()) app.use(bodyParser.urlencoded({ extended: true })) app.use(httpMethodWatcher) require('../auth/auth-init')() registerRouters() errorsHandler(app) } function httpMethodWatcher (req, res, next) { logger.info('%s -> "%s"', req.method, req.path) next() } /** * Register routers. */ function registerRouters () { app.options('*', cors()) require('../auth').routing(app) require('../user').routing(app) require('../request').routing(app) require('../dictionary/dictionary-routing')(app) require('../geo/geo-routing')(app) require('../message/message-routing')(app) } module.exports = function (rootDir) { defineMiddleware() return { /** * Run server (info about host and port see config.json). * * @returns {Observable} */ run: () => { return Rx.Observable.create(observer => { let port = config.get('server:port') let host = config.get('server:host') app.listen(port, host, () => { logger.info('The server running at "http://%s:%d/"', host, port) observer.onNext() observer.onCompleted() }).on('error', err => { logger.error(err) observer.onError(err) }) }) } } } <file_sep>/app/rest/index.js module.exports = { Routing: require('./routing'), Route: require('./route'), RestUtil: require('./rest-util'), AbstractController: require('./abstract-controller') } <file_sep>/app/token/token.js const mongoose = require('mongoose') const AuthUtil = require('../auth/auth-util') const config = require('../config') const properties = { accessToken: { type: String, required: true, unique: true }, creationDate: { type: Date, default: new Date(), required: true }, expires: { type: Number, required: true }, enabled: { type: Boolean, default: true }, user: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true } } const schema = new mongoose.Schema(properties) schema.statics = { /** * Create token properties by params. * * @param {User} user * @param {bool} remember * @returns {Object} */ newProperties: function (user, remember) { return { accessToken: AuthUtil.genToken(config.get('auth:tokenLength')), expires: remember ? config.get('auth:rememberLong') : config.get('auth:rememberShort'), user: user._id, } } } schema.methods = { /** * Convert object of this class to simple response object. * * @returns {Object} */ toResponse: function () { let obj = {} obj.accessToken = this.accessToken obj.expires = this.expires obj.scope = this.user ? this.user.scope : 'user'; obj.user = this.user ? this.user._id : undefined; return obj }, /** * Expires checking * * @returns {bool} */ isExpired: function () { let startTime = this.creationDate.getTime() let finishTime = startTime + this.expires let currentTime = new Date().getTime() return currentTime > finishTime } } module.exports = mongoose.model('Token', schema) <file_sep>/app/message/message-routing.js const ctrl = require('./message-controller') const Routing = require('../rest').Routing const Route = require('../rest').Route const namespase = '/messages' const routes = [ { method: Route.GET, path: '/', protection: '*', handler: (req, res, next) => ctrl.find(req, res, next) }, { method: Route.GET, path: '/:id', protection: '*', handler: (req, res, next) => ctrl.findById(req, res, next) }, { method: Route.POST, path: '/', protection: '*', handler: (req, res, next) => ctrl.create(req, res, next) }, { method: Route.GET, path: '/box/in', protection: '*', handler: (req, res, next) => ctrl.inbox(req, res, next) }, { method: Route.GET, path: '/box/out', protection: '*', handler: (req, res, next) => ctrl.outbox(req, res, next) }, { method: Route.GET, path: '/box/read/:id', protection: '*', handler: (req, res, next) => ctrl.read(req, res, next) } ] module.exports = (app) => { new Routing(app, namespase, routes).commit() } <file_sep>/app/dictionary/dictionary.js const mongoose = require('mongoose') const properties = { key: { type: String, required: true }, value: { type: String, required: true }, type: { type: String, required: true }, description: String } const schema = new mongoose.Schema(properties) schema.methods = { /** * Convert object of this class to simple response object. * * @return {object} */ toResponse: function (extended) { let obj = {} obj.id = this._id; obj.key = this.key; obj.value = this.value; obj.type = this.type; obj.description = this.description; return obj } } const Dictionary = mongoose.model('Dictionary', schema) Dictionary.LANGUAGE = 'language' Dictionary.COUNTRY = 'country' Dictionary.REQUEST_KIND = 'request-kind' Dictionary.REQUEST_SERVICE = 'request-service' Dictionary.TRANSPORT = 'transport' module.exports = Dictionary <file_sep>/app/message/message-controller.js const AbstractController = require('../rest').AbstractController const messageService = require('./message-service') const RestUtil = require('../rest/rest-util') class MessageController extends AbstractController { constructor () { super(messageService) } create(req, res, next) { let ths = this let params = req.body params.sender = req.user._id params.read = false params.date = new Date() this.service.create(params) .flatMap((model, numAffected) => RestUtil.dataToResponse(model)) .subscribe( data => res.json(ths.createResponseBoby(data)), err => next(err)) } inbox(req, res, next) { let ths = this let params = { recipient: req.user._id } this.service.find(params, null, { sort: { date: -1 }}) .flatMap(data => RestUtil.dataToResponse(data)) .subscribe( data => res.json(ths.createResponseBoby(data)), err => next(err)) } outbox(req, res, next) { let ths = this let params = { sender: req.user._id } this.service.find(params, null, { sort: { date: -1 }}) .flatMap(data => RestUtil.dataToResponse(data)) .subscribe( data => res.json(ths.createResponseBoby(data)), err => next(err)) } read(req, res, next) { let ths = this ths.service.read(req.params.id, req.user._id) .flatMap(data => RestUtil.dataToResponse(data)) .subscribe( data => res.json(ths.createResponseBoby(data)), err => next(err)) } } module.exports = new MessageController() <file_sep>/app/auth/auth-util.js const bcrypt = require('bcrypt') const Rx = require('rx') const randtoken = require('rand-token') class AuthUtil { /** * Generate salt by salt round. * * @param {number} saltRounds * @return {Observable<string>} */ static genSalt (saltRounds) { return Rx.Observable.fromNodeCallback(bcrypt.genSalt)(saltRounds) } /** * Generate hash for string by the salt. * * @param {string} str * @param {string} salt * @return {Observable<string>} */ static genHash (str, salt) { return Rx.Observable.fromNodeCallback(bcrypt.hash)(str, salt) } /** * Compare original string to hashed. * * @param {string} original - original string * @param {string} hashed - hashed string * @return {Observable<bool>} */ static compareHashed (original, hashed) { return Rx.Observable.fromNodeCallback(bcrypt.compare)(original, hashed) } /** * Generate hash for string. * * @param {string} str * @param {number} saltRounds * @return {Observable<string>} */ static genHashedString (str, saltRounds) { return AuthUtil .genSalt(saltRounds) .flatMap(salt => AuthUtil.genHash(str, salt)) } /** * Generate token by the length * * @param {number} length */ static genToken (length) { return randtoken.generate(length) } } module.exports = AuthUtil <file_sep>/app/geo/geo.js const config = require('../config') class Geo { constructor(name, fullName, latitude, longitude, placeId) { this.name = name this.fullName = fullName this.latitude = latitude this.longitude = longitude this.placeId = placeId; } } module.exports = Geo<file_sep>/app/auth/index.js module.exports = { AuthUtil: require('./auth-util'), routing: require('./auth-routing'), controller: require('./auth-controller'), init: require('./auth-init') } <file_sep>/app/user/user-routing.js const ctrl = require('./user-controller') const Routing = require('../rest').Routing const Route = require('../rest').Route const namespase = '/users' const routes = [ { method: Route.GET, path: '/profile', straight: true, protection: '*', handler: (req, res, next) => ctrl.profile(req, res, next) }, { method: Route.POST, path: '/profile', straight: true, handler: (req, res, next) => ctrl.createProfile(req, res, next) }, { method: Route.PUT, path: '/profile', straight: true, protection: '*', handler: (req, res, next) => ctrl.updateProfile(req, res, next) }, { method: Route.GET, path: '/', handler: (req, res, next) => ctrl.find(req, res, next) }, { method: Route.GET, path: '/filter', handler: (req, res, next) => ctrl.filter(req, res, next) }, { method: Route.GET, path: '/:id', protection: '*', handler: (req, res, next) => ctrl.findById(req, res, next) }, { method: Route.POST, path: '/', protection: 'admin', handler: (req, res, next) => ctrl.create(req, res, next) }, { method: Route.PUT, path: '/:id', protection: 'admin', handler: (req, res, next) => ctrl.update(req, res, next) } ] module.exports = (app) => { new Routing(app, namespase, routes).commit() } <file_sep>/app/point/point.js const mongoose = require('mongoose') const properties = { latitude: {type: Number, required: true }, longitude: { type: Number, required: true }, name: { type: String }, radius: { type: Number }, radiusUnitFactor: { type: Number }, start: { type: Boolean, default: false, required: true }, end: { type: Boolean, default: false, required: true }, arrivalDatetime: { type: Date, required: true }, departureDatetime: { type: Date, required: true }, order: { type: Number, required: true }, placeId: { type: String }, editable: { type: Boolean, default: true }, enabled: { type: Boolean, default: true }, length: { type: Number }, creationDate: { type: Date, default: new Date(), required: true } } const schema = new mongoose.Schema(properties) schema.statics = { toResponse: function (point) { let obj = {} obj.id = point._id obj.latitude = point.latitude obj.longitude = point.longitude obj.name = point.name obj.radius = point.radius obj.radiusUnitFactor = point.radiusUnitFactor obj.start = point.start obj.end = point.end obj.arrivalDatetime = point.arrivalDatetime obj.departureDatetime = point.departureDatetime obj.order = point.order obj.placeId = point.placeId obj.editable = point.editable obj.enabled = point.enabled obj.creationDate = point.creationDate return obj; } } schema.methods = { /** * Convert object of this class to simple response object. * * @return {object} */ toResponse: function () { return this.toResponse(this); } } module.exports = mongoose.model('Point', schema)<file_sep>/app/store/store.js const config = require('../config') const mongoose = require('mongoose') const Database = require('./database') const Promise = require('promise') mongoose.Promise = Promise let db = new Database( mongoose, config.get('db:uri'), config.get('db:options') ) module.exports = db <file_sep>/app/rest/routing.js const Route = require('./route') const logger = require('../logger')(module) const passport = require('passport') class Routing { /** * @typedef Raw * @property {string} method - type of the method (GET, POST, PUT ...). * @property {string} path - url. * @property {bool} straight - if it is true, route path exactly matches defined path. * @property {bool|string|Array<string>} protection - if it's true or defined scope, * route is protected (available strings: *, admin, user). * @property {function} handler - processing request middleware. */ /** * @param {Object} app - expressJS app. * @param {string} namespace - namespace of the routing. * @param {Array<Raw>} raws - raw routing objects. */ constructor (app, namespace, raws) { this.app = app this.namespace = namespace this.routesWithNamespace = [] this.routesWithoutNamespace = [] this._createRoutesFromRaws(raws) } /** * @private * Create routing objects from {@link Routing#raws} * array of route data. * * @param {Array<Raw>} raws - raw routing objects. */ _createRoutesFromRaws (raws) { if (raws && Array.isArray(raws)) { for (let raw of raws) { let protect = raw.protection ? passport.authenticate('bearer', { session: false }) : null let scope = raw.protection ? this._createScopeMiddleware(raw.protection) : null let route = new Route(raw.method, raw.path, protect, scope, raw.handler, raw.straight) this.addRoute(route) } } } _createScopeMiddleware (scope) { if (scope && (typeof scope === 'boolean' || scope instanceof Boolean)) { return passport.scope('*') } if (scope && (Array.isArray(scope) || typeof scope === 'string' || scope instanceof String)) { return passport.scope(scope) } return null } /** * Add route to the list applying. * Route won't apply, to apply needs to call {@link Routing#commit}. * * @param {Route} route */ addRoute (route) { route.straight ? this.routesWithoutNamespace.push(route) : this.routesWithNamespace.push(route) } /** * Apply all routing methods to the app. */ commit () { let ths = this for (let route of this.routesWithoutNamespace) { this._registerRoute(route) } this.app.namespace(this.namespace, () => { for (let route of this.routesWithNamespace) { ths._registerRoute(route) } }) } /** * Register route in the app by the method. * * @param {Route} route - local route. * @private */ _registerRoute (route) { switch (route.method) { case Route.GET: this._registerMethod(this.app.get, route) break case Route.POST: this._registerMethod(this.app.post, route) break case Route.PUT: this._registerMethod(this.app.put, route) break case Route.DELETE: this._registerMethod(this.app.delete, route) break default: logger.error('Unknown route (namespace=[%s]): %s', route.straight ? '' : this.namespace, route.toString()) logger.error('Add this method to the {rest.Routing#_registerRoute}') throw new TypeError('Unknown route method.') } } /** * Apply router method to the app. * * @param {function} fn - app router function. * @param {Route} route - local route. * @private */ _registerMethod (fn, route) { fn.apply(this.app, route.toArguments()) let pr = route.protection ? '(-)' : '(+)' logger.info('Mapped: %s -> %s -> %s%s', pr, route.method, route.straight ? '' : this.namespace, route.path) } } module.exports = Routing <file_sep>/README.md # Simple Logistics (server) Simple logistics web server application. ## Getting Started ### Prerequisities ### Installing 1. Download or clone project: ``` git clone https://github.com/andrei-radzetski/simple-logistics-server.git ``` 2. Move to the project directory and install the project: ``` npm install ``` 3. Run the starting script: ``` npm start ``` ## Authors * **<NAME>** - [Github](https://github.com/andrei-radzetski), [Facebook](https://www.facebook.com/stels666) <file_sep>/app/server/errors-handler.js const logger = require('../logger')(module) const RestUtil = require('../rest/rest-util') const MongoErrors = require('mongo-errors') const HttpError = require('../rest/error/http-error') const HttpError404 = require('../rest/error/http-error-404') const HttpError500 = require('../rest/error/http-error-500') const ValidationError = require('../validation/validation-error') module.exports = app => { /** * Handle page not found error. */ app.use((req, res) => { throw new HttpError404() }) /** * Handle ValidationError */ app.use((err, req, res, next) => { if (!(err instanceof ValidationError)) { return next(err) } logger.warn(err.message) res.status(400).json(RestUtil.createErrorResBoby(err.message)) }) /** * Handle MongoError */ app.use((err, req, res, next) => { if (err.name !== 'MongoError') { return next(err) } switch (err.code) { case MongoErrors.DuplicateKey: logger.error(err.message) return res.status(400) .json(RestUtil.createErrorResBoby('User with such parameters already exists.', err.code)) default: logger.error('Unknown MongoError code: ' + err.code) return next(err) } }) /** * Handle HttpError500 */ app.use((err, req, res, next) => { if (!(err instanceof HttpError500)) { return next(err) } logger.error(err.toString()) res.status(err.code).json(RestUtil.createErrorResBoby(err.message)) }) /** * Handle HttpError */ app.use((err, req, res, next) => { if (!(err instanceof HttpError)) { return next(err) } logger.warn(err.message) res.status(err.code).json(RestUtil.createErrorResBoby(err.message)) }) /** * Handle Error */ app.use((err, req, res, next) => { logger.error(err) res.status(500).json(RestUtil.createErrorResBoby('Internal Server Error')) }) }<file_sep>/app/auth/auth-routing.js const ctrl = require('./auth-controller') const Routing = require('../rest').Routing const Route = require('../rest').Route const namespase = '/auth' const routes = [ { method: Route.POST, path: '/login', straight: true, handler: (req, res, next) => ctrl.login(req, res, next) }, { method: Route.GET, path: '/logout', straight: true, protection: '*', handler: (req, res, next) => ctrl.logout(req, res, next) } ] module.exports = (app) => { new Routing(app, namespase, routes).commit() } <file_sep>/app/rest/error/http-error-400.js const HttpError = require('./http-error') /** * 400 Bad Request. */ class HttpError400 extends HttpError { constructor (message) { message = message != null ? message : 'Bad Request' super(400, message) this.name = this.constructor.name this.message = message if (typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, this.constructor) } else { this.stack = (new Error(message)).stack } } } module.exports = HttpError400 <file_sep>/app/validation/params-validator.js const ParamValidator = require('./param-validator') const ValidationError = require('./validation-error') const Observable = require('rx').Observable class ParamsValidator { /** * @typedef RawParam * @property {string} name - param name. * @property {Object|undefined} value - value of the param. * @property {string} type - type of the param (ParamValidator.EMAIL, ParamValidator.PHONE ... ) * @property {boolean} required - requirement of the param. * @property {function} condition - aditional validation condition. */ /** * @param {Array<RawParam>} raws */ constructor (raws) { if (raws == null || !Array.isArray(raws)) { throw new TypeError('Argument "raws" must be array.') } this.params = [] this._init(raws) } /** * Initialize params validator. */ _init (raws) { for (let raw of raws) { this.params.push(new ParamValidator(raw.name, raw.value, raw.type, raw.required, raw.condition)) } } /** * Validate params, if valid return object * of values ({ fieldname1: fieldvalue1, fieldname2: fieldvalue2, ... } * if invalid throw error. * * @return {Observable} */ validate () { return Observable.fromArray(this.params) .filter(param => !param.validate()) .map(param => param.createMessage()) .toArray() .flatMap(array => { return array != null && array.length > 0 ? Observable.throw(new ValidationError(array.join('; '))) : Observable.fromArray(this.params) }) .reduce((acc, x) => { if(x.value != null) { acc[x.name] = x.value } return acc }, {}) } } module.exports = ParamsValidator <file_sep>/app/rest/error/http-error-401.js const HttpError = require('./http-error') /** * 401 Unauthorized. */ class HttpError401 extends HttpError { constructor (message) { message = message != null ? message : 'Unauthorized' super(401, message) this.name = this.constructor.name this.message = message if (typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, this.constructor) } else { this.stack = (new Error(message)).stack } } } module.exports = HttpError401 <file_sep>/app/request/index.js module.exports = { routing: require('./request-routing'), controller: require('./request-controller'), service: require('./request-service') } <file_sep>/app/rest/route.js const cors = require('cors') class Route { static get GET () { return 'GET' } static get POST () { return 'POST' } static get PUT () { return 'PUT' } static get DELETE () { return 'DELETE' } /** * @property {string} method - type of the method (GET, POST, PUT ...). * @property {string} path - url. * @property {function} protection - protecting middleware. * @property {function} scope - scope protection middleware. * @property {function} handler - processing request middleware. * @property {bool} straight - if it is true, route path exactly matches defined path. */ constructor (method, path, protection, scope, handler, straight) { this.method = method this.path = path this.protection = protection this.scope = scope this.handler = handler this.straight = straight } /** * Create array of arguments to register route function. * If protect middleware isn't null, array consists of tree * elements (first - path, second - protection, third - handler), * otherwise array consists of two elemens * (first - path, second - handler). * * @returns {Array<Object>} */ toArguments () { return this.protection != null ? [this.path, cors(), this.protection, this.scope, this.handler] : [this.path, cors(), this.handler] } toString () { return this.method + ' -> "' + this.path + '"' } } module.exports = Route <file_sep>/app/token/index.js module.exports = { Token: require('./token'), service: require('./token-service') } <file_sep>/app/validation/param-validator.js const ValidationUtil = require('./validation-util') const logger = require('../logger')(module) class ParamValidator { static get EMAIL () { return 'EMAIL' } static get PHONE () { return 'PHONE' } static get STRING () { return 'STRING' } static get NUMBER () { return 'NUMBER' } static get BOOLEAN () { return 'BOOLEAN' } static get OBJECT_ID () { return 'OBJECT_ID' } /** * @param {string} name - param name. * @param {Object|undefined} value - value of the param. * @param {string} type - type of the param (EMAIL, PHONE ... see above) * @param {boolean} required - requirement of the param. * @param {function} condition - aditional validation condition. */ constructor (name, value, type, required, condition) { if (!ValidationUtil.isString(name)) { throw new TypeError('Field "name" must have string type.') } if (!ValidationUtil.isString(type)) { throw new TypeError('Field "type" must have string type.') } this.name = name this.value = ValidationUtil.isString(value) && ValidationUtil.isStringBlank(value) ? null : value this.type = type this.required = !!required this.condition = ValidationUtil.isFunction(condition) ? condition : null this.error = false this.message = null } /** * @returns {boolean} */ validate () { let exists = this._validateRequired() if (this.required && !exists) { return this._markAsError(' is undefined') } if (exists && !this._validateType()) { return this._markAsError(' isn\'t ' + this.type) } if (this.condition != null && !this.condition(this.value)) { return this._markAsError(' is wrong') } this.value = exists ? ParamValidator.convert(this.value, this.type) : this.value return this._markAsValid() } /** * @private * Validate field by the required. * * @returns {boolean} */ _validateRequired () { switch (this.type) { case ParamValidator.EMAIL: case ParamValidator.PHONE: case ParamValidator.STRING: return !ValidationUtil.isStringBlank(this.value) case ParamValidator.NUMBER: return this.value != null case ParamValidator.BOOLEAN: return this.value != null case ParamValidator.OBJECT_ID: return !ValidationUtil.isStringBlank(this.value) default: throw new TypeError('Unknown type "' + this.type + '"') } } /** * @private * Validate field by the type. * * @returns {boolean} */ _validateType () { switch (this.type) { case ParamValidator.EMAIL: return ValidationUtil.isEmail(this.value) case ParamValidator.PHONE: return ValidationUtil.isPhone(this.value) case ParamValidator.STRING: return ValidationUtil.isString(this.value) case ParamValidator.NUMBER: return ValidationUtil.isNumber(this.value, true) case ParamValidator.BOOLEAN: return ValidationUtil.isBoolean(this.value, true) case ParamValidator.OBJECT_ID: return ValidationUtil.isObjectId(this.value) default: throw new TypeError('Unknown type "' + this.type + '"') } } /** * Mark param as invalid. * All the time returns false. * * @return {boolean} */ _markAsError (message) { this.error = true this.message = message return false } /** * Mark param as valid. * All the time returns true. * * @return {boolean} */ _markAsValid () { this.error = false this.message = null return true } /** * Create message. Format "name" + "message". * @returns {string} */ createMessage () { return this.error ? ('"' + this.name + '"' + this.message) : null } /** * Conver the value to native type by user type (EMAIL, PHONE ...) * * @param {any} value * @param {string} type * * @return {any} */ static convert (value, type) { switch (type) { case ParamValidator.EMAIL: case ParamValidator.PHONE: case ParamValidator.STRING: return value.toString() case ParamValidator.NUMBER: // TODO: verify logger.warn('Not Verified') return Number(value) case ParamValidator.BOOLEAN: return ValidationUtil.isBoolean(value) ? value : value === 'true' case ParamValidator.OBJECT_ID: // TODO: verify logger.warn('Not Verified') return value.toString() default: throw new TypeError('Unknown type "' + type + '"') } } } module.exports = ParamValidator <file_sep>/app/geo/geo-service.js const config = require('../config') const request = require('request') const urlencode = require('urlencode') const Observable = require('rx').Observable const Geo = require('./geo') class GeoService { formUrl(name) { return 'https://maps.googleapis.com/maps/api/geocode/json?language=ru&types=locality|political&address=' + name + '&key=' + config.get('google:apiKey') } find(name) { return Observable.create(observer => { name = urlencode(name); var options = { url: this.formUrl(name) }; request(options, (error, response, body) => { if (error || response == null || response.statusCode != 200) { observer.onError(error) } else { observer.onNext(this.parse(body)) observer.onCompleted() } }) }) } parse(body) { let temp = JSON.parse(body) let geos = [] if (temp.results) { for (let tempGeo of temp.results) { if (tempGeo && tempGeo.formatted_address && tempGeo.geometry && tempGeo.geometry.location && tempGeo.geometry.location.lat && tempGeo.geometry.location.lng && tempGeo.address_components && tempGeo.address_components[0] && tempGeo.address_components[0].long_name && tempGeo.place_id) geos.push(new Geo(tempGeo.address_components[0].long_name, tempGeo.formatted_address, tempGeo.geometry.location.lat, tempGeo.geometry.location.lng, tempGeo.place_id)) } } return geos } } module.exports = new GeoService()<file_sep>/app/user/user.js const mongoose = require('mongoose') const config = require('../config') const AuthUtil = require('../auth/auth-util') const logger = require('../logger')(module) const properties = { email: { type: String, required: true, unique: true, maxlength: 50 }, phone: { type: String, required: true, unique: true, maxlength: 13 }, password: { type: String, required: true }, firstName: { type: String, required: true, maxlength: 50 }, secondName: { type: String, required: true, maxlength: 50 }, country: { type: String, maxlength: 3 }, city: { type: String, maxlength: 50 }, language: { type: String, maxlength: 3 }, additionalInfo: { type: String, maxlength: 500 }, confirmed: { type: Boolean, default: true }, enabled: { type: Boolean, default: true }, creationDate: { type: Date, default: new Date(), required: true }, // *, admin, user scope: { type: String, default: 'user', required: true }/*, tokens: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Token' }] */ } const schema = new mongoose.Schema(properties) schema.methods = { /** * Convert object of this class to simple response object. * * @returns {Object} */ toResponse: function (extended) { let obj = {} obj.id = this._id obj.email = this.email obj.phone = this.phone obj.firstName = this.firstName obj.secondName = this.secondName obj.country = this.country obj.city = this.city obj.additionalInfo = this.additionalInfo if(extended) { obj.language = this.language obj.scope = this.scope obj.confirmed = this.confirmed } return obj }, getFullName() { return this.firstName + ' ' + this.secondName }, /** * Compare password. * * @param {string} password * @returns {Observable<bool>} */ comparePassword: function (password) { return AuthUtil.compareHashed(password, this.password) } } schema.pre('save', function (next) { // TODO: Unchecked format of email, phone, password, firstName, secondName logger.warn('Unchecked format of email, phone, password, firstName, secondName') var ths = this // only hash the password if it has been modified (or is new) if (!ths.isModified('password')) { return next() } /* * Generate password hash. */ AuthUtil.genHashedString(ths.password, config.get('auth:saltRounds')) .subscribe( hash => ths.password = hash, err => next(err), () => next()) }) module.exports = mongoose.model('User', schema)
48962420506c2b17af11b7b31234d0becb059015
[ "JavaScript", "Markdown" ]
36
JavaScript
andrei-radzetski/simple-logistics-server
f1114825cdb3210e83fecdd5e0c0ffd1fc962a9e
88bd62167ef9de04f950cb6d3712df6a25d49aaa
refs/heads/master
<file_sep>var Loginobj = require ('../PageObjects/loginobjects'); var KeyActions = require('../commom/KeyActions'); let properties = require('../Properties/Elmslocators.json'); var InputData = require('../InputData/elmsdata.json'); describe("Navigate to elms",function() { it("Validate with Invalid username and pswd",function(){ browser.get(properties.ElmsLocators.URL); browser.driver.manage().window().maximize(); //browser.get("http://pre-prod.hbfxlabs.com/"); browser.sleep(3000); KeyActions.TypeTextWhenElementVisible(Loginobj.UserName,InputData.AppInputData.Invaliduserpswd.username); KeyActions.TypeTextWhenElementVisible(Loginobj.Password,InputData.AppInputData.Invaliduserpswd.password); KeyActions.clickWhenClickable(Loginobj.Login); browser.sleep(2000); //console.log(KeyActions.getTextValueElementVisible(Loginobj.Invalid)); expect(KeyActions.getTextValueElementVisible(Loginobj.Invaliduserpswd)).toEqual("Invalid Credentials"); }) })<file_sep>var properties = require('../Properties/Elmslocators.json') var Userobj = function(){ }; Userobj.prototype = Object.create({},{ clickuser:{ get: function(){ return element(by.xpath(properties.ElmsLocators.User.clickuser)); } }, Adduser:{ get:function(){ return element(by.xpath(properties.ElmsLocators.User.adduser)); } }, Uname:{ get:function(){ return element(by.xpath(properties.ElmsLocators.User.name)); } }, Userpswd:{ get:function(){ return element(by.xpath(properties.ElmsLocators.User.pswd)); } }, Fname:{ get:function(){ return element(by.xpath(properties.ElmsLocators.User.fname)); } }, Lname:{ get:function(){ return element(by.xpath(properties.ElmsLocators.User.lname)); } }, Email:{ get:function(){ return element(by.xpath(properties.ElmsLocators.User.email)); } }, Searchadds:{ get:function(){ return element(by.id(properties.ElmsLocators.User.searchaddress)); } }, Contactnum:{ get:function(){ return element(by.xpath(properties.ElmsLocators.User.mobilenum)); } }, Desc:{ get:function(){ return element(by.xpath(properties.ElmsLocators.User.description)); } } }); module.exports = new Userobj(); <file_sep>var properties = require('../Properties/Elmslocators.json'); var courseobj = function(){ }; courseobj.prototype = Object.create({},{ clickcourse:{ get: function(){ return element(by.xpath(properties.ElmsLocators.Courses.clickcourse)); } }, addcourse:{ get: function(){ return element(by.xpath(properties.ElmsLocators.Courses.addcour)); } }, parentcourse:{ get: function(){ return element(by.xpath(properties.ElmsLocators.Courses.parntcours)); } }, selectcourse:{ get:function(){ return element(by.xpath(properties.ElmsLocators.Courses.selectcours)); } }, coursename:{ get:function(){ return element(by.xpath(properties.ElmsLocators.Courses.coursename)); } }, Coursedesc:{ get:function(){ return element(by.xpath(properties.ElmsLocators.Courses.descr)); } } }); module.exports = new courseobj();<file_sep>var properties = require('../Properties/Elmslocators.json') var RoleObj = function () { }; RoleObj.prototype = Object.create({}, { Role: { get: function () { return element(by.xpath(properties.ElmsLocators.Roles.clickrole)); } }, AddRole:{ get: function (){ return element(by.xpath(properties.ElmsLocators.Roles.addrole)); } }, Rolename:{ get: function(){ return element(by.xpath(properties.ElmsLocators.Roles.rolename)); } }, Description:{ get: function(){ return element(by.xpath(properties.ElmsLocators.Roles.desc)); } } }); module.exports = new RoleObj();<file_sep>var AdminObj = require('../PageObjects/Organisationobj'); var KeyActions = require('../commom/KeyActions'); //const EC = protractor.ExpectedConditions; //var RoleObjs = ('../PageObjects/roleobj.js'); //var properties = require('../Properties/Elmslocators.json'); var InputData = require('../InputData/elmsdata.json'); //var login = require('../Test Cases/login.js'); describe("Navigate to Admin", function () { require('../Test Cases/Adminlogin.js'); it("Open Admin Page", function () { KeyActions.clickWhenClickable(AdminObj.Profilebtn); KeyActions.selectDropdownWhenVisible(AdminObj.Admin); KeyActions.clickWhenClickable(AdminObj.ClickOrg); KeyActions.clickWhenClickable(AdminObj.AddOrg); KeyActions.TypeTextWhenElementVisible(AdminObj.Organization, InputData.AppInputData.Organization.name); KeyActions.TypeTextWhenElementVisible(AdminObj.Code, InputData.AppInputData.Organization.code); KeyActions.clickWhenClickable(AdminObj.selectOrg); KeyActions.selectDropdownWhenVisible(AdminObj.ParentOrg); KeyActions.TypeTextWhenElementVisible(AdminObj.Phonenumber, InputData.AppInputData.Organization.Mobilenumber); KeyActions.TypeTextWhenElementVisible(AdminObj.Email, InputData.AppInputData.Organization.emailid); KeyActions.performAutoCompleteWhenElementVisible(AdminObj.SearchAddress, InputData.AppInputData.Organization.searchaddress, InputData.AppInputData.Organization.address_indexvalue); KeyActions.TypeTextWhenElementVisible(AdminObj.Domainnme, InputData.AppInputData.Organization.domain_name ); //element (by.xpath("//button[@class='primary-btn btn-white mat-raised-button']")).click(); // expect(AdminObj.UploadBanner.isDisplayed()).toBeTruthy(); browser.sleep(2000); KeyActions.clickWhenClickable(AdminObj.UploadBanner); //element (by.xpath("//input[@id='inputGroupFile04']")).click(); browser.sleep(2000); }) })<file_sep>var AdminObj = require('../PageObjects/Organisationobj'); var courseobj = require('../PageObjects/courseobj.js'); var KeyActions = require('../commom/KeyActions'); var InputData = require('../InputData/elmsdata.json'); describe ("Navigate to courses",function() { require('../Test Cases/Adminlogin.js'); it("Open course page",function() { KeyActions.clickWhenClickable(AdminObj.Profilebtn); KeyActions.selectDropdownWhenVisible(AdminObj.Admin); KeyActions.clickWhenClickable(courseobj.clickcourse); KeyActions.clickWhenClickable(courseobj.addcourse); KeyActions.clickWhenClickable(courseobj.parentcourse); KeyActions.selectDropdownWhenVisible(courseobj.selectcourse); KeyActions.TypeTextWhenElementVisible(courseobj.coursename,InputData.AppInputData.Courses.coursename); KeyActions.TypeTextWhenElementVisible(courseobj.Coursedesc,InputData.AppInputData.Courses.description); }) })<file_sep>var Loginobj = require ('../PageObjects/loginobjects'); var KeyActions = require('../commom/KeyActions'); let properties = require('../Properties/Elmslocators.json'); var InputData = require('../InputData/elmsdata.json'); describe("Navigate to elms",function() { it("Validate with Invalid Pswd",function(){ browser.get(properties.ElmsLocators.URL); browser.driver.manage().window().maximize(); //browser.get("http://pre-prod.hbfxlabs.com/"); browser.sleep(3000); KeyActions.TypeTextWhenElementVisible(Loginobj.UserName,InputData.AppInputData.Invalidpswd.username); KeyActions.TypeTextWhenElementVisible(Loginobj.Password,InputData.AppInputData.Invalidpswd.password); KeyActions.clickWhenClickable(Loginobj.Login); browser.sleep(2000); //console.log(KeyActions.getTextValueElementVisible(Loginobj.Invalid)); expect(KeyActions.getTextValueElementVisible(Loginobj.Invalidpswd)).toEqual("Invalid Credentials"); }) })<file_sep>var properties = require('../Properties/Elmslocators.json') var Loginobj = function(){ }; Loginobj.prototype = Object.create({},{ UserName:{ get:function(){ return element(by.id(properties.ElmsLocators.LoginDetails.username)); } }, Password:{ get:function(){ return element(by.id(properties.ElmsLocators.LoginDetails.password)); } }, Login:{ get:function(){ return element(by.css(properties.ElmsLocators.LoginDetails.Login)); } }, Invalid:{ get:function(){ return element(by.xpath(properties.ElmsLocators.Invaliduser.emailerrormsg)); } }, Invalidpswd:{ get:function(){ return element(by.xpath(properties.ElmsLocators.Invalidpswd.pswderrormsg)); } }, Emptypwsd:{ get:function(){ return element(by.xpath(properties.ElmsLocators.EmptyPswd.Pswdreq)); } }, Invaliduserpswd:{ get:function(){ return element(by.xpath(properties.ElmsLocators.Invaliduserpswd.Errormsg)); } } }); module.exports = new Loginobj();<file_sep># ProtractorDemoCode This Repo contains Protractor code <file_sep>var AdminObj = require('../PageObjects/Organisationobj'); var KeyActions = require('../commom/KeyActions'); var TopicObj = require('../PageObjects/topicobj.js'); var InputData = require('../InputData/elmsdata.json'); describe("Navigate to Topics",function() { require('../Test Cases/Adminlogin.js'); it("Open Topic Page",function() { KeyActions.clickWhenClickable(AdminObj.Profilebtn); KeyActions.selectDropdownWhenVisible(AdminObj.Admin); KeyActions.clickWhenClickable(TopicObj.clicktopic); KeyActions.clickWhenClickable(TopicObj.addtopic); KeyActions.TypeTextWhenElementVisible(TopicObj.topicname,InputData.AppInputData.Courses.topicname); KeyActions.TypeTextWhenElementVisible(TopicObj.topiccode,InputData.AppInputData.Courses.topiccode); KeyActions.TypeTextWhenElementVisible(TopicObj.Tpcdesc,InputData.AppInputData.Courses.desc); }) })<file_sep>var Loginobj = require ('../PageObjects/loginobjects'); var KeyActions = require('../commom/KeyActions'); let properties = require('../Properties/Elmslocators.json'); var InputData = require('../InputData/elmsdata.json'); describe("Navigate to ELMS", function(){ it("Open Login Page", function(){ // browser.get(properties.ElmsLocators.URL); browser.driver.manage().window().maximize(); browser.get("http://pre-prod.hbfxlabs.com/"); browser.sleep(3000); KeyActions.TypeTextWhenElementVisible(Loginobj.UserName,InputData.AppInputData.LoginData.username); KeyActions.TypeTextWhenElementVisible(Loginobj.Password,InputData.AppInputData.LoginData.password); KeyActions.clickWhenClickable(Loginobj.Login); browser.sleep(2000); }) })
bc8ca0e782e6f26ac050455fe23d034b319e25c4
[ "JavaScript", "Markdown" ]
11
JavaScript
Manasa646/ProtractorDemoCode
9596e8e5b0754373f935e4fce476cf3f17e38e02
b5cd5452fce17f706dd2eecfb0ad0622a040b7f1